OSDN Git Service

Delete unused source files for 1.98d.
[ffftp/ffftp.git] / contrib / putty / WINDOWS / WINDOW.C
diff --git a/contrib/putty/WINDOWS/WINDOW.C b/contrib/putty/WINDOWS/WINDOW.C
deleted file mode 100644 (file)
index cac7672..0000000
+++ /dev/null
@@ -1,5547 +0,0 @@
-/*\r
- * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal\r
- * emulator and backend in a window.\r
- */\r
-\r
-#include <stdio.h>\r
-#include <stdlib.h>\r
-#include <ctype.h>\r
-#include <time.h>\r
-#include <limits.h>\r
-#include <assert.h>\r
-\r
-#ifndef NO_MULTIMON\r
-#define COMPILE_MULTIMON_STUBS\r
-#endif\r
-\r
-#define PUTTY_DO_GLOBALS              /* actually _define_ globals */\r
-#include "putty.h"\r
-#include "terminal.h"\r
-#include "storage.h"\r
-#include "win_res.h"\r
-\r
-#ifndef NO_MULTIMON\r
-#include <multimon.h>\r
-#endif\r
-\r
-#include <imm.h>\r
-#include <commctrl.h>\r
-#include <richedit.h>\r
-#include <mmsystem.h>\r
-\r
-/* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of\r
- * wParam are used by Windows, and should be masked off, so we shouldn't\r
- * attempt to store information in them. Hence all these identifiers have\r
- * the low 4 bits clear. Also, identifiers should < 0xF000. */\r
-\r
-#define IDM_SHOWLOG   0x0010\r
-#define IDM_NEWSESS   0x0020\r
-#define IDM_DUPSESS   0x0030\r
-#define IDM_RESTART   0x0040\r
-#define IDM_RECONF    0x0050\r
-#define IDM_CLRSB     0x0060\r
-#define IDM_RESET     0x0070\r
-#define IDM_HELP      0x0140\r
-#define IDM_ABOUT     0x0150\r
-#define IDM_SAVEDSESS 0x0160\r
-#define IDM_COPYALL   0x0170\r
-#define IDM_FULLSCREEN 0x0180\r
-#define IDM_PASTE     0x0190\r
-#define IDM_SPECIALSEP 0x0200\r
-\r
-#define IDM_SPECIAL_MIN 0x0400\r
-#define IDM_SPECIAL_MAX 0x0800\r
-\r
-#define IDM_SAVED_MIN 0x1000\r
-#define IDM_SAVED_MAX 0x5000\r
-#define MENU_SAVED_STEP 16\r
-/* Maximum number of sessions on saved-session submenu */\r
-#define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)\r
-\r
-#define WM_IGNORE_CLIP (WM_APP + 2)\r
-#define WM_FULLSCR_ON_MAX (WM_APP + 3)\r
-#define WM_AGENT_CALLBACK (WM_APP + 4)\r
-#define WM_GOT_CLIPDATA (WM_APP + 6)\r
-\r
-/* Needed for Chinese support and apparently not always defined. */\r
-#ifndef VK_PROCESSKEY\r
-#define VK_PROCESSKEY 0xE5\r
-#endif\r
-\r
-/* Mouse wheel support. */\r
-#ifndef WM_MOUSEWHEEL\r
-#define WM_MOUSEWHEEL 0x020A          /* not defined in earlier SDKs */\r
-#endif\r
-#ifndef WHEEL_DELTA\r
-#define WHEEL_DELTA 120\r
-#endif\r
-\r
-static Mouse_Button translate_button(Mouse_Button button);\r
-static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);\r
-static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,\r
-                       unsigned char *output);\r
-static void cfgtopalette(void);\r
-static void systopalette(void);\r
-static void init_palette(void);\r
-static void init_fonts(int, int);\r
-static void another_font(int);\r
-static void deinit_fonts(void);\r
-static void set_input_locale(HKL);\r
-static void update_savedsess_menu(void);\r
-static void init_flashwindow(void);\r
-\r
-static int is_full_screen(void);\r
-static void make_full_screen(void);\r
-static void clear_full_screen(void);\r
-static void flip_full_screen(void);\r
-static int process_clipdata(HGLOBAL clipdata, int unicode);\r
-\r
-/* Window layout information */\r
-static void reset_window(int);\r
-static int extra_width, extra_height;\r
-static int font_width, font_height, font_dualwidth, font_varpitch;\r
-static int offset_width, offset_height;\r
-static int was_zoomed = 0;\r
-static int prev_rows, prev_cols;\r
-  \r
-static int pending_netevent = 0;\r
-static WPARAM pend_netevent_wParam = 0;\r
-static LPARAM pend_netevent_lParam = 0;\r
-static void enact_pending_netevent(void);\r
-static void flash_window(int mode);\r
-static void sys_cursor_update(void);\r
-static int get_fullscreen_rect(RECT * ss);\r
-\r
-static int caret_x = -1, caret_y = -1;\r
-\r
-static int kbd_codepage;\r
-\r
-static void *ldisc;\r
-static Backend *back;\r
-static void *backhandle;\r
-\r
-static struct unicode_data ucsdata;\r
-static int must_close_session, session_closed;\r
-static int reconfiguring = FALSE;\r
-\r
-static const struct telnet_special *specials = NULL;\r
-static HMENU specials_menu = NULL;\r
-static int n_specials = 0;\r
-\r
-static wchar_t *clipboard_contents;\r
-static size_t clipboard_length;\r
-\r
-#define TIMING_TIMER_ID 1234\r
-static long timing_next_time;\r
-\r
-static struct {\r
-    HMENU menu;\r
-} popup_menus[2];\r
-enum { SYSMENU, CTXMENU };\r
-static HMENU savedsess_menu;\r
-\r
-Config cfg;                           /* exported to windlg.c */\r
-\r
-static struct sesslist sesslist;       /* for saved-session menu */\r
-\r
-struct agent_callback {\r
-    void (*callback)(void *, void *, int);\r
-    void *callback_ctx;\r
-    void *data;\r
-    int len;\r
-};\r
-\r
-#define FONT_NORMAL 0\r
-#define FONT_BOLD 1\r
-#define FONT_UNDERLINE 2\r
-#define FONT_BOLDUND 3\r
-#define FONT_WIDE      0x04\r
-#define FONT_HIGH      0x08\r
-#define FONT_NARROW    0x10\r
-\r
-#define FONT_OEM       0x20\r
-#define FONT_OEMBOLD   0x21\r
-#define FONT_OEMUND    0x22\r
-#define FONT_OEMBOLDUND 0x23\r
-\r
-#define FONT_MAXNO     0x2F\r
-#define FONT_SHIFT     5\r
-static HFONT fonts[FONT_MAXNO];\r
-static LOGFONT lfont;\r
-static int fontflag[FONT_MAXNO];\r
-static enum {\r
-    BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT\r
-} bold_mode;\r
-static enum {\r
-    UND_LINE, UND_FONT\r
-} und_mode;\r
-static int descent;\r
-\r
-#define NCFGCOLOURS 22\r
-#define NEXTCOLOURS 240\r
-#define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)\r
-static COLORREF colours[NALLCOLOURS];\r
-static HPALETTE pal;\r
-static LPLOGPALETTE logpal;\r
-static RGBTRIPLE defpal[NALLCOLOURS];\r
-\r
-static HBITMAP caretbm;\r
-\r
-static int dbltime, lasttime, lastact;\r
-static Mouse_Button lastbtn;\r
-\r
-/* this allows xterm-style mouse handling. */\r
-static int send_raw_mouse = 0;\r
-static int wheel_accumulator = 0;\r
-\r
-static int busy_status = BUSY_NOT;\r
-\r
-static char *window_name, *icon_name;\r
-\r
-static int compose_state = 0;\r
-\r
-static UINT wm_mousewheel = WM_MOUSEWHEEL;\r
-\r
-/* Dummy routine, only required in plink. */\r
-void ldisc_update(void *frontend, int echo, int edit)\r
-{\r
-}\r
-\r
-char *get_ttymode(void *frontend, const char *mode)\r
-{\r
-    return term_get_ttymode(term, mode);\r
-}\r
-\r
-static void start_backend(void)\r
-{\r
-    const char *error;\r
-    char msg[1024], *title;\r
-    char *realhost;\r
-    int i;\r
-\r
-    /*\r
-     * Select protocol. This is farmed out into a table in a\r
-     * separate file to enable an ssh-free variant.\r
-     */\r
-    back = backend_from_proto(cfg.protocol);\r
-    if (back == NULL) {\r
-       char *str = dupprintf("%s Internal Error", appname);\r
-       MessageBox(NULL, "Unsupported protocol number found",\r
-                  str, MB_OK | MB_ICONEXCLAMATION);\r
-       sfree(str);\r
-       cleanup_exit(1);\r
-    }\r
-\r
-    error = back->init(NULL, &backhandle, &cfg,\r
-                      cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,\r
-                      cfg.tcp_keepalives);\r
-    back->provide_logctx(backhandle, logctx);\r
-    if (error) {\r
-       char *str = dupprintf("%s Error", appname);\r
-       sprintf(msg, "Unable to open connection to\n"\r
-               "%.800s\n" "%s", cfg_dest(&cfg), error);\r
-       MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);\r
-       sfree(str);\r
-       exit(0);\r
-    }\r
-    window_name = icon_name = NULL;\r
-    if (*cfg.wintitle) {\r
-       title = cfg.wintitle;\r
-    } else {\r
-       sprintf(msg, "%s - %s", realhost, appname);\r
-       title = msg;\r
-    }\r
-    sfree(realhost);\r
-    set_title(NULL, title);\r
-    set_icon(NULL, title);\r
-\r
-    /*\r
-     * Connect the terminal to the backend for resize purposes.\r
-     */\r
-    term_provide_resize_fn(term, back->size, backhandle);\r
-\r
-    /*\r
-     * Set up a line discipline.\r
-     */\r
-    ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);\r
-\r
-    /*\r
-     * Destroy the Restart Session menu item. (This will return\r
-     * failure if it's already absent, as it will be the very first\r
-     * time we call this function. We ignore that, because as long\r
-     * as the menu item ends up not being there, we don't care\r
-     * whether it was us who removed it or not!)\r
-     */\r
-    for (i = 0; i < lenof(popup_menus); i++) {\r
-       DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);\r
-    }\r
-\r
-    must_close_session = FALSE;\r
-    session_closed = FALSE;\r
-}\r
-\r
-static void close_session(void)\r
-{\r
-    char morestuff[100];\r
-    int i;\r
-\r
-    session_closed = TRUE;\r
-    sprintf(morestuff, "%.70s (inactive)", appname);\r
-    set_icon(NULL, morestuff);\r
-    set_title(NULL, morestuff);\r
-\r
-    if (ldisc) {\r
-       ldisc_free(ldisc);\r
-       ldisc = NULL;\r
-    }\r
-    if (back) {\r
-       back->free(backhandle);\r
-       backhandle = NULL;\r
-       back = NULL;\r
-        term_provide_resize_fn(term, NULL, NULL);\r
-       update_specials_menu(NULL);\r
-    }\r
-\r
-    /*\r
-     * Show the Restart Session menu item. Do a precautionary\r
-     * delete first to ensure we never end up with more than one.\r
-     */\r
-    for (i = 0; i < lenof(popup_menus); i++) {\r
-       DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);\r
-       InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,\r
-                  IDM_RESTART, "&Restart Session");\r
-    }\r
-\r
-    /*\r
-     * Unset the 'must_close_session' flag, or else we'll come\r
-     * straight back here the next time we go round the main message\r
-     * loop - which, worse still, will be immediately (without\r
-     * blocking) because we've just triggered a WM_SETTEXT by the\r
-     * window title change above.\r
-     */\r
-    must_close_session = FALSE;\r
-}\r
-\r
-int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)\r
-{\r
-    WNDCLASS wndclass;\r
-    MSG msg;\r
-    HRESULT hr;\r
-    int guess_width, guess_height;\r
-\r
-    hinst = inst;\r
-    hwnd = NULL;\r
-    flags = FLAG_VERBOSE | FLAG_INTERACTIVE;\r
-\r
-    sk_init();\r
-\r
-    InitCommonControls();\r
-\r
-    /* Ensure a Maximize setting in Explorer doesn't maximise the\r
-     * config box. */\r
-    defuse_showwindow();\r
-\r
-    if (!init_winver())\r
-    {\r
-       char *str = dupprintf("%s Fatal Error", appname);\r
-       MessageBox(NULL, "Windows refuses to report a version",\r
-                  str, MB_OK | MB_ICONEXCLAMATION);\r
-       sfree(str);\r
-       return 1;\r
-    }\r
-\r
-    /*\r
-     * If we're running a version of Windows that doesn't support\r
-     * WM_MOUSEWHEEL, find out what message number we should be\r
-     * using instead.\r
-     */\r
-    if (osVersion.dwMajorVersion < 4 ||\r
-       (osVersion.dwMajorVersion == 4 && \r
-        osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))\r
-       wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");\r
-\r
-    init_help();\r
-\r
-    init_flashwindow();\r
-\r
-    /*\r
-     * Initialize COM.\r
-     */\r
-    hr = CoInitialize(NULL);\r
-    if (hr != S_OK && hr != S_FALSE) {\r
-        char *str = dupprintf("%s Fatal Error", appname);\r
-       MessageBox(NULL, "Failed to initialize COM subsystem",\r
-                  str, MB_OK | MB_ICONEXCLAMATION);\r
-       sfree(str);\r
-       return 1;\r
-    }\r
-\r
-    /*\r
-     * Process the command line.\r
-     */\r
-    {\r
-       char *p;\r
-       int got_host = 0;\r
-       /* By default, we bring up the config dialog, rather than launching\r
-        * a session. This gets set to TRUE if something happens to change\r
-        * that (e.g., a hostname is specified on the command-line). */\r
-       int allow_launch = FALSE;\r
-\r
-       default_protocol = be_default_protocol;\r
-       /* Find the appropriate default port. */\r
-       {\r
-           Backend *b = backend_from_proto(default_protocol);\r
-           default_port = 0; /* illegal */\r
-           if (b)\r
-               default_port = b->default_port;\r
-       }\r
-       cfg.logtype = LGTYP_NONE;\r
-\r
-       do_defaults(NULL, &cfg);\r
-\r
-       p = cmdline;\r
-\r
-       /*\r
-        * Process a couple of command-line options which are more\r
-        * easily dealt with before the line is broken up into words.\r
-        * These are the old-fashioned but convenient @sessionname and\r
-        * the internal-use-only &sharedmemoryhandle, neither of which\r
-        * are combined with anything else.\r
-        */\r
-       while (*p && isspace(*p))\r
-           p++;\r
-       if (*p == '@') {\r
-            /*\r
-             * An initial @ means that the whole of the rest of the\r
-             * command line should be treated as the name of a saved\r
-             * session, with _no quoting or escaping_. This makes it a\r
-             * very convenient means of automated saved-session\r
-             * launching, via IDM_SAVEDSESS or Windows 7 jump lists.\r
-             */\r
-           int i = strlen(p);\r
-           while (i > 1 && isspace(p[i - 1]))\r
-               i--;\r
-           p[i] = '\0';\r
-           do_defaults(p + 1, &cfg);\r
-           if (!cfg_launchable(&cfg) && !do_config()) {\r
-               cleanup_exit(0);\r
-           }\r
-           allow_launch = TRUE;    /* allow it to be launched directly */\r
-       } else if (*p == '&') {\r
-           /*\r
-            * An initial & means we've been given a command line\r
-            * containing the hex value of a HANDLE for a file\r
-            * mapping object, which we must then extract as a\r
-            * config.\r
-            */\r
-           HANDLE filemap;\r
-           Config *cp;\r
-           if (sscanf(p + 1, "%p", &filemap) == 1 &&\r
-               (cp = MapViewOfFile(filemap, FILE_MAP_READ,\r
-                                   0, 0, sizeof(Config))) != NULL) {\r
-               cfg = *cp;\r
-               UnmapViewOfFile(cp);\r
-               CloseHandle(filemap);\r
-           } else if (!do_config()) {\r
-               cleanup_exit(0);\r
-           }\r
-           allow_launch = TRUE;\r
-       } else {\r
-           /*\r
-            * Otherwise, break up the command line and deal with\r
-            * it sensibly.\r
-            */\r
-           int argc, i;\r
-           char **argv;\r
-           \r
-           split_into_argv(cmdline, &argc, &argv, NULL);\r
-\r
-           for (i = 0; i < argc; i++) {\r
-               char *p = argv[i];\r
-               int ret;\r
-\r
-               ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,\r
-                                           1, &cfg);\r
-               if (ret == -2) {\r
-                   cmdline_error("option \"%s\" requires an argument", p);\r
-               } else if (ret == 2) {\r
-                   i++;               /* skip next argument */\r
-               } else if (ret == 1) {\r
-                   continue;          /* nothing further needs doing */\r
-               } else if (!strcmp(p, "-cleanup") ||\r
-                          !strcmp(p, "-cleanup-during-uninstall")) {\r
-                   /*\r
-                    * `putty -cleanup'. Remove all registry\r
-                    * entries associated with PuTTY, and also find\r
-                    * and delete the random seed file.\r
-                    */\r
-                   char *s1, *s2;\r
-                   /* Are we being invoked from an uninstaller? */\r
-                   if (!strcmp(p, "-cleanup-during-uninstall")) {\r
-                       s1 = dupprintf("Remove saved sessions and random seed file?\n"\r
-                                      "\n"\r
-                                      "If you hit Yes, ALL Registry entries associated\n"\r
-                                      "with %s will be removed, as well as the\n"\r
-                                      "random seed file. THIS PROCESS WILL\n"\r
-                                      "DESTROY YOUR SAVED SESSIONS.\n"\r
-                                      "(This only affects the currently logged-in user.)\n"\r
-                                      "\n"\r
-                                      "If you hit No, uninstallation will proceed, but\n"\r
-                                      "saved sessions etc will be left on the machine.",\r
-                                      appname);\r
-                       s2 = dupprintf("%s Uninstallation", appname);\r
-                   } else {\r
-                       s1 = dupprintf("This procedure will remove ALL Registry entries\n"\r
-                                      "associated with %s, and will also remove\n"\r
-                                      "the random seed file. (This only affects the\n"\r
-                                      "currently logged-in user.)\n"\r
-                                      "\n"\r
-                                      "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"\r
-                                      "Are you really sure you want to continue?",\r
-                                      appname);\r
-                       s2 = dupprintf("%s Warning", appname);\r
-                   }\r
-                   if (message_box(s1, s2,\r
-                                   MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,\r
-                                   HELPCTXID(option_cleanup)) == IDYES) {\r
-                       cleanup_all();\r
-                   }\r
-                   sfree(s1);\r
-                   sfree(s2);\r
-                   exit(0);\r
-               } else if (!strcmp(p, "-pgpfp")) {\r
-                   pgp_fingerprints();\r
-                   exit(1);\r
-               } else if (*p != '-') {\r
-                   char *q = p;\r
-                   if (got_host) {\r
-                       /*\r
-                        * If we already have a host name, treat\r
-                        * this argument as a port number. NB we\r
-                        * have to treat this as a saved -P\r
-                        * argument, so that it will be deferred\r
-                        * until it's a good moment to run it.\r
-                        */\r
-                       int ret = cmdline_process_param("-P", p, 1, &cfg);\r
-                       assert(ret == 2);\r
-                   } else if (!strncmp(q, "telnet:", 7)) {\r
-                       /*\r
-                        * If the hostname starts with "telnet:",\r
-                        * set the protocol to Telnet and process\r
-                        * the string as a Telnet URL.\r
-                        */\r
-                       char c;\r
-\r
-                       q += 7;\r
-                       if (q[0] == '/' && q[1] == '/')\r
-                           q += 2;\r
-                       cfg.protocol = PROT_TELNET;\r
-                       p = q;\r
-                       while (*p && *p != ':' && *p != '/')\r
-                           p++;\r
-                       c = *p;\r
-                       if (*p)\r
-                           *p++ = '\0';\r
-                       if (c == ':')\r
-                           cfg.port = atoi(p);\r
-                       else\r
-                           cfg.port = -1;\r
-                       strncpy(cfg.host, q, sizeof(cfg.host) - 1);\r
-                       cfg.host[sizeof(cfg.host) - 1] = '\0';\r
-                       got_host = 1;\r
-                   } else {\r
-                       /*\r
-                        * Otherwise, treat this argument as a host\r
-                        * name.\r
-                        */\r
-                       while (*p && !isspace(*p))\r
-                           p++;\r
-                       if (*p)\r
-                           *p++ = '\0';\r
-                       strncpy(cfg.host, q, sizeof(cfg.host) - 1);\r
-                       cfg.host[sizeof(cfg.host) - 1] = '\0';\r
-                       got_host = 1;\r
-                   }\r
-               } else {\r
-                   cmdline_error("unknown option \"%s\"", p);\r
-               }\r
-           }\r
-       }\r
-\r
-       cmdline_run_saved(&cfg);\r
-\r
-       if (loaded_session || got_host)\r
-           allow_launch = TRUE;\r
-\r
-       if ((!allow_launch || !cfg_launchable(&cfg)) && !do_config()) {\r
-           cleanup_exit(0);\r
-       }\r
-\r
-       /*\r
-        * Trim leading whitespace off the hostname if it's there.\r
-        */\r
-       {\r
-           int space = strspn(cfg.host, " \t");\r
-           memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);\r
-       }\r
-\r
-       /* See if host is of the form user@host */\r
-       if (cfg.host[0] != '\0') {\r
-           char *atsign = strrchr(cfg.host, '@');\r
-           /* Make sure we're not overflowing the user field */\r
-           if (atsign) {\r
-               if (atsign - cfg.host < sizeof cfg.username) {\r
-                   strncpy(cfg.username, cfg.host, atsign - cfg.host);\r
-                   cfg.username[atsign - cfg.host] = '\0';\r
-               }\r
-               memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));\r
-           }\r
-       }\r
-\r
-       /*\r
-        * Trim a colon suffix off the hostname if it's there. In\r
-        * order to protect IPv6 address literals against this\r
-        * treatment, we do not do this if there's _more_ than one\r
-        * colon.\r
-        */\r
-       {\r
-           char *c = strchr(cfg.host, ':');\r
-\r
-           if (c) {\r
-               char *d = strchr(c+1, ':');\r
-               if (!d)\r
-                   *c = '\0';\r
-           }\r
-       }\r
-\r
-       /*\r
-        * Remove any remaining whitespace from the hostname.\r
-        */\r
-       {\r
-           int p1 = 0, p2 = 0;\r
-           while (cfg.host[p2] != '\0') {\r
-               if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {\r
-                   cfg.host[p1] = cfg.host[p2];\r
-                   p1++;\r
-               }\r
-               p2++;\r
-           }\r
-           cfg.host[p1] = '\0';\r
-       }\r
-    }\r
-\r
-    if (!prev) {\r
-       wndclass.style = 0;\r
-       wndclass.lpfnWndProc = WndProc;\r
-       wndclass.cbClsExtra = 0;\r
-       wndclass.cbWndExtra = 0;\r
-       wndclass.hInstance = inst;\r
-       wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));\r
-       wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);\r
-       wndclass.hbrBackground = NULL;\r
-       wndclass.lpszMenuName = NULL;\r
-       wndclass.lpszClassName = appname;\r
-\r
-       RegisterClass(&wndclass);\r
-    }\r
-\r
-    memset(&ucsdata, 0, sizeof(ucsdata));\r
-\r
-    cfgtopalette();\r
-\r
-    /*\r
-     * Guess some defaults for the window size. This all gets\r
-     * updated later, so we don't really care too much. However, we\r
-     * do want the font width/height guesses to correspond to a\r
-     * large font rather than a small one...\r
-     */\r
-\r
-    font_width = 10;\r
-    font_height = 20;\r
-    extra_width = 25;\r
-    extra_height = 28;\r
-    guess_width = extra_width + font_width * cfg.width;\r
-    guess_height = extra_height + font_height * cfg.height;\r
-    {\r
-       RECT r;\r
-       get_fullscreen_rect(&r);\r
-       if (guess_width > r.right - r.left)\r
-           guess_width = r.right - r.left;\r
-       if (guess_height > r.bottom - r.top)\r
-           guess_height = r.bottom - r.top;\r
-    }\r
-\r
-    {\r
-       int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;\r
-       int exwinmode = 0;\r
-       if (!cfg.scrollbar)\r
-           winmode &= ~(WS_VSCROLL);\r
-       if (cfg.resize_action == RESIZE_DISABLED)\r
-           winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);\r
-       if (cfg.alwaysontop)\r
-           exwinmode |= WS_EX_TOPMOST;\r
-       if (cfg.sunken_edge)\r
-           exwinmode |= WS_EX_CLIENTEDGE;\r
-       hwnd = CreateWindowEx(exwinmode, appname, appname,\r
-                             winmode, CW_USEDEFAULT, CW_USEDEFAULT,\r
-                             guess_width, guess_height,\r
-                             NULL, NULL, inst, NULL);\r
-    }\r
-\r
-    /*\r
-     * Initialise the terminal. (We have to do this _after_\r
-     * creating the window, since the terminal is the first thing\r
-     * which will call schedule_timer(), which will in turn call\r
-     * timer_change_notify() which will expect hwnd to exist.)\r
-     */\r
-    term = term_init(&cfg, &ucsdata, NULL);\r
-    logctx = log_init(NULL, &cfg);\r
-    term_provide_logctx(term, logctx);\r
-    term_size(term, cfg.height, cfg.width, cfg.savelines);\r
-\r
-    /*\r
-     * Initialise the fonts, simultaneously correcting the guesses\r
-     * for font_{width,height}.\r
-     */\r
-    init_fonts(0,0);\r
-\r
-    /*\r
-     * Correct the guesses for extra_{width,height}.\r
-     */\r
-    {\r
-       RECT cr, wr;\r
-       GetWindowRect(hwnd, &wr);\r
-       GetClientRect(hwnd, &cr);\r
-       offset_width = offset_height = cfg.window_border;\r
-       extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;\r
-       extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;\r
-    }\r
-\r
-    /*\r
-     * Resize the window, now we know what size we _really_ want it\r
-     * to be.\r
-     */\r
-    guess_width = extra_width + font_width * term->cols;\r
-    guess_height = extra_height + font_height * term->rows;\r
-    SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,\r
-                SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);\r
-\r
-    /*\r
-     * Set up a caret bitmap, with no content.\r
-     */\r
-    {\r
-       char *bits;\r
-       int size = (font_width + 15) / 16 * 2 * font_height;\r
-       bits = snewn(size, char);\r
-       memset(bits, 0, size);\r
-       caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);\r
-       sfree(bits);\r
-    }\r
-    CreateCaret(hwnd, caretbm, font_width, font_height);\r
-\r
-    /*\r
-     * Initialise the scroll bar.\r
-     */\r
-    {\r
-       SCROLLINFO si;\r
-\r
-       si.cbSize = sizeof(si);\r
-       si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;\r
-       si.nMin = 0;\r
-       si.nMax = term->rows - 1;\r
-       si.nPage = term->rows;\r
-       si.nPos = 0;\r
-       SetScrollInfo(hwnd, SB_VERT, &si, FALSE);\r
-    }\r
-\r
-    /*\r
-     * Prepare the mouse handler.\r
-     */\r
-    lastact = MA_NOTHING;\r
-    lastbtn = MBT_NOTHING;\r
-    dbltime = GetDoubleClickTime();\r
-\r
-    /*\r
-     * Set up the session-control options on the system menu.\r
-     */\r
-    {\r
-       HMENU m;\r
-       int j;\r
-       char *str;\r
-\r
-       popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);\r
-       popup_menus[CTXMENU].menu = CreatePopupMenu();\r
-       AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");\r
-\r
-       savedsess_menu = CreateMenu();\r
-       get_sesslist(&sesslist, TRUE);\r
-       update_savedsess_menu();\r
-\r
-       for (j = 0; j < lenof(popup_menus); j++) {\r
-           m = popup_menus[j].menu;\r
-\r
-           AppendMenu(m, MF_SEPARATOR, 0, 0);\r
-           AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");\r
-           AppendMenu(m, MF_SEPARATOR, 0, 0);\r
-           AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");\r
-           AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");\r
-           AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,\r
-                      "Sa&ved Sessions");\r
-           AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");\r
-           AppendMenu(m, MF_SEPARATOR, 0, 0);\r
-           AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");\r
-           AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");\r
-           AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");\r
-           AppendMenu(m, MF_SEPARATOR, 0, 0);\r
-           AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?\r
-                      MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");\r
-           AppendMenu(m, MF_SEPARATOR, 0, 0);\r
-           if (has_help())\r
-               AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");\r
-           str = dupprintf("&About %s", appname);\r
-           AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);\r
-           sfree(str);\r
-       }\r
-    }\r
-\r
-    start_backend();\r
-\r
-    /*\r
-     * Set up the initial input locale.\r
-     */\r
-    set_input_locale(GetKeyboardLayout(0));\r
-\r
-    /*\r
-     * Finally show the window!\r
-     */\r
-    ShowWindow(hwnd, show);\r
-    SetForegroundWindow(hwnd);\r
-\r
-    /*\r
-     * Set the palette up.\r
-     */\r
-    pal = NULL;\r
-    logpal = NULL;\r
-    init_palette();\r
-\r
-    term_set_focus(term, GetForegroundWindow() == hwnd);\r
-    UpdateWindow(hwnd);\r
-\r
-    while (1) {\r
-       HANDLE *handles;\r
-       int nhandles, n;\r
-\r
-       handles = handle_get_events(&nhandles);\r
-\r
-       n = MsgWaitForMultipleObjects(nhandles, handles, FALSE, INFINITE,\r
-                                     QS_ALLINPUT);\r
-\r
-       if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {\r
-           handle_got_event(handles[n - WAIT_OBJECT_0]);\r
-           sfree(handles);\r
-           if (must_close_session)\r
-               close_session();\r
-       } else\r
-           sfree(handles);\r
-\r
-       while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {\r
-           if (msg.message == WM_QUIT)\r
-               goto finished;         /* two-level break */\r
-\r
-           if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))\r
-               DispatchMessage(&msg);\r
-           /* Send the paste buffer if there's anything to send */\r
-           term_paste(term);\r
-           /* If there's nothing new in the queue then we can do everything\r
-            * we've delayed, reading the socket, writing, and repainting\r
-            * the window.\r
-            */\r
-           if (must_close_session)\r
-               close_session();\r
-       }\r
-\r
-       /* The messages seem unreliable; especially if we're being tricky */\r
-       term_set_focus(term, GetForegroundWindow() == hwnd);\r
-\r
-       if (pending_netevent)\r
-           enact_pending_netevent();\r
-\r
-       net_pending_errors();\r
-    }\r
-\r
-    finished:\r
-    cleanup_exit(msg.wParam);         /* this doesn't return... */\r
-    return msg.wParam;                /* ... but optimiser doesn't know */\r
-}\r
-\r
-/*\r
- * Clean up and exit.\r
- */\r
-void cleanup_exit(int code)\r
-{\r
-    /*\r
-     * Clean up.\r
-     */\r
-    deinit_fonts();\r
-    sfree(logpal);\r
-    if (pal)\r
-       DeleteObject(pal);\r
-    sk_cleanup();\r
-\r
-    if (cfg.protocol == PROT_SSH) {\r
-       random_save_seed();\r
-#ifdef MSCRYPTOAPI\r
-       crypto_wrapup();\r
-#endif\r
-    }\r
-    shutdown_help();\r
-\r
-    /* Clean up COM. */\r
-    CoUninitialize();\r
-\r
-    exit(code);\r
-}\r
-\r
-/*\r
- * Set up, or shut down, an AsyncSelect. Called from winnet.c.\r
- */\r
-char *do_select(SOCKET skt, int startup)\r
-{\r
-    int msg, events;\r
-    if (startup) {\r
-       msg = WM_NETEVENT;\r
-       events = (FD_CONNECT | FD_READ | FD_WRITE |\r
-                 FD_OOB | FD_CLOSE | FD_ACCEPT);\r
-    } else {\r
-       msg = events = 0;\r
-    }\r
-    if (!hwnd)\r
-       return "do_select(): internal error (hwnd==NULL)";\r
-    if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {\r
-       switch (p_WSAGetLastError()) {\r
-         case WSAENETDOWN:\r
-           return "Network is down";\r
-         default:\r
-           return "WSAAsyncSelect(): unknown error";\r
-       }\r
-    }\r
-    return NULL;\r
-}\r
-\r
-/*\r
- * Refresh the saved-session submenu from `sesslist'.\r
- */\r
-static void update_savedsess_menu(void)\r
-{\r
-    int i;\r
-    while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;\r
-    /* skip sesslist.sessions[0] == Default Settings */\r
-    for (i = 1;\r
-        i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions\r
-                                                      : MENU_SAVED_MAX+1);\r
-        i++)\r
-       AppendMenu(savedsess_menu, MF_ENABLED,\r
-                  IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,\r
-                  sesslist.sessions[i]);\r
-    if (sesslist.nsessions <= 1)\r
-       AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");\r
-}\r
-\r
-/*\r
- * Update the Special Commands submenu.\r
- */\r
-void update_specials_menu(void *frontend)\r
-{\r
-    HMENU new_menu;\r
-    int i, j;\r
-\r
-    if (back)\r
-       specials = back->get_specials(backhandle);\r
-    else\r
-       specials = NULL;\r
-\r
-    if (specials) {\r
-       /* We can't use Windows to provide a stack for submenus, so\r
-        * here's a lame "stack" that will do for now. */\r
-       HMENU saved_menu = NULL;\r
-       int nesting = 1;\r
-       new_menu = CreatePopupMenu();\r
-       for (i = 0; nesting > 0; i++) {\r
-           assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);\r
-           switch (specials[i].code) {\r
-             case TS_SEP:\r
-               AppendMenu(new_menu, MF_SEPARATOR, 0, 0);\r
-               break;\r
-             case TS_SUBMENU:\r
-               assert(nesting < 2);\r
-               nesting++;\r
-               saved_menu = new_menu; /* XXX lame stacking */\r
-               new_menu = CreatePopupMenu();\r
-               AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,\r
-                          (UINT) new_menu, specials[i].name);\r
-               break;\r
-             case TS_EXITMENU:\r
-               nesting--;\r
-               if (nesting) {\r
-                   new_menu = saved_menu; /* XXX lame stacking */\r
-                   saved_menu = NULL;\r
-               }\r
-               break;\r
-             default:\r
-               AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,\r
-                          specials[i].name);\r
-               break;\r
-           }\r
-       }\r
-       /* Squirrel the highest special. */\r
-       n_specials = i - 1;\r
-    } else {\r
-       new_menu = NULL;\r
-       n_specials = 0;\r
-    }\r
-\r
-    for (j = 0; j < lenof(popup_menus); j++) {\r
-       if (specials_menu) {\r
-           /* XXX does this free up all submenus? */\r
-           DeleteMenu(popup_menus[j].menu, (UINT)specials_menu, MF_BYCOMMAND);\r
-           DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);\r
-       }\r
-       if (new_menu) {\r
-           InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,\r
-                      MF_BYCOMMAND | MF_POPUP | MF_ENABLED,\r
-                      (UINT) new_menu, "S&pecial Command");\r
-           InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,\r
-                      MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);\r
-       }\r
-    }\r
-    specials_menu = new_menu;\r
-}\r
-\r
-static void update_mouse_pointer(void)\r
-{\r
-    LPTSTR curstype;\r
-    int force_visible = FALSE;\r
-    static int forced_visible = FALSE;\r
-    switch (busy_status) {\r
-      case BUSY_NOT:\r
-       if (send_raw_mouse)\r
-           curstype = IDC_ARROW;\r
-       else\r
-           curstype = IDC_IBEAM;\r
-       break;\r
-      case BUSY_WAITING:\r
-       curstype = IDC_APPSTARTING; /* this may be an abuse */\r
-       force_visible = TRUE;\r
-       break;\r
-      case BUSY_CPU:\r
-       curstype = IDC_WAIT;\r
-       force_visible = TRUE;\r
-       break;\r
-      default:\r
-       assert(0);\r
-    }\r
-    {\r
-       HCURSOR cursor = LoadCursor(NULL, curstype);\r
-       SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);\r
-       SetCursor(cursor); /* force redraw of cursor at current posn */\r
-    }\r
-    if (force_visible != forced_visible) {\r
-       /* We want some cursor shapes to be visible always.\r
-        * Along with show_mouseptr(), this manages the ShowCursor()\r
-        * counter such that if we switch back to a non-force_visible\r
-        * cursor, the previous visibility state is restored. */\r
-       ShowCursor(force_visible);\r
-       forced_visible = force_visible;\r
-    }\r
-}\r
-\r
-void set_busy_status(void *frontend, int status)\r
-{\r
-    busy_status = status;\r
-    update_mouse_pointer();\r
-}\r
-\r
-/*\r
- * set or clear the "raw mouse message" mode\r
- */\r
-void set_raw_mouse_mode(void *frontend, int activate)\r
-{\r
-    activate = activate && !cfg.no_mouse_rep;\r
-    send_raw_mouse = activate;\r
-    update_mouse_pointer();\r
-}\r
-\r
-/*\r
- * Print a message box and close the connection.\r
- */\r
-void connection_fatal(void *frontend, char *fmt, ...)\r
-{\r
-    va_list ap;\r
-    char *stuff, morestuff[100];\r
-\r
-    va_start(ap, fmt);\r
-    stuff = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    sprintf(morestuff, "%.70s Fatal Error", appname);\r
-    MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);\r
-    sfree(stuff);\r
-\r
-    if (cfg.close_on_exit == FORCE_ON)\r
-       PostQuitMessage(1);\r
-    else {\r
-       must_close_session = TRUE;\r
-    }\r
-}\r
-\r
-/*\r
- * Report an error at the command-line parsing stage.\r
- */\r
-void cmdline_error(char *fmt, ...)\r
-{\r
-    va_list ap;\r
-    char *stuff, morestuff[100];\r
-\r
-    va_start(ap, fmt);\r
-    stuff = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    sprintf(morestuff, "%.70s Command Line Error", appname);\r
-    MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);\r
-    sfree(stuff);\r
-    exit(1);\r
-}\r
-\r
-/*\r
- * Actually do the job requested by a WM_NETEVENT\r
- */\r
-static void enact_pending_netevent(void)\r
-{\r
-    static int reentering = 0;\r
-    extern int select_result(WPARAM, LPARAM);\r
-\r
-    if (reentering)\r
-       return;                        /* don't unpend the pending */\r
-\r
-    pending_netevent = FALSE;\r
-\r
-    reentering = 1;\r
-    select_result(pend_netevent_wParam, pend_netevent_lParam);\r
-    reentering = 0;\r
-}\r
-\r
-/*\r
- * Copy the colour palette from the configuration data into defpal.\r
- * This is non-trivial because the colour indices are different.\r
- */\r
-static void cfgtopalette(void)\r
-{\r
-    int i;\r
-    static const int ww[] = {\r
-       256, 257, 258, 259, 260, 261,\r
-       0, 8, 1, 9, 2, 10, 3, 11,\r
-       4, 12, 5, 13, 6, 14, 7, 15\r
-    };\r
-\r
-    for (i = 0; i < 22; i++) {\r
-       int w = ww[i];\r
-       defpal[w].rgbtRed = cfg.colours[i][0];\r
-       defpal[w].rgbtGreen = cfg.colours[i][1];\r
-       defpal[w].rgbtBlue = cfg.colours[i][2];\r
-    }\r
-    for (i = 0; i < NEXTCOLOURS; i++) {\r
-       if (i < 216) {\r
-           int r = i / 36, g = (i / 6) % 6, b = i % 6;\r
-           defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;\r
-           defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;\r
-           defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;\r
-       } else {\r
-           int shade = i - 216;\r
-           shade = shade * 10 + 8;\r
-           defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =\r
-               defpal[i+16].rgbtBlue = shade;\r
-       }\r
-    }\r
-\r
-    /* Override with system colours if appropriate */\r
-    if (cfg.system_colour)\r
-        systopalette();\r
-}\r
-\r
-/*\r
- * Override bit of defpal with colours from the system.\r
- * (NB that this takes a copy the system colours at the time this is called,\r
- * so subsequent colour scheme changes don't take effect. To fix that we'd\r
- * probably want to be using GetSysColorBrush() and the like.)\r
- */\r
-static void systopalette(void)\r
-{\r
-    int i;\r
-    static const struct { int nIndex; int norm; int bold; } or[] =\r
-    {\r
-       { COLOR_WINDOWTEXT,     256, 257 }, /* Default Foreground */\r
-       { COLOR_WINDOW,         258, 259 }, /* Default Background */\r
-       { COLOR_HIGHLIGHTTEXT,  260, 260 }, /* Cursor Text */\r
-       { COLOR_HIGHLIGHT,      261, 261 }, /* Cursor Colour */\r
-    };\r
-\r
-    for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {\r
-       COLORREF colour = GetSysColor(or[i].nIndex);\r
-       defpal[or[i].norm].rgbtRed =\r
-          defpal[or[i].bold].rgbtRed = GetRValue(colour);\r
-       defpal[or[i].norm].rgbtGreen =\r
-          defpal[or[i].bold].rgbtGreen = GetGValue(colour);\r
-       defpal[or[i].norm].rgbtBlue =\r
-          defpal[or[i].bold].rgbtBlue = GetBValue(colour);\r
-    }\r
-}\r
-\r
-/*\r
- * Set up the colour palette.\r
- */\r
-static void init_palette(void)\r
-{\r
-    int i;\r
-    HDC hdc = GetDC(hwnd);\r
-    if (hdc) {\r
-       if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {\r
-           /*\r
-            * This is a genuine case where we must use smalloc\r
-            * because the snew macros can't cope.\r
-            */\r
-           logpal = smalloc(sizeof(*logpal)\r
-                            - sizeof(logpal->palPalEntry)\r
-                            + NALLCOLOURS * sizeof(PALETTEENTRY));\r
-           logpal->palVersion = 0x300;\r
-           logpal->palNumEntries = NALLCOLOURS;\r
-           for (i = 0; i < NALLCOLOURS; i++) {\r
-               logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;\r
-               logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;\r
-               logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;\r
-               logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;\r
-           }\r
-           pal = CreatePalette(logpal);\r
-           if (pal) {\r
-               SelectPalette(hdc, pal, FALSE);\r
-               RealizePalette(hdc);\r
-               SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);\r
-           }\r
-       }\r
-       ReleaseDC(hwnd, hdc);\r
-    }\r
-    if (pal)\r
-       for (i = 0; i < NALLCOLOURS; i++)\r
-           colours[i] = PALETTERGB(defpal[i].rgbtRed,\r
-                                   defpal[i].rgbtGreen,\r
-                                   defpal[i].rgbtBlue);\r
-    else\r
-       for (i = 0; i < NALLCOLOURS; i++)\r
-           colours[i] = RGB(defpal[i].rgbtRed,\r
-                            defpal[i].rgbtGreen, defpal[i].rgbtBlue);\r
-}\r
-\r
-/*\r
- * This is a wrapper to ExtTextOut() to force Windows to display\r
- * the precise glyphs we give it. Otherwise it would do its own\r
- * bidi and Arabic shaping, and we would end up uncertain which\r
- * characters it had put where.\r
- */\r
-static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,\r
-                         unsigned short *lpString, UINT cbCount,\r
-                         CONST INT *lpDx, int opaque)\r
-{\r
-#ifdef __LCC__\r
-    /*\r
-     * The LCC include files apparently don't supply the\r
-     * GCP_RESULTSW type, but we can make do with GCP_RESULTS\r
-     * proper: the differences aren't important to us (the only\r
-     * variable-width string parameter is one we don't use anyway).\r
-     */\r
-    GCP_RESULTS gcpr;\r
-#else\r
-    GCP_RESULTSW gcpr;\r
-#endif\r
-    char *buffer = snewn(cbCount*2+2, char);\r
-    char *classbuffer = snewn(cbCount, char);\r
-    memset(&gcpr, 0, sizeof(gcpr));\r
-    memset(buffer, 0, cbCount*2+2);\r
-    memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);\r
-\r
-    gcpr.lStructSize = sizeof(gcpr);\r
-    gcpr.lpGlyphs = (void *)buffer;\r
-    gcpr.lpClass = (void *)classbuffer;\r
-    gcpr.nGlyphs = cbCount;\r
-    GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,\r
-                          FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);\r
-\r
-    ExtTextOut(hdc, x, y,\r
-              ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),\r
-              lprc, buffer, cbCount, lpDx);\r
-}\r
-\r
-/*\r
- * The exact_textout() wrapper, unfortunately, destroys the useful\r
- * Windows `font linking' behaviour: automatic handling of Unicode\r
- * code points not supported in this font by falling back to a font\r
- * which does contain them. Therefore, we adopt a multi-layered\r
- * approach: for any potentially-bidi text, we use exact_textout(),\r
- * and for everything else we use a simple ExtTextOut as we did\r
- * before exact_textout() was introduced.\r
- */\r
-static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,\r
-                           unsigned short *lpString, UINT cbCount,\r
-                           CONST INT *lpDx, int opaque)\r
-{\r
-    int i, j, xp, xn;\r
-    int bkmode = 0, got_bkmode = FALSE;\r
-\r
-    xp = xn = x;\r
-\r
-    for (i = 0; i < (int)cbCount ;) {\r
-       int rtl = is_rtl(lpString[i]);\r
-\r
-       xn += lpDx[i];\r
-\r
-       for (j = i+1; j < (int)cbCount; j++) {\r
-           if (rtl != is_rtl(lpString[j]))\r
-               break;\r
-           xn += lpDx[j];\r
-       }\r
-\r
-       /*\r
-        * Now [i,j) indicates a maximal substring of lpString\r
-        * which should be displayed using the same textout\r
-        * function.\r
-        */\r
-       if (rtl) {\r
-           exact_textout(hdc, xp, y, lprc, lpString+i, j-i,\r
-                          font_varpitch ? NULL : lpDx+i, opaque);\r
-       } else {\r
-           ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),\r
-                       lprc, lpString+i, j-i,\r
-                        font_varpitch ? NULL : lpDx+i);\r
-       }\r
-\r
-       i = j;\r
-       xp = xn;\r
-\r
-        bkmode = GetBkMode(hdc);\r
-        got_bkmode = TRUE;\r
-        SetBkMode(hdc, TRANSPARENT);\r
-        opaque = FALSE;\r
-    }\r
-\r
-    if (got_bkmode)\r
-        SetBkMode(hdc, bkmode);\r
-}\r
-\r
-static int get_font_width(HDC hdc, const TEXTMETRIC *tm)\r
-{\r
-    int ret;\r
-    /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */\r
-    if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {\r
-        ret = tm->tmAveCharWidth;\r
-    } else {\r
-#define FIRST '0'\r
-#define LAST '9'\r
-        ABCFLOAT widths[LAST-FIRST + 1];\r
-        int j;\r
-\r
-        font_varpitch = TRUE;\r
-        font_dualwidth = TRUE;\r
-        if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {\r
-            ret = 0;\r
-            for (j = 0; j < lenof(widths); j++) {\r
-                int width = (int)(0.5 + widths[j].abcfA +\r
-                                  widths[j].abcfB + widths[j].abcfC);\r
-                if (ret < width)\r
-                    ret = width;\r
-            }\r
-        } else {\r
-            ret = tm->tmMaxCharWidth;\r
-        }\r
-#undef FIRST\r
-#undef LAST\r
-    }\r
-    return ret;\r
-}\r
-\r
-/*\r
- * Initialise all the fonts we will need initially. There may be as many as\r
- * three or as few as one.  The other (potentially) twenty-one fonts are done\r
- * if/when they are needed.\r
- *\r
- * We also:\r
- *\r
- * - check the font width and height, correcting our guesses if\r
- *   necessary.\r
- *\r
- * - verify that the bold font is the same width as the ordinary\r
- *   one, and engage shadow bolding if not.\r
- * \r
- * - verify that the underlined font is the same width as the\r
- *   ordinary one (manual underlining by means of line drawing can\r
- *   be done in a pinch).\r
- */\r
-static void init_fonts(int pick_width, int pick_height)\r
-{\r
-    TEXTMETRIC tm;\r
-    CPINFO cpinfo;\r
-    int fontsize[3];\r
-    int i;\r
-    HDC hdc;\r
-    int fw_dontcare, fw_bold;\r
-\r
-    for (i = 0; i < FONT_MAXNO; i++)\r
-       fonts[i] = NULL;\r
-\r
-    bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;\r
-    und_mode = UND_FONT;\r
-\r
-    if (cfg.font.isbold) {\r
-       fw_dontcare = FW_BOLD;\r
-       fw_bold = FW_HEAVY;\r
-    } else {\r
-       fw_dontcare = FW_DONTCARE;\r
-       fw_bold = FW_BOLD;\r
-    }\r
-\r
-    hdc = GetDC(hwnd);\r
-\r
-    if (pick_height)\r
-       font_height = pick_height;\r
-    else {\r
-       font_height = cfg.font.height;\r
-       if (font_height > 0) {\r
-           font_height =\r
-               -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);\r
-       }\r
-    }\r
-    font_width = pick_width;\r
-\r
-#define f(i,c,w,u) \\r
-    fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \\r
-                          c, OUT_DEFAULT_PRECIS, \\r
-                          CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality), \\r
-                          FIXED_PITCH | FF_DONTCARE, cfg.font.name)\r
-\r
-    f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);\r
-\r
-    SelectObject(hdc, fonts[FONT_NORMAL]);\r
-    GetTextMetrics(hdc, &tm);\r
-\r
-    GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);\r
-\r
-    /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */\r
-    if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {\r
-        font_varpitch = FALSE;\r
-        font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);\r
-    } else {\r
-        font_varpitch = TRUE;\r
-        font_dualwidth = TRUE;\r
-    }\r
-    if (pick_width == 0 || pick_height == 0) {\r
-       font_height = tm.tmHeight;\r
-        font_width = get_font_width(hdc, &tm);\r
-    }\r
-\r
-#ifdef RDB_DEBUG_PATCH\r
-    debug(23, "Primary font H=%d, AW=%d, MW=%d",\r
-           tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);\r
-#endif\r
-\r
-    {\r
-       CHARSETINFO info;\r
-       DWORD cset = tm.tmCharSet;\r
-       memset(&info, 0xFF, sizeof(info));\r
-\r
-       /* !!! Yes the next line is right */\r
-       if (cset == OEM_CHARSET)\r
-           ucsdata.font_codepage = GetOEMCP();\r
-       else\r
-           if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))\r
-               ucsdata.font_codepage = info.ciACP;\r
-       else\r
-           ucsdata.font_codepage = -1;\r
-\r
-       GetCPInfo(ucsdata.font_codepage, &cpinfo);\r
-       ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);\r
-    }\r
-\r
-    f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);\r
-\r
-    /*\r
-     * Some fonts, e.g. 9-pt Courier, draw their underlines\r
-     * outside their character cell. We successfully prevent\r
-     * screen corruption by clipping the text output, but then\r
-     * we lose the underline completely. Here we try to work\r
-     * out whether this is such a font, and if it is, we set a\r
-     * flag that causes underlines to be drawn by hand.\r
-     *\r
-     * Having tried other more sophisticated approaches (such\r
-     * as examining the TEXTMETRIC structure or requesting the\r
-     * height of a string), I think we'll do this the brute\r
-     * force way: we create a small bitmap, draw an underlined\r
-     * space on it, and test to see whether any pixels are\r
-     * foreground-coloured. (Since we expect the underline to\r
-     * go all the way across the character cell, we only search\r
-     * down a single column of the bitmap, half way across.)\r
-     */\r
-    {\r
-       HDC und_dc;\r
-       HBITMAP und_bm, und_oldbm;\r
-       int i, gotit;\r
-       COLORREF c;\r
-\r
-       und_dc = CreateCompatibleDC(hdc);\r
-       und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);\r
-       und_oldbm = SelectObject(und_dc, und_bm);\r
-       SelectObject(und_dc, fonts[FONT_UNDERLINE]);\r
-       SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);\r
-       SetTextColor(und_dc, RGB(255, 255, 255));\r
-       SetBkColor(und_dc, RGB(0, 0, 0));\r
-       SetBkMode(und_dc, OPAQUE);\r
-       ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);\r
-       gotit = FALSE;\r
-       for (i = 0; i < font_height; i++) {\r
-           c = GetPixel(und_dc, font_width / 2, i);\r
-           if (c != RGB(0, 0, 0))\r
-               gotit = TRUE;\r
-       }\r
-       SelectObject(und_dc, und_oldbm);\r
-       DeleteObject(und_bm);\r
-       DeleteDC(und_dc);\r
-       if (!gotit) {\r
-           und_mode = UND_LINE;\r
-           DeleteObject(fonts[FONT_UNDERLINE]);\r
-           fonts[FONT_UNDERLINE] = 0;\r
-       }\r
-    }\r
-\r
-    if (bold_mode == BOLD_FONT) {\r
-       f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);\r
-    }\r
-#undef f\r
-\r
-    descent = tm.tmAscent + 1;\r
-    if (descent >= font_height)\r
-       descent = font_height - 1;\r
-\r
-    for (i = 0; i < 3; i++) {\r
-       if (fonts[i]) {\r
-           if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))\r
-               fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;\r
-           else\r
-               fontsize[i] = -i;\r
-       } else\r
-           fontsize[i] = -i;\r
-    }\r
-\r
-    ReleaseDC(hwnd, hdc);\r
-\r
-    if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {\r
-       und_mode = UND_LINE;\r
-       DeleteObject(fonts[FONT_UNDERLINE]);\r
-       fonts[FONT_UNDERLINE] = 0;\r
-    }\r
-\r
-    if (bold_mode == BOLD_FONT &&\r
-       fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {\r
-       bold_mode = BOLD_SHADOW;\r
-       DeleteObject(fonts[FONT_BOLD]);\r
-       fonts[FONT_BOLD] = 0;\r
-    }\r
-    fontflag[0] = fontflag[1] = fontflag[2] = 1;\r
-\r
-    init_ucs(&cfg, &ucsdata);\r
-}\r
-\r
-static void another_font(int fontno)\r
-{\r
-    int basefont;\r
-    int fw_dontcare, fw_bold;\r
-    int c, u, w, x;\r
-    char *s;\r
-\r
-    if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])\r
-       return;\r
-\r
-    basefont = (fontno & ~(FONT_BOLDUND));\r
-    if (basefont != fontno && !fontflag[basefont])\r
-       another_font(basefont);\r
-\r
-    if (cfg.font.isbold) {\r
-       fw_dontcare = FW_BOLD;\r
-       fw_bold = FW_HEAVY;\r
-    } else {\r
-       fw_dontcare = FW_DONTCARE;\r
-       fw_bold = FW_BOLD;\r
-    }\r
-\r
-    c = cfg.font.charset;\r
-    w = fw_dontcare;\r
-    u = FALSE;\r
-    s = cfg.font.name;\r
-    x = font_width;\r
-\r
-    if (fontno & FONT_WIDE)\r
-       x *= 2;\r
-    if (fontno & FONT_NARROW)\r
-       x = (x+1)/2;\r
-    if (fontno & FONT_OEM)\r
-       c = OEM_CHARSET;\r
-    if (fontno & FONT_BOLD)\r
-       w = fw_bold;\r
-    if (fontno & FONT_UNDERLINE)\r
-       u = TRUE;\r
-\r
-    fonts[fontno] =\r
-       CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,\r
-                  FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,\r
-                  CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality),\r
-                  DEFAULT_PITCH | FF_DONTCARE, s);\r
-\r
-    fontflag[fontno] = 1;\r
-}\r
-\r
-static void deinit_fonts(void)\r
-{\r
-    int i;\r
-    for (i = 0; i < FONT_MAXNO; i++) {\r
-       if (fonts[i])\r
-           DeleteObject(fonts[i]);\r
-       fonts[i] = 0;\r
-       fontflag[i] = 0;\r
-    }\r
-}\r
-\r
-void request_resize(void *frontend, int w, int h)\r
-{\r
-    int width, height;\r
-\r
-    /* If the window is maximized supress resizing attempts */\r
-    if (IsZoomed(hwnd)) {\r
-       if (cfg.resize_action == RESIZE_TERM)\r
-           return;\r
-    }\r
-\r
-    if (cfg.resize_action == RESIZE_DISABLED) return;\r
-    if (h == term->rows && w == term->cols) return;\r
-\r
-    /* Sanity checks ... */\r
-    {\r
-       static int first_time = 1;\r
-       static RECT ss;\r
-\r
-       switch (first_time) {\r
-         case 1:\r
-           /* Get the size of the screen */\r
-           if (get_fullscreen_rect(&ss))\r
-               /* first_time = 0 */ ;\r
-           else {\r
-               first_time = 2;\r
-               break;\r
-           }\r
-         case 0:\r
-           /* Make sure the values are sane */\r
-           width = (ss.right - ss.left - extra_width) / 4;\r
-           height = (ss.bottom - ss.top - extra_height) / 6;\r
-\r
-           if (w > width || h > height)\r
-               return;\r
-           if (w < 15)\r
-               w = 15;\r
-           if (h < 1)\r
-               h = 1;\r
-       }\r
-    }\r
-\r
-    term_size(term, h, w, cfg.savelines);\r
-\r
-    if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {\r
-       width = extra_width + font_width * w;\r
-       height = extra_height + font_height * h;\r
-\r
-       SetWindowPos(hwnd, NULL, 0, 0, width, height,\r
-           SWP_NOACTIVATE | SWP_NOCOPYBITS |\r
-           SWP_NOMOVE | SWP_NOZORDER);\r
-    } else\r
-       reset_window(0);\r
-\r
-    InvalidateRect(hwnd, NULL, TRUE);\r
-}\r
-\r
-static void reset_window(int reinit) {\r
-    /*\r
-     * This function decides how to resize or redraw when the \r
-     * user changes something. \r
-     *\r
-     * This function doesn't like to change the terminal size but if the\r
-     * font size is locked that may be it's only soluion.\r
-     */\r
-    int win_width, win_height;\r
-    RECT cr, wr;\r
-\r
-#ifdef RDB_DEBUG_PATCH\r
-    debug((27, "reset_window()"));\r
-#endif\r
-\r
-    /* Current window sizes ... */\r
-    GetWindowRect(hwnd, &wr);\r
-    GetClientRect(hwnd, &cr);\r
-\r
-    win_width  = cr.right - cr.left;\r
-    win_height = cr.bottom - cr.top;\r
-\r
-    if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;\r
-\r
-    /* Are we being forced to reload the fonts ? */\r
-    if (reinit>1) {\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "reset_window() -- Forced deinit"));\r
-#endif\r
-       deinit_fonts();\r
-       init_fonts(0,0);\r
-    }\r
-\r
-    /* Oh, looks like we're minimised */\r
-    if (win_width == 0 || win_height == 0)\r
-       return;\r
-\r
-    /* Is the window out of position ? */\r
-    if ( !reinit && \r
-           (offset_width != (win_width-font_width*term->cols)/2 ||\r
-            offset_height != (win_height-font_height*term->rows)/2) ){\r
-       offset_width = (win_width-font_width*term->cols)/2;\r
-       offset_height = (win_height-font_height*term->rows)/2;\r
-       InvalidateRect(hwnd, NULL, TRUE);\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "reset_window() -> Reposition terminal"));\r
-#endif\r
-    }\r
-\r
-    if (IsZoomed(hwnd)) {\r
-       /* We're fullscreen, this means we must not change the size of\r
-        * the window so it's the font size or the terminal itself.\r
-        */\r
-\r
-       extra_width = wr.right - wr.left - cr.right + cr.left;\r
-       extra_height = wr.bottom - wr.top - cr.bottom + cr.top;\r
-\r
-       if (cfg.resize_action != RESIZE_TERM) {\r
-           if (  font_width != win_width/term->cols || \r
-                 font_height != win_height/term->rows) {\r
-               deinit_fonts();\r
-               init_fonts(win_width/term->cols, win_height/term->rows);\r
-               offset_width = (win_width-font_width*term->cols)/2;\r
-               offset_height = (win_height-font_height*term->rows)/2;\r
-               InvalidateRect(hwnd, NULL, TRUE);\r
-#ifdef RDB_DEBUG_PATCH\r
-               debug((25, "reset_window() -> Z font resize to (%d, %d)",\r
-                       font_width, font_height));\r
-#endif\r
-           }\r
-       } else {\r
-           if (  font_width * term->cols != win_width || \r
-                 font_height * term->rows != win_height) {\r
-               /* Our only choice at this point is to change the \r
-                * size of the terminal; Oh well.\r
-                */\r
-               term_size(term, win_height/font_height, win_width/font_width,\r
-                         cfg.savelines);\r
-               offset_width = (win_width-font_width*term->cols)/2;\r
-               offset_height = (win_height-font_height*term->rows)/2;\r
-               InvalidateRect(hwnd, NULL, TRUE);\r
-#ifdef RDB_DEBUG_PATCH\r
-               debug((27, "reset_window() -> Zoomed term_size"));\r
-#endif\r
-           }\r
-       }\r
-       return;\r
-    }\r
-\r
-    /* Hmm, a force re-init means we should ignore the current window\r
-     * so we resize to the default font size.\r
-     */\r
-    if (reinit>0) {\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "reset_window() -> Forced re-init"));\r
-#endif\r
-\r
-       offset_width = offset_height = cfg.window_border;\r
-       extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;\r
-       extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;\r
-\r
-       if (win_width != font_width*term->cols + offset_width*2 ||\r
-           win_height != font_height*term->rows + offset_height*2) {\r
-\r
-           /* If this is too large windows will resize it to the maximum\r
-            * allowed window size, we will then be back in here and resize\r
-            * the font or terminal to fit.\r
-            */\r
-           SetWindowPos(hwnd, NULL, 0, 0, \r
-                        font_width*term->cols + extra_width, \r
-                        font_height*term->rows + extra_height,\r
-                        SWP_NOMOVE | SWP_NOZORDER);\r
-       }\r
-\r
-       InvalidateRect(hwnd, NULL, TRUE);\r
-       return;\r
-    }\r
-\r
-    /* Okay the user doesn't want us to change the font so we try the \r
-     * window. But that may be too big for the screen which forces us\r
-     * to change the terminal.\r
-     */\r
-    if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||\r
-        (cfg.resize_action == RESIZE_EITHER && reinit<0) ||\r
-           reinit>0) {\r
-       offset_width = offset_height = cfg.window_border;\r
-       extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;\r
-       extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;\r
-\r
-       if (win_width != font_width*term->cols + offset_width*2 ||\r
-           win_height != font_height*term->rows + offset_height*2) {\r
-\r
-           static RECT ss;\r
-           int width, height;\r
-               \r
-               get_fullscreen_rect(&ss);\r
-\r
-           width = (ss.right - ss.left - extra_width) / font_width;\r
-           height = (ss.bottom - ss.top - extra_height) / font_height;\r
-\r
-           /* Grrr too big */\r
-           if ( term->rows > height || term->cols > width ) {\r
-               if (cfg.resize_action == RESIZE_EITHER) {\r
-                   /* Make the font the biggest we can */\r
-                   if (term->cols > width)\r
-                       font_width = (ss.right - ss.left - extra_width)\r
-                           / term->cols;\r
-                   if (term->rows > height)\r
-                       font_height = (ss.bottom - ss.top - extra_height)\r
-                           / term->rows;\r
-\r
-                   deinit_fonts();\r
-                   init_fonts(font_width, font_height);\r
-\r
-                   width = (ss.right - ss.left - extra_width) / font_width;\r
-                   height = (ss.bottom - ss.top - extra_height) / font_height;\r
-               } else {\r
-                   if ( height > term->rows ) height = term->rows;\r
-                   if ( width > term->cols )  width = term->cols;\r
-                   term_size(term, height, width, cfg.savelines);\r
-#ifdef RDB_DEBUG_PATCH\r
-                   debug((27, "reset_window() -> term resize to (%d,%d)",\r
-                              height, width));\r
-#endif\r
-               }\r
-           }\r
-           \r
-           SetWindowPos(hwnd, NULL, 0, 0, \r
-                        font_width*term->cols + extra_width, \r
-                        font_height*term->rows + extra_height,\r
-                        SWP_NOMOVE | SWP_NOZORDER);\r
-\r
-           InvalidateRect(hwnd, NULL, TRUE);\r
-#ifdef RDB_DEBUG_PATCH\r
-           debug((27, "reset_window() -> window resize to (%d,%d)",\r
-                       font_width*term->cols + extra_width,\r
-                       font_height*term->rows + extra_height));\r
-#endif\r
-       }\r
-       return;\r
-    }\r
-\r
-    /* We're allowed to or must change the font but do we want to ?  */\r
-\r
-    if (font_width != (win_width-cfg.window_border*2)/term->cols || \r
-       font_height != (win_height-cfg.window_border*2)/term->rows) {\r
-\r
-       deinit_fonts();\r
-       init_fonts((win_width-cfg.window_border*2)/term->cols, \r
-                  (win_height-cfg.window_border*2)/term->rows);\r
-       offset_width = (win_width-font_width*term->cols)/2;\r
-       offset_height = (win_height-font_height*term->rows)/2;\r
-\r
-       extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;\r
-       extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;\r
-\r
-       InvalidateRect(hwnd, NULL, TRUE);\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((25, "reset_window() -> font resize to (%d,%d)", \r
-                  font_width, font_height));\r
-#endif\r
-    }\r
-}\r
-\r
-static void set_input_locale(HKL kl)\r
-{\r
-    char lbuf[20];\r
-\r
-    GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,\r
-                 lbuf, sizeof(lbuf));\r
-\r
-    kbd_codepage = atoi(lbuf);\r
-}\r
-\r
-static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)\r
-{\r
-    int thistime = GetMessageTime();\r
-\r
-    if (send_raw_mouse && !(cfg.mouse_override && shift)) {\r
-       lastbtn = MBT_NOTHING;\r
-       term_mouse(term, b, translate_button(b), MA_CLICK,\r
-                  x, y, shift, ctrl, alt);\r
-       return;\r
-    }\r
-\r
-    if (lastbtn == b && thistime - lasttime < dbltime) {\r
-       lastact = (lastact == MA_CLICK ? MA_2CLK :\r
-                  lastact == MA_2CLK ? MA_3CLK :\r
-                  lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);\r
-    } else {\r
-       lastbtn = b;\r
-       lastact = MA_CLICK;\r
-    }\r
-    if (lastact != MA_NOTHING)\r
-       term_mouse(term, b, translate_button(b), lastact,\r
-                  x, y, shift, ctrl, alt);\r
-    lasttime = thistime;\r
-}\r
-\r
-/*\r
- * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)\r
- * into a cooked one (SELECT, EXTEND, PASTE).\r
- */\r
-static Mouse_Button translate_button(Mouse_Button button)\r
-{\r
-    if (button == MBT_LEFT)\r
-       return MBT_SELECT;\r
-    if (button == MBT_MIDDLE)\r
-       return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;\r
-    if (button == MBT_RIGHT)\r
-       return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;\r
-    return 0;                         /* shouldn't happen */\r
-}\r
-\r
-static void show_mouseptr(int show)\r
-{\r
-    /* NB that the counter in ShowCursor() is also frobbed by\r
-     * update_mouse_pointer() */\r
-    static int cursor_visible = 1;\r
-    if (!cfg.hide_mouseptr)           /* override if this feature disabled */\r
-       show = 1;\r
-    if (cursor_visible && !show)\r
-       ShowCursor(FALSE);\r
-    else if (!cursor_visible && show)\r
-       ShowCursor(TRUE);\r
-    cursor_visible = show;\r
-}\r
-\r
-static int is_alt_pressed(void)\r
-{\r
-    BYTE keystate[256];\r
-    int r = GetKeyboardState(keystate);\r
-    if (!r)\r
-       return FALSE;\r
-    if (keystate[VK_MENU] & 0x80)\r
-       return TRUE;\r
-    if (keystate[VK_RMENU] & 0x80)\r
-       return TRUE;\r
-    return FALSE;\r
-}\r
-\r
-static int resizing;\r
-\r
-void notify_remote_exit(void *fe)\r
-{\r
-    int exitcode;\r
-\r
-    if (!session_closed &&\r
-        (exitcode = back->exitcode(backhandle)) >= 0) {\r
-       /* Abnormal exits will already have set session_closed and taken\r
-        * appropriate action. */\r
-       if (cfg.close_on_exit == FORCE_ON ||\r
-           (cfg.close_on_exit == AUTO && exitcode != INT_MAX)) {\r
-           PostQuitMessage(0);\r
-       } else {\r
-           must_close_session = TRUE;\r
-           session_closed = TRUE;\r
-           /* exitcode == INT_MAX indicates that the connection was closed\r
-            * by a fatal error, so an error box will be coming our way and\r
-            * we should not generate this informational one. */\r
-           if (exitcode != INT_MAX)\r
-               MessageBox(hwnd, "Connection closed by remote host",\r
-                          appname, MB_OK | MB_ICONINFORMATION);\r
-       }\r
-    }\r
-}\r
-\r
-void timer_change_notify(long next)\r
-{\r
-    long ticks = next - GETTICKCOUNT();\r
-    if (ticks <= 0) ticks = 1;        /* just in case */\r
-    KillTimer(hwnd, TIMING_TIMER_ID);\r
-    SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);\r
-    timing_next_time = next;\r
-}\r
-\r
-static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,\r
-                               WPARAM wParam, LPARAM lParam)\r
-{\r
-    HDC hdc;\r
-    static int ignore_clip = FALSE;\r
-    static int need_backend_resize = FALSE;\r
-    static int fullscr_on_max = FALSE;\r
-    static int processed_resize = FALSE;\r
-    static UINT last_mousemove = 0;\r
-\r
-    switch (message) {\r
-      case WM_TIMER:\r
-       if ((UINT_PTR)wParam == TIMING_TIMER_ID) {\r
-           long next;\r
-\r
-           KillTimer(hwnd, TIMING_TIMER_ID);\r
-           if (run_timers(timing_next_time, &next)) {\r
-               timer_change_notify(next);\r
-           } else {\r
-           }\r
-       }\r
-       return 0;\r
-      case WM_CREATE:\r
-       break;\r
-      case WM_CLOSE:\r
-       {\r
-           char *str;\r
-           show_mouseptr(1);\r
-           str = dupprintf("%s Exit Confirmation", appname);\r
-           if (!cfg.warn_on_close || session_closed ||\r
-               MessageBox(hwnd,\r
-                          "Are you sure you want to close this session?",\r
-                          str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)\r
-               == IDOK)\r
-               DestroyWindow(hwnd);\r
-           sfree(str);\r
-       }\r
-       return 0;\r
-      case WM_DESTROY:\r
-       show_mouseptr(1);\r
-       PostQuitMessage(0);\r
-       return 0;\r
-      case WM_INITMENUPOPUP:\r
-       if ((HMENU)wParam == savedsess_menu) {\r
-           /* About to pop up Saved Sessions sub-menu.\r
-            * Refresh the session list. */\r
-           get_sesslist(&sesslist, FALSE); /* free */\r
-           get_sesslist(&sesslist, TRUE);\r
-           update_savedsess_menu();\r
-           return 0;\r
-       }\r
-       break;\r
-      case WM_COMMAND:\r
-      case WM_SYSCOMMAND:\r
-       switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */\r
-         case IDM_SHOWLOG:\r
-           showeventlog(hwnd);\r
-           break;\r
-         case IDM_NEWSESS:\r
-         case IDM_DUPSESS:\r
-         case IDM_SAVEDSESS:\r
-           {\r
-               char b[2048];\r
-               char c[30], *cl;\r
-               int freecl = FALSE;\r
-               BOOL inherit_handles;\r
-               STARTUPINFO si;\r
-               PROCESS_INFORMATION pi;\r
-               HANDLE filemap = NULL;\r
-\r
-               if (wParam == IDM_DUPSESS) {\r
-                   /*\r
-                    * Allocate a file-mapping memory chunk for the\r
-                    * config structure.\r
-                    */\r
-                   SECURITY_ATTRIBUTES sa;\r
-                   Config *p;\r
-\r
-                   sa.nLength = sizeof(sa);\r
-                   sa.lpSecurityDescriptor = NULL;\r
-                   sa.bInheritHandle = TRUE;\r
-                   filemap = CreateFileMapping(INVALID_HANDLE_VALUE,\r
-                                               &sa,\r
-                                               PAGE_READWRITE,\r
-                                               0, sizeof(Config), NULL);\r
-                   if (filemap && filemap != INVALID_HANDLE_VALUE) {\r
-                       p = (Config *) MapViewOfFile(filemap,\r
-                                                    FILE_MAP_WRITE,\r
-                                                    0, 0, sizeof(Config));\r
-                       if (p) {\r
-                           *p = cfg;  /* structure copy */\r
-                           UnmapViewOfFile(p);\r
-                       }\r
-                   }\r
-                   inherit_handles = TRUE;\r
-                   sprintf(c, "putty &%p", filemap);\r
-                   cl = c;\r
-               } else if (wParam == IDM_SAVEDSESS) {\r
-                   unsigned int sessno = ((lParam - IDM_SAVED_MIN)\r
-                                          / MENU_SAVED_STEP) + 1;\r
-                   if (sessno < (unsigned)sesslist.nsessions) {\r
-                       char *session = sesslist.sessions[sessno];\r
-                       cl = dupprintf("putty @%s", session);\r
-                       inherit_handles = FALSE;\r
-                       freecl = TRUE;\r
-                   } else\r
-                       break;\r
-               } else /* IDM_NEWSESS */ {\r
-                   cl = NULL;\r
-                   inherit_handles = FALSE;\r
-               }\r
-\r
-               GetModuleFileName(NULL, b, sizeof(b) - 1);\r
-               si.cb = sizeof(si);\r
-               si.lpReserved = NULL;\r
-               si.lpDesktop = NULL;\r
-               si.lpTitle = NULL;\r
-               si.dwFlags = 0;\r
-               si.cbReserved2 = 0;\r
-               si.lpReserved2 = NULL;\r
-               CreateProcess(b, cl, NULL, NULL, inherit_handles,\r
-                             NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);\r
-\r
-               if (filemap)\r
-                   CloseHandle(filemap);\r
-               if (freecl)\r
-                   sfree(cl);\r
-           }\r
-           break;\r
-         case IDM_RESTART:\r
-           if (!back) {\r
-               logevent(NULL, "----- Session restarted -----");\r
-               term_pwron(term, FALSE);\r
-               start_backend();\r
-           }\r
-\r
-           break;\r
-         case IDM_RECONF:\r
-           {\r
-               Config prev_cfg;\r
-               int init_lvl = 1;\r
-               int reconfig_result;\r
-\r
-               if (reconfiguring)\r
-                   break;\r
-               else\r
-                   reconfiguring = TRUE;\r
-\r
-               GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));\r
-               prev_cfg = cfg;\r
-\r
-               reconfig_result =\r
-                   do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);\r
-               reconfiguring = FALSE;\r
-               if (!reconfig_result)\r
-                   break;\r
-\r
-               {\r
-                   /* Disable full-screen if resizing forbidden */\r
-                   int i;\r
-                   for (i = 0; i < lenof(popup_menus); i++)\r
-                       EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,\r
-                                      MF_BYCOMMAND | \r
-                                      (cfg.resize_action == RESIZE_DISABLED)\r
-                                      ? MF_GRAYED : MF_ENABLED);\r
-                   /* Gracefully unzoom if necessary */\r
-                   if (IsZoomed(hwnd) &&\r
-                       (cfg.resize_action == RESIZE_DISABLED)) {\r
-                       ShowWindow(hwnd, SW_RESTORE);\r
-                   }\r
-               }\r
-\r
-               /* Pass new config data to the logging module */\r
-               log_reconfig(logctx, &cfg);\r
-\r
-               sfree(logpal);\r
-               /*\r
-                * Flush the line discipline's edit buffer in the\r
-                * case where local editing has just been disabled.\r
-                */\r
-               if (ldisc)\r
-                   ldisc_send(ldisc, NULL, 0, 0);\r
-               if (pal)\r
-                   DeleteObject(pal);\r
-               logpal = NULL;\r
-               pal = NULL;\r
-               cfgtopalette();\r
-               init_palette();\r
-\r
-               /* Pass new config data to the terminal */\r
-               term_reconfig(term, &cfg);\r
-\r
-               /* Pass new config data to the back end */\r
-               if (back)\r
-                   back->reconfig(backhandle, &cfg);\r
-\r
-               /* Screen size changed ? */\r
-               if (cfg.height != prev_cfg.height ||\r
-                   cfg.width != prev_cfg.width ||\r
-                   cfg.savelines != prev_cfg.savelines ||\r
-                   cfg.resize_action == RESIZE_FONT ||\r
-                   (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||\r
-                   cfg.resize_action == RESIZE_DISABLED)\r
-                   term_size(term, cfg.height, cfg.width, cfg.savelines);\r
-\r
-               /* Enable or disable the scroll bar, etc */\r
-               {\r
-                   LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);\r
-                   LONG nexflag, exflag =\r
-                       GetWindowLongPtr(hwnd, GWL_EXSTYLE);\r
-\r
-                   nexflag = exflag;\r
-                   if (cfg.alwaysontop != prev_cfg.alwaysontop) {\r
-                       if (cfg.alwaysontop) {\r
-                           nexflag |= WS_EX_TOPMOST;\r
-                           SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,\r
-                                        SWP_NOMOVE | SWP_NOSIZE);\r
-                       } else {\r
-                           nexflag &= ~(WS_EX_TOPMOST);\r
-                           SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,\r
-                                        SWP_NOMOVE | SWP_NOSIZE);\r
-                       }\r
-                   }\r
-                   if (cfg.sunken_edge)\r
-                       nexflag |= WS_EX_CLIENTEDGE;\r
-                   else\r
-                       nexflag &= ~(WS_EX_CLIENTEDGE);\r
-\r
-                   nflg = flag;\r
-                   if (is_full_screen() ?\r
-                       cfg.scrollbar_in_fullscreen : cfg.scrollbar)\r
-                       nflg |= WS_VSCROLL;\r
-                   else\r
-                       nflg &= ~WS_VSCROLL;\r
-\r
-                   if (cfg.resize_action == RESIZE_DISABLED ||\r
-                        is_full_screen())\r
-                       nflg &= ~WS_THICKFRAME;\r
-                   else\r
-                       nflg |= WS_THICKFRAME;\r
-\r
-                   if (cfg.resize_action == RESIZE_DISABLED)\r
-                       nflg &= ~WS_MAXIMIZEBOX;\r
-                   else\r
-                       nflg |= WS_MAXIMIZEBOX;\r
-\r
-                   if (nflg != flag || nexflag != exflag) {\r
-                       if (nflg != flag)\r
-                           SetWindowLongPtr(hwnd, GWL_STYLE, nflg);\r
-                       if (nexflag != exflag)\r
-                           SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);\r
-\r
-                       SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\r
-                                    SWP_NOACTIVATE | SWP_NOCOPYBITS |\r
-                                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |\r
-                                    SWP_FRAMECHANGED);\r
-\r
-                       init_lvl = 2;\r
-                   }\r
-               }\r
-\r
-               /* Oops */\r
-               if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {\r
-                   force_normal(hwnd);\r
-                   init_lvl = 2;\r
-               }\r
-\r
-               set_title(NULL, cfg.wintitle);\r
-               if (IsIconic(hwnd)) {\r
-                   SetWindowText(hwnd,\r
-                                 cfg.win_name_always ? window_name :\r
-                                 icon_name);\r
-               }\r
-\r
-               if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||\r
-                   strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||\r
-                   cfg.font.isbold != prev_cfg.font.isbold ||\r
-                   cfg.font.height != prev_cfg.font.height ||\r
-                   cfg.font.charset != prev_cfg.font.charset ||\r
-                   cfg.font_quality != prev_cfg.font_quality ||\r
-                   cfg.vtmode != prev_cfg.vtmode ||\r
-                   cfg.bold_colour != prev_cfg.bold_colour ||\r
-                   cfg.resize_action == RESIZE_DISABLED ||\r
-                   cfg.resize_action == RESIZE_EITHER ||\r
-                   (cfg.resize_action != prev_cfg.resize_action))\r
-                   init_lvl = 2;\r
-\r
-               InvalidateRect(hwnd, NULL, TRUE);\r
-               reset_window(init_lvl);\r
-               net_pending_errors();\r
-           }\r
-           break;\r
-         case IDM_COPYALL:\r
-           term_copyall(term);\r
-           break;\r
-         case IDM_PASTE:\r
-           request_paste(NULL);\r
-           break;\r
-         case IDM_CLRSB:\r
-           term_clrsb(term);\r
-           break;\r
-         case IDM_RESET:\r
-           term_pwron(term, TRUE);\r
-           if (ldisc)\r
-               ldisc_send(ldisc, NULL, 0, 0);\r
-           break;\r
-         case IDM_ABOUT:\r
-           showabout(hwnd);\r
-           break;\r
-         case IDM_HELP:\r
-           launch_help(hwnd, NULL);\r
-           break;\r
-         case SC_MOUSEMENU:\r
-           /*\r
-            * We get this if the System menu has been activated\r
-            * using the mouse.\r
-            */\r
-           show_mouseptr(1);\r
-           break;\r
-          case SC_KEYMENU:\r
-           /*\r
-            * We get this if the System menu has been activated\r
-            * using the keyboard. This might happen from within\r
-            * TranslateKey, in which case it really wants to be\r
-            * followed by a `space' character to actually _bring\r
-            * the menu up_ rather than just sitting there in\r
-            * `ready to appear' state.\r
-            */\r
-           show_mouseptr(1);          /* make sure pointer is visible */\r
-           if( lParam == 0 )\r
-               PostMessage(hwnd, WM_CHAR, ' ', 0);\r
-           break;\r
-         case IDM_FULLSCREEN:\r
-           flip_full_screen();\r
-           break;\r
-         default:\r
-           if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {\r
-               SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);\r
-           }\r
-           if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {\r
-               int i = (wParam - IDM_SPECIAL_MIN) / 0x10;\r
-               /*\r
-                * Ensure we haven't been sent a bogus SYSCOMMAND\r
-                * which would cause us to reference invalid memory\r
-                * and crash. Perhaps I'm just too paranoid here.\r
-                */\r
-               if (i >= n_specials)\r
-                   break;\r
-               if (back)\r
-                   back->special(backhandle, specials[i].code);\r
-               net_pending_errors();\r
-           }\r
-       }\r
-       break;\r
-\r
-#define X_POS(l) ((int)(short)LOWORD(l))\r
-#define Y_POS(l) ((int)(short)HIWORD(l))\r
-\r
-#define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)\r
-#define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)\r
-      case WM_LBUTTONDOWN:\r
-      case WM_MBUTTONDOWN:\r
-      case WM_RBUTTONDOWN:\r
-      case WM_LBUTTONUP:\r
-      case WM_MBUTTONUP:\r
-      case WM_RBUTTONUP:\r
-       if (message == WM_RBUTTONDOWN &&\r
-           ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {\r
-           POINT cursorpos;\r
-\r
-           show_mouseptr(1);          /* make sure pointer is visible */\r
-           GetCursorPos(&cursorpos);\r
-           TrackPopupMenu(popup_menus[CTXMENU].menu,\r
-                          TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,\r
-                          cursorpos.x, cursorpos.y,\r
-                          0, hwnd, NULL);\r
-           break;\r
-       }\r
-       {\r
-           int button, press;\r
-\r
-           switch (message) {\r
-             case WM_LBUTTONDOWN:\r
-               button = MBT_LEFT;\r
-               wParam |= MK_LBUTTON;\r
-               press = 1;\r
-               break;\r
-             case WM_MBUTTONDOWN:\r
-               button = MBT_MIDDLE;\r
-               wParam |= MK_MBUTTON;\r
-               press = 1;\r
-               break;\r
-             case WM_RBUTTONDOWN:\r
-               button = MBT_RIGHT;\r
-               wParam |= MK_RBUTTON;\r
-               press = 1;\r
-               break;\r
-             case WM_LBUTTONUP:\r
-               button = MBT_LEFT;\r
-               wParam &= ~MK_LBUTTON;\r
-               press = 0;\r
-               break;\r
-             case WM_MBUTTONUP:\r
-               button = MBT_MIDDLE;\r
-               wParam &= ~MK_MBUTTON;\r
-               press = 0;\r
-               break;\r
-             case WM_RBUTTONUP:\r
-               button = MBT_RIGHT;\r
-               wParam &= ~MK_RBUTTON;\r
-               press = 0;\r
-               break;\r
-             default:\r
-               button = press = 0;    /* shouldn't happen */\r
-           }\r
-           show_mouseptr(1);\r
-           /*\r
-            * Special case: in full-screen mode, if the left\r
-            * button is clicked in the very top left corner of the\r
-            * window, we put up the System menu instead of doing\r
-            * selection.\r
-            */\r
-           {\r
-               char mouse_on_hotspot = 0;\r
-               POINT pt;\r
-\r
-               GetCursorPos(&pt);\r
-#ifndef NO_MULTIMON\r
-               {\r
-                   HMONITOR mon;\r
-                   MONITORINFO mi;\r
-\r
-                   mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);\r
-\r
-                   if (mon != NULL) {\r
-                       mi.cbSize = sizeof(MONITORINFO);\r
-                       GetMonitorInfo(mon, &mi);\r
-\r
-                       if (mi.rcMonitor.left == pt.x &&\r
-                           mi.rcMonitor.top == pt.y) {\r
-                           mouse_on_hotspot = 1;\r
-                       }\r
-                   }\r
-               }\r
-#else\r
-               if (pt.x == 0 && pt.y == 0) {\r
-                   mouse_on_hotspot = 1;\r
-               }\r
-#endif\r
-               if (is_full_screen() && press &&\r
-                   button == MBT_LEFT && mouse_on_hotspot) {\r
-                   SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,\r
-                               MAKELPARAM(pt.x, pt.y));\r
-                   return 0;\r
-               }\r
-           }\r
-\r
-           if (press) {\r
-               click(button,\r
-                     TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),\r
-                     wParam & MK_SHIFT, wParam & MK_CONTROL,\r
-                     is_alt_pressed());\r
-               SetCapture(hwnd);\r
-           } else {\r
-               term_mouse(term, button, translate_button(button), MA_RELEASE,\r
-                          TO_CHR_X(X_POS(lParam)),\r
-                          TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,\r
-                          wParam & MK_CONTROL, is_alt_pressed());\r
-               if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))\r
-                   ReleaseCapture();\r
-           }\r
-       }\r
-       return 0;\r
-      case WM_MOUSEMOVE:\r
-       {\r
-           /*\r
-            * Windows seems to like to occasionally send MOUSEMOVE\r
-            * events even if the mouse hasn't moved. Don't unhide\r
-            * the mouse pointer in this case.\r
-            */\r
-           static WPARAM wp = 0;\r
-           static LPARAM lp = 0;\r
-           if (wParam != wp || lParam != lp ||\r
-               last_mousemove != WM_MOUSEMOVE) {\r
-               show_mouseptr(1);\r
-               wp = wParam; lp = lParam;\r
-               last_mousemove = WM_MOUSEMOVE;\r
-           }\r
-       }\r
-       /*\r
-        * Add the mouse position and message time to the random\r
-        * number noise.\r
-        */\r
-       noise_ultralight(lParam);\r
-\r
-       if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&\r
-           GetCapture() == hwnd) {\r
-           Mouse_Button b;\r
-           if (wParam & MK_LBUTTON)\r
-               b = MBT_LEFT;\r
-           else if (wParam & MK_MBUTTON)\r
-               b = MBT_MIDDLE;\r
-           else\r
-               b = MBT_RIGHT;\r
-           term_mouse(term, b, translate_button(b), MA_DRAG,\r
-                      TO_CHR_X(X_POS(lParam)),\r
-                      TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,\r
-                      wParam & MK_CONTROL, is_alt_pressed());\r
-       }\r
-       return 0;\r
-      case WM_NCMOUSEMOVE:\r
-       {\r
-           static WPARAM wp = 0;\r
-           static LPARAM lp = 0;\r
-           if (wParam != wp || lParam != lp ||\r
-               last_mousemove != WM_NCMOUSEMOVE) {\r
-               show_mouseptr(1);\r
-               wp = wParam; lp = lParam;\r
-               last_mousemove = WM_NCMOUSEMOVE;\r
-           }\r
-       }\r
-       noise_ultralight(lParam);\r
-       break;\r
-      case WM_IGNORE_CLIP:\r
-       ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */\r
-       break;\r
-      case WM_DESTROYCLIPBOARD:\r
-       if (!ignore_clip)\r
-           term_deselect(term);\r
-       ignore_clip = FALSE;\r
-       return 0;\r
-      case WM_PAINT:\r
-       {\r
-           PAINTSTRUCT p;\r
-\r
-           HideCaret(hwnd);\r
-           hdc = BeginPaint(hwnd, &p);\r
-           if (pal) {\r
-               SelectPalette(hdc, pal, TRUE);\r
-               RealizePalette(hdc);\r
-           }\r
-\r
-           /*\r
-            * We have to be careful about term_paint(). It will\r
-            * set a bunch of character cells to INVALID and then\r
-            * call do_paint(), which will redraw those cells and\r
-            * _then mark them as done_. This may not be accurate:\r
-            * when painting in WM_PAINT context we are restricted\r
-            * to the rectangle which has just been exposed - so if\r
-            * that only covers _part_ of a character cell and the\r
-            * rest of it was already visible, that remainder will\r
-            * not be redrawn at all. Accordingly, we must not\r
-            * paint any character cell in a WM_PAINT context which\r
-            * already has a pending update due to terminal output.\r
-            * The simplest solution to this - and many, many\r
-            * thanks to Hung-Te Lin for working all this out - is\r
-            * not to do any actual painting at _all_ if there's a\r
-            * pending terminal update: just mark the relevant\r
-            * character cells as INVALID and wait for the\r
-            * scheduled full update to sort it out.\r
-            * \r
-            * I have a suspicion this isn't the _right_ solution.\r
-            * An alternative approach would be to have terminal.c\r
-            * separately track what _should_ be on the terminal\r
-            * screen and what _is_ on the terminal screen, and\r
-            * have two completely different types of redraw (one\r
-            * for full updates, which syncs the former with the\r
-            * terminal itself, and one for WM_PAINT which syncs\r
-            * the latter with the former); yet another possibility\r
-            * would be to have the Windows front end do what the\r
-            * GTK one already does, and maintain a bitmap of the\r
-            * current terminal appearance so that WM_PAINT becomes\r
-            * completely trivial. However, this should do for now.\r
-            */\r
-           term_paint(term, hdc, \r
-                      (p.rcPaint.left-offset_width)/font_width,\r
-                      (p.rcPaint.top-offset_height)/font_height,\r
-                      (p.rcPaint.right-offset_width-1)/font_width,\r
-                      (p.rcPaint.bottom-offset_height-1)/font_height,\r
-                      !term->window_update_pending);\r
-\r
-           if (p.fErase ||\r
-               p.rcPaint.left  < offset_width  ||\r
-               p.rcPaint.top   < offset_height ||\r
-               p.rcPaint.right >= offset_width + font_width*term->cols ||\r
-               p.rcPaint.bottom>= offset_height + font_height*term->rows)\r
-           {\r
-               HBRUSH fillcolour, oldbrush;\r
-               HPEN   edge, oldpen;\r
-               fillcolour = CreateSolidBrush (\r
-                                   colours[ATTR_DEFBG>>ATTR_BGSHIFT]);\r
-               oldbrush = SelectObject(hdc, fillcolour);\r
-               edge = CreatePen(PS_SOLID, 0, \r
-                                   colours[ATTR_DEFBG>>ATTR_BGSHIFT]);\r
-               oldpen = SelectObject(hdc, edge);\r
-\r
-               /*\r
-                * Jordan Russell reports that this apparently\r
-                * ineffectual IntersectClipRect() call masks a\r
-                * Windows NT/2K bug causing strange display\r
-                * problems when the PuTTY window is taller than\r
-                * the primary monitor. It seems harmless enough...\r
-                */\r
-               IntersectClipRect(hdc,\r
-                       p.rcPaint.left, p.rcPaint.top,\r
-                       p.rcPaint.right, p.rcPaint.bottom);\r
-\r
-               ExcludeClipRect(hdc, \r
-                       offset_width, offset_height,\r
-                       offset_width+font_width*term->cols,\r
-                       offset_height+font_height*term->rows);\r
-\r
-               Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, \r
-                         p.rcPaint.right, p.rcPaint.bottom);\r
-\r
-               /* SelectClipRgn(hdc, NULL); */\r
-\r
-               SelectObject(hdc, oldbrush);\r
-               DeleteObject(fillcolour);\r
-               SelectObject(hdc, oldpen);\r
-               DeleteObject(edge);\r
-           }\r
-           SelectObject(hdc, GetStockObject(SYSTEM_FONT));\r
-           SelectObject(hdc, GetStockObject(WHITE_PEN));\r
-           EndPaint(hwnd, &p);\r
-           ShowCaret(hwnd);\r
-       }\r
-       return 0;\r
-      case WM_NETEVENT:\r
-       /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc\r
-        * but the only one that's likely to try to overload us is FD_READ.\r
-        * This means buffering just one is fine.\r
-        */\r
-       if (pending_netevent)\r
-           enact_pending_netevent();\r
-\r
-       pending_netevent = TRUE;\r
-       pend_netevent_wParam = wParam;\r
-       pend_netevent_lParam = lParam;\r
-       if (WSAGETSELECTEVENT(lParam) != FD_READ)\r
-           enact_pending_netevent();\r
-\r
-       net_pending_errors();\r
-       return 0;\r
-      case WM_SETFOCUS:\r
-       term_set_focus(term, TRUE);\r
-       CreateCaret(hwnd, caretbm, font_width, font_height);\r
-       ShowCaret(hwnd);\r
-       flash_window(0);               /* stop */\r
-       compose_state = 0;\r
-       term_update(term);\r
-       break;\r
-      case WM_KILLFOCUS:\r
-       show_mouseptr(1);\r
-       term_set_focus(term, FALSE);\r
-       DestroyCaret();\r
-       caret_x = caret_y = -1;        /* ensure caret is replaced next time */\r
-       term_update(term);\r
-       break;\r
-      case WM_ENTERSIZEMOVE:\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "WM_ENTERSIZEMOVE"));\r
-#endif\r
-       EnableSizeTip(1);\r
-       resizing = TRUE;\r
-       need_backend_resize = FALSE;\r
-       break;\r
-      case WM_EXITSIZEMOVE:\r
-       EnableSizeTip(0);\r
-       resizing = FALSE;\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "WM_EXITSIZEMOVE"));\r
-#endif\r
-       if (need_backend_resize) {\r
-           term_size(term, cfg.height, cfg.width, cfg.savelines);\r
-           InvalidateRect(hwnd, NULL, TRUE);\r
-       }\r
-       break;\r
-      case WM_SIZING:\r
-       /*\r
-        * This does two jobs:\r
-        * 1) Keep the sizetip uptodate\r
-        * 2) Make sure the window size is _stepped_ in units of the font size.\r
-        */\r
-        if (cfg.resize_action == RESIZE_TERM ||\r
-            (cfg.resize_action == RESIZE_EITHER && !is_alt_pressed())) {\r
-           int width, height, w, h, ew, eh;\r
-           LPRECT r = (LPRECT) lParam;\r
-\r
-           if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&\r
-                   (cfg.height != term->rows || cfg.width != term->cols )) {\r
-               /* \r
-                * Great! It seems that both the terminal size and the\r
-                * font size have been changed and the user is now dragging.\r
-                * \r
-                * It will now be difficult to get back to the configured\r
-                * font size!\r
-                *\r
-                * This would be easier but it seems to be too confusing.\r
-\r
-               term_size(term, cfg.height, cfg.width, cfg.savelines);\r
-               reset_window(2);\r
-                */\r
-               cfg.height=term->rows; cfg.width=term->cols;\r
-\r
-               InvalidateRect(hwnd, NULL, TRUE);\r
-               need_backend_resize = TRUE;\r
-           }\r
-\r
-           width = r->right - r->left - extra_width;\r
-           height = r->bottom - r->top - extra_height;\r
-           w = (width + font_width / 2) / font_width;\r
-           if (w < 1)\r
-               w = 1;\r
-           h = (height + font_height / 2) / font_height;\r
-           if (h < 1)\r
-               h = 1;\r
-           UpdateSizeTip(hwnd, w, h);\r
-           ew = width - w * font_width;\r
-           eh = height - h * font_height;\r
-           if (ew != 0) {\r
-               if (wParam == WMSZ_LEFT ||\r
-                   wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)\r
-                   r->left += ew;\r
-               else\r
-                   r->right -= ew;\r
-           }\r
-           if (eh != 0) {\r
-               if (wParam == WMSZ_TOP ||\r
-                   wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)\r
-                   r->top += eh;\r
-               else\r
-                   r->bottom -= eh;\r
-           }\r
-           if (ew || eh)\r
-               return 1;\r
-           else\r
-               return 0;\r
-       } else {\r
-           int width, height, w, h, rv = 0;\r
-           int ex_width = extra_width + (cfg.window_border - offset_width) * 2;\r
-           int ex_height = extra_height + (cfg.window_border - offset_height) * 2;\r
-           LPRECT r = (LPRECT) lParam;\r
-\r
-           width = r->right - r->left - ex_width;\r
-           height = r->bottom - r->top - ex_height;\r
-\r
-           w = (width + term->cols/2)/term->cols;\r
-           h = (height + term->rows/2)/term->rows;\r
-           if ( r->right != r->left + w*term->cols + ex_width)\r
-               rv = 1;\r
-\r
-           if (wParam == WMSZ_LEFT ||\r
-               wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)\r
-               r->left = r->right - w*term->cols - ex_width;\r
-           else\r
-               r->right = r->left + w*term->cols + ex_width;\r
-\r
-           if (r->bottom != r->top + h*term->rows + ex_height)\r
-               rv = 1;\r
-\r
-           if (wParam == WMSZ_TOP ||\r
-               wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)\r
-               r->top = r->bottom - h*term->rows - ex_height;\r
-           else\r
-               r->bottom = r->top + h*term->rows + ex_height;\r
-\r
-           return rv;\r
-       }\r
-       /* break;  (never reached) */\r
-      case WM_FULLSCR_ON_MAX:\r
-       fullscr_on_max = TRUE;\r
-       break;\r
-      case WM_MOVE:\r
-       sys_cursor_update();\r
-       break;\r
-      case WM_SIZE:\r
-#ifdef RDB_DEBUG_PATCH\r
-       debug((27, "WM_SIZE %s (%d,%d)",\r
-               (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":\r
-               (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":\r
-               (wParam == SIZE_RESTORED && resizing) ? "to":\r
-               (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":\r
-               "...",\r
-           LOWORD(lParam), HIWORD(lParam)));\r
-#endif\r
-       if (wParam == SIZE_MINIMIZED)\r
-           SetWindowText(hwnd,\r
-                         cfg.win_name_always ? window_name : icon_name);\r
-       if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)\r
-           SetWindowText(hwnd, window_name);\r
-        if (wParam == SIZE_RESTORED) {\r
-            processed_resize = FALSE;\r
-            clear_full_screen();\r
-            if (processed_resize) {\r
-                /*\r
-                 * Inhibit normal processing of this WM_SIZE; a\r
-                 * secondary one was triggered just now by\r
-                 * clear_full_screen which contained the correct\r
-                 * client area size.\r
-                 */\r
-                return 0;\r
-            }\r
-        }\r
-        if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {\r
-            fullscr_on_max = FALSE;\r
-            processed_resize = FALSE;\r
-            make_full_screen();\r
-            if (processed_resize) {\r
-                /*\r
-                 * Inhibit normal processing of this WM_SIZE; a\r
-                 * secondary one was triggered just now by\r
-                 * make_full_screen which contained the correct client\r
-                 * area size.\r
-                 */\r
-                return 0;\r
-            }\r
-        }\r
-\r
-        processed_resize = TRUE;\r
-\r
-       if (cfg.resize_action == RESIZE_DISABLED) {\r
-           /* A resize, well it better be a minimize. */\r
-           reset_window(-1);\r
-       } else {\r
-\r
-           int width, height, w, h;\r
-\r
-           width = LOWORD(lParam);\r
-           height = HIWORD(lParam);\r
-\r
-            if (wParam == SIZE_MAXIMIZED && !was_zoomed) {\r
-                was_zoomed = 1;\r
-                prev_rows = term->rows;\r
-                prev_cols = term->cols;\r
-                if (cfg.resize_action == RESIZE_TERM) {\r
-                    w = width / font_width;\r
-                    if (w < 1) w = 1;\r
-                    h = height / font_height;\r
-                    if (h < 1) h = 1;\r
-\r
-                    term_size(term, h, w, cfg.savelines);\r
-                }\r
-                reset_window(0);\r
-            } else if (wParam == SIZE_RESTORED && was_zoomed) {\r
-                was_zoomed = 0;\r
-                if (cfg.resize_action == RESIZE_TERM) {\r
-                    w = (width-cfg.window_border*2) / font_width;\r
-                    if (w < 1) w = 1;\r
-                    h = (height-cfg.window_border*2) / font_height;\r
-                    if (h < 1) h = 1;\r
-                    term_size(term, h, w, cfg.savelines);\r
-                    reset_window(2);\r
-                } else if (cfg.resize_action != RESIZE_FONT)\r
-                    reset_window(2);\r
-                else\r
-                    reset_window(0);\r
-            } else if (wParam == SIZE_MINIMIZED) {\r
-                /* do nothing */\r
-           } else if (cfg.resize_action == RESIZE_TERM ||\r
-                       (cfg.resize_action == RESIZE_EITHER &&\r
-                        !is_alt_pressed())) {\r
-                w = (width-cfg.window_border*2) / font_width;\r
-                if (w < 1) w = 1;\r
-                h = (height-cfg.window_border*2) / font_height;\r
-                if (h < 1) h = 1;\r
-\r
-                if (resizing) {\r
-                    /*\r
-                     * Don't call back->size in mid-resize. (To\r
-                     * prevent massive numbers of resize events\r
-                     * getting sent down the connection during an NT\r
-                     * opaque drag.)\r
-                     */\r
-                   need_backend_resize = TRUE;\r
-                   cfg.height = h;\r
-                   cfg.width = w;\r
-                } else {\r
-                    term_size(term, h, w, cfg.savelines);\r
-                }\r
-            } else {\r
-                reset_window(0);\r
-           }\r
-       }\r
-       sys_cursor_update();\r
-       return 0;\r
-      case WM_VSCROLL:\r
-       switch (LOWORD(wParam)) {\r
-         case SB_BOTTOM:\r
-           term_scroll(term, -1, 0);\r
-           break;\r
-         case SB_TOP:\r
-           term_scroll(term, +1, 0);\r
-           break;\r
-         case SB_LINEDOWN:\r
-           term_scroll(term, 0, +1);\r
-           break;\r
-         case SB_LINEUP:\r
-           term_scroll(term, 0, -1);\r
-           break;\r
-         case SB_PAGEDOWN:\r
-           term_scroll(term, 0, +term->rows / 2);\r
-           break;\r
-         case SB_PAGEUP:\r
-           term_scroll(term, 0, -term->rows / 2);\r
-           break;\r
-         case SB_THUMBPOSITION:\r
-         case SB_THUMBTRACK:\r
-           term_scroll(term, 1, HIWORD(wParam));\r
-           break;\r
-       }\r
-       break;\r
-      case WM_PALETTECHANGED:\r
-       if ((HWND) wParam != hwnd && pal != NULL) {\r
-           HDC hdc = get_ctx(NULL);\r
-           if (hdc) {\r
-               if (RealizePalette(hdc) > 0)\r
-                   UpdateColors(hdc);\r
-               free_ctx(hdc);\r
-           }\r
-       }\r
-       break;\r
-      case WM_QUERYNEWPALETTE:\r
-       if (pal != NULL) {\r
-           HDC hdc = get_ctx(NULL);\r
-           if (hdc) {\r
-               if (RealizePalette(hdc) > 0)\r
-                   UpdateColors(hdc);\r
-               free_ctx(hdc);\r
-               return TRUE;\r
-           }\r
-       }\r
-       return FALSE;\r
-      case WM_KEYDOWN:\r
-      case WM_SYSKEYDOWN:\r
-      case WM_KEYUP:\r
-      case WM_SYSKEYUP:\r
-       /*\r
-        * Add the scan code and keypress timing to the random\r
-        * number noise.\r
-        */\r
-       noise_ultralight(lParam);\r
-\r
-       /*\r
-        * We don't do TranslateMessage since it disassociates the\r
-        * resulting CHAR message from the KEYDOWN that sparked it,\r
-        * which we occasionally don't want. Instead, we process\r
-        * KEYDOWN, and call the Win32 translator functions so that\r
-        * we get the translations under _our_ control.\r
-        */\r
-       {\r
-           unsigned char buf[20];\r
-           int len;\r
-\r
-           if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */\r
-               if (message == WM_KEYDOWN) {\r
-                   MSG m;\r
-                   m.hwnd = hwnd;\r
-                   m.message = WM_KEYDOWN;\r
-                   m.wParam = wParam;\r
-                   m.lParam = lParam & 0xdfff;\r
-                   TranslateMessage(&m);\r
-               } else break; /* pass to Windows for default processing */\r
-           } else {\r
-               len = TranslateKey(message, wParam, lParam, buf);\r
-               if (len == -1)\r
-                   return DefWindowProc(hwnd, message, wParam, lParam);\r
-\r
-               if (len != 0) {\r
-                   /*\r
-                    * Interrupt an ongoing paste. I'm not sure\r
-                    * this is sensible, but for the moment it's\r
-                    * preferable to having to faff about buffering\r
-                    * things.\r
-                    */\r
-                   term_nopaste(term);\r
-\r
-                   /*\r
-                    * We need not bother about stdin backlogs\r
-                    * here, because in GUI PuTTY we can't do\r
-                    * anything about it anyway; there's no means\r
-                    * of asking Windows to hold off on KEYDOWN\r
-                    * messages. We _have_ to buffer everything\r
-                    * we're sent.\r
-                    */\r
-                   term_seen_key_event(term);\r
-                   if (ldisc)\r
-                       ldisc_send(ldisc, buf, len, 1);\r
-                   show_mouseptr(0);\r
-               }\r
-           }\r
-       }\r
-       net_pending_errors();\r
-       return 0;\r
-      case WM_INPUTLANGCHANGE:\r
-       /* wParam == Font number */\r
-       /* lParam == Locale */\r
-       set_input_locale((HKL)lParam);\r
-       sys_cursor_update();\r
-       break;\r
-      case WM_IME_STARTCOMPOSITION:\r
-       {\r
-           HIMC hImc = ImmGetContext(hwnd);\r
-           ImmSetCompositionFont(hImc, &lfont);\r
-           ImmReleaseContext(hwnd, hImc);\r
-       }\r
-       break;\r
-      case WM_IME_COMPOSITION:\r
-       {\r
-           HIMC hIMC;\r
-           int n;\r
-           char *buff;\r
-\r
-           if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || \r
-               osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */\r
-\r
-           if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */\r
-               break; /* fall back to DefWindowProc */\r
-\r
-           hIMC = ImmGetContext(hwnd);\r
-           n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);\r
-\r
-           if (n > 0) {\r
-               int i;\r
-               buff = snewn(n, char);\r
-               ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);\r
-               /*\r
-                * Jaeyoun Chung reports that Korean character\r
-                * input doesn't work correctly if we do a single\r
-                * luni_send() covering the whole of buff. So\r
-                * instead we luni_send the characters one by one.\r
-                */\r
-               term_seen_key_event(term);\r
-               for (i = 0; i < n; i += 2) {\r
-                   if (ldisc)\r
-                       luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);\r
-               }\r
-               free(buff);\r
-           }\r
-           ImmReleaseContext(hwnd, hIMC);\r
-           return 1;\r
-       }\r
-\r
-      case WM_IME_CHAR:\r
-       if (wParam & 0xFF00) {\r
-           unsigned char buf[2];\r
-\r
-           buf[1] = wParam;\r
-           buf[0] = wParam >> 8;\r
-           term_seen_key_event(term);\r
-           if (ldisc)\r
-               lpage_send(ldisc, kbd_codepage, buf, 2, 1);\r
-       } else {\r
-           char c = (unsigned char) wParam;\r
-           term_seen_key_event(term);\r
-           if (ldisc)\r
-               lpage_send(ldisc, kbd_codepage, &c, 1, 1);\r
-       }\r
-       return (0);\r
-      case WM_CHAR:\r
-      case WM_SYSCHAR:\r
-       /*\r
-        * Nevertheless, we are prepared to deal with WM_CHAR\r
-        * messages, should they crop up. So if someone wants to\r
-        * post the things to us as part of a macro manoeuvre,\r
-        * we're ready to cope.\r
-        */\r
-       {\r
-           char c = (unsigned char)wParam;\r
-           term_seen_key_event(term);\r
-           if (ldisc)\r
-               lpage_send(ldisc, CP_ACP, &c, 1, 1);\r
-       }\r
-       return 0;\r
-      case WM_SYSCOLORCHANGE:\r
-       if (cfg.system_colour) {\r
-           /* Refresh palette from system colours. */\r
-           /* XXX actually this zaps the entire palette. */\r
-           systopalette();\r
-           init_palette();\r
-           /* Force a repaint of the terminal window. */\r
-           term_invalidate(term);\r
-       }\r
-       break;\r
-      case WM_AGENT_CALLBACK:\r
-       {\r
-           struct agent_callback *c = (struct agent_callback *)lParam;\r
-           c->callback(c->callback_ctx, c->data, c->len);\r
-           sfree(c);\r
-       }\r
-       return 0;\r
-      case WM_GOT_CLIPDATA:\r
-       if (process_clipdata((HGLOBAL)lParam, wParam))\r
-           term_do_paste(term);\r
-       return 0;\r
-      default:\r
-       if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {\r
-           int shift_pressed=0, control_pressed=0;\r
-\r
-           if (message == WM_MOUSEWHEEL) {\r
-               wheel_accumulator += (short)HIWORD(wParam);\r
-               shift_pressed=LOWORD(wParam) & MK_SHIFT;\r
-               control_pressed=LOWORD(wParam) & MK_CONTROL;\r
-           } else {\r
-               BYTE keys[256];\r
-               wheel_accumulator += (int)wParam;\r
-               if (GetKeyboardState(keys)!=0) {\r
-                   shift_pressed=keys[VK_SHIFT]&0x80;\r
-                   control_pressed=keys[VK_CONTROL]&0x80;\r
-               }\r
-           }\r
-\r
-           /* process events when the threshold is reached */\r
-           while (abs(wheel_accumulator) >= WHEEL_DELTA) {\r
-               int b;\r
-\r
-               /* reduce amount for next time */\r
-               if (wheel_accumulator > 0) {\r
-                   b = MBT_WHEEL_UP;\r
-                   wheel_accumulator -= WHEEL_DELTA;\r
-               } else if (wheel_accumulator < 0) {\r
-                   b = MBT_WHEEL_DOWN;\r
-                   wheel_accumulator += WHEEL_DELTA;\r
-               } else\r
-                   break;\r
-\r
-               if (send_raw_mouse &&\r
-                   !(cfg.mouse_override && shift_pressed)) {\r
-                   /* Mouse wheel position is in screen coordinates for\r
-                    * some reason */\r
-                   POINT p;\r
-                   p.x = X_POS(lParam); p.y = Y_POS(lParam);\r
-                   if (ScreenToClient(hwnd, &p)) {\r
-                       /* send a mouse-down followed by a mouse up */\r
-                       term_mouse(term, b, translate_button(b),\r
-                                  MA_CLICK,\r
-                                  TO_CHR_X(p.x),\r
-                                  TO_CHR_Y(p.y), shift_pressed,\r
-                                  control_pressed, is_alt_pressed());\r
-                       term_mouse(term, b, translate_button(b),\r
-                                  MA_RELEASE, TO_CHR_X(p.x),\r
-                                  TO_CHR_Y(p.y), shift_pressed,\r
-                                  control_pressed, is_alt_pressed());\r
-                   } /* else: not sure when this can fail */\r
-               } else {\r
-                   /* trigger a scroll */\r
-                   term_scroll(term, 0,\r
-                               b == MBT_WHEEL_UP ?\r
-                               -term->rows / 2 : term->rows / 2);\r
-               }\r
-           }\r
-           return 0;\r
-       }\r
-    }\r
-\r
-    /*\r
-     * Any messages we don't process completely above are passed through to\r
-     * DefWindowProc() for default processing.\r
-     */\r
-    return DefWindowProc(hwnd, message, wParam, lParam);\r
-}\r
-\r
-/*\r
- * Move the system caret. (We maintain one, even though it's\r
- * invisible, for the benefit of blind people: apparently some\r
- * helper software tracks the system caret, so we should arrange to\r
- * have one.)\r
- */\r
-void sys_cursor(void *frontend, int x, int y)\r
-{\r
-    int cx, cy;\r
-\r
-    if (!term->has_focus) return;\r
-\r
-    /*\r
-     * Avoid gratuitously re-updating the cursor position and IMM\r
-     * window if there's no actual change required.\r
-     */\r
-    cx = x * font_width + offset_width;\r
-    cy = y * font_height + offset_height;\r
-    if (cx == caret_x && cy == caret_y)\r
-       return;\r
-    caret_x = cx;\r
-    caret_y = cy;\r
-\r
-    sys_cursor_update();\r
-}\r
-\r
-static void sys_cursor_update(void)\r
-{\r
-    COMPOSITIONFORM cf;\r
-    HIMC hIMC;\r
-\r
-    if (!term->has_focus) return;\r
-\r
-    if (caret_x < 0 || caret_y < 0)\r
-       return;\r
-\r
-    SetCaretPos(caret_x, caret_y);\r
-\r
-    /* IMM calls on Win98 and beyond only */\r
-    if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */\r
-    \r
-    if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&\r
-           osVersion.dwMinorVersion == 0) return; /* 95 */\r
-\r
-    /* we should have the IMM functions */\r
-    hIMC = ImmGetContext(hwnd);\r
-    cf.dwStyle = CFS_POINT;\r
-    cf.ptCurrentPos.x = caret_x;\r
-    cf.ptCurrentPos.y = caret_y;\r
-    ImmSetCompositionWindow(hIMC, &cf);\r
-\r
-    ImmReleaseContext(hwnd, hIMC);\r
-}\r
-\r
-/*\r
- * Draw a line of text in the window, at given character\r
- * coordinates, in given attributes.\r
- *\r
- * We are allowed to fiddle with the contents of `text'.\r
- */\r
-void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,\r
-                     unsigned long attr, int lattr)\r
-{\r
-    COLORREF fg, bg, t;\r
-    int nfg, nbg, nfont;\r
-    HDC hdc = ctx;\r
-    RECT line_box;\r
-    int force_manual_underline = 0;\r
-    int fnt_width, char_width;\r
-    int text_adjust = 0;\r
-    int xoffset = 0;\r
-    int maxlen, remaining, opaque;\r
-    static int *lpDx = NULL;\r
-    static int lpDx_len = 0;\r
-    int *lpDx_maybe;\r
-\r
-    lattr &= LATTR_MODE;\r
-\r
-    char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));\r
-\r
-    if (attr & ATTR_WIDE)\r
-       char_width *= 2;\r
-\r
-    /* Only want the left half of double width lines */\r
-    if (lattr != LATTR_NORM && x*2 >= term->cols)\r
-       return;\r
-\r
-    x *= fnt_width;\r
-    y *= font_height;\r
-    x += offset_width;\r
-    y += offset_height;\r
-\r
-    if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {\r
-       attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);\r
-       if (bold_mode == BOLD_COLOURS)\r
-           attr &= ~ATTR_BOLD;\r
-\r
-       /* cursor fg and bg */\r
-       attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);\r
-    }\r
-\r
-    nfont = 0;\r
-    if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {\r
-       /* Assume a poorman font is borken in other ways too. */\r
-       lattr = LATTR_WIDE;\r
-    } else\r
-       switch (lattr) {\r
-         case LATTR_NORM:\r
-           break;\r
-         case LATTR_WIDE:\r
-           nfont |= FONT_WIDE;\r
-           break;\r
-         default:\r
-           nfont |= FONT_WIDE + FONT_HIGH;\r
-           break;\r
-       }\r
-    if (attr & ATTR_NARROW)\r
-       nfont |= FONT_NARROW;\r
-\r
-    /* Special hack for the VT100 linedraw glyphs. */\r
-    if (text[0] >= 0x23BA && text[0] <= 0x23BD) {\r
-       switch ((unsigned char) (text[0])) {\r
-         case 0xBA:\r
-           text_adjust = -2 * font_height / 5;\r
-           break;\r
-         case 0xBB:\r
-           text_adjust = -1 * font_height / 5;\r
-           break;\r
-         case 0xBC:\r
-           text_adjust = font_height / 5;\r
-           break;\r
-         case 0xBD:\r
-           text_adjust = 2 * font_height / 5;\r
-           break;\r
-       }\r
-       if (lattr == LATTR_TOP || lattr == LATTR_BOT)\r
-           text_adjust *= 2;\r
-       text[0] = ucsdata.unitab_xterm['q'];\r
-       if (attr & ATTR_UNDER) {\r
-           attr &= ~ATTR_UNDER;\r
-           force_manual_underline = 1;\r
-       }\r
-    }\r
-\r
-    /* Anything left as an original character set is unprintable. */\r
-    if (DIRECT_CHAR(text[0])) {\r
-       int i;\r
-       for (i = 0; i < len; i++)\r
-           text[i] = 0xFFFD;\r
-    }\r
-\r
-    /* OEM CP */\r
-    if ((text[0] & CSET_MASK) == CSET_OEMCP)\r
-       nfont |= FONT_OEM;\r
-\r
-    nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);\r
-    nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);\r
-    if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))\r
-       nfont |= FONT_BOLD;\r
-    if (und_mode == UND_FONT && (attr & ATTR_UNDER))\r
-       nfont |= FONT_UNDERLINE;\r
-    another_font(nfont);\r
-    if (!fonts[nfont]) {\r
-       if (nfont & FONT_UNDERLINE)\r
-           force_manual_underline = 1;\r
-       /* Don't do the same for manual bold, it could be bad news. */\r
-\r
-       nfont &= ~(FONT_BOLD | FONT_UNDERLINE);\r
-    }\r
-    another_font(nfont);\r
-    if (!fonts[nfont])\r
-       nfont = FONT_NORMAL;\r
-    if (attr & ATTR_REVERSE) {\r
-       t = nfg;\r
-       nfg = nbg;\r
-       nbg = t;\r
-    }\r
-    if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {\r
-       if (nfg < 16) nfg |= 8;\r
-       else if (nfg >= 256) nfg |= 1;\r
-    }\r
-    if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {\r
-       if (nbg < 16) nbg |= 8;\r
-       else if (nbg >= 256) nbg |= 1;\r
-    }\r
-    fg = colours[nfg];\r
-    bg = colours[nbg];\r
-    SelectObject(hdc, fonts[nfont]);\r
-    SetTextColor(hdc, fg);\r
-    SetBkColor(hdc, bg);\r
-    if (attr & TATTR_COMBINING)\r
-       SetBkMode(hdc, TRANSPARENT);\r
-    else\r
-       SetBkMode(hdc, OPAQUE);\r
-    line_box.left = x;\r
-    line_box.top = y;\r
-    line_box.right = x + char_width * len;\r
-    line_box.bottom = y + font_height;\r
-\r
-    /* Only want the left half of double width lines */\r
-    if (line_box.right > font_width*term->cols+offset_width)\r
-       line_box.right = font_width*term->cols+offset_width;\r
-\r
-    if (font_varpitch) {\r
-        /*\r
-         * If we're using a variable-pitch font, we unconditionally\r
-         * draw the glyphs one at a time and centre them in their\r
-         * character cells (which means in particular that we must\r
-         * disable the lpDx mechanism). This gives slightly odd but\r
-         * generally reasonable results.\r
-         */\r
-        xoffset = char_width / 2;\r
-        SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);\r
-        lpDx_maybe = NULL;\r
-        maxlen = 1;\r
-    } else {\r
-        /*\r
-         * In a fixed-pitch font, we draw the whole string in one go\r
-         * in the normal way.\r
-         */\r
-        xoffset = 0;\r
-        SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);\r
-        lpDx_maybe = lpDx;\r
-        maxlen = len;\r
-    }\r
-\r
-    opaque = TRUE;                     /* start by erasing the rectangle */\r
-    for (remaining = len; remaining > 0;\r
-         text += len, remaining -= len, x += char_width * len) {\r
-        len = (maxlen < remaining ? maxlen : remaining);\r
-\r
-        if (len > lpDx_len) {\r
-            if (len > lpDx_len) {\r
-                lpDx_len = len * 9 / 8 + 16;\r
-                lpDx = sresize(lpDx, lpDx_len, int);\r
-            }\r
-        }\r
-        {\r
-            int i;\r
-            for (i = 0; i < len; i++)\r
-                lpDx[i] = char_width;\r
-        }\r
-\r
-        /* We're using a private area for direct to font. (512 chars.) */\r
-        if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {\r
-            /* Ho Hum, dbcs fonts are a PITA! */\r
-            /* To display on W9x I have to convert to UCS */\r
-            static wchar_t *uni_buf = 0;\r
-            static int uni_len = 0;\r
-            int nlen, mptr;\r
-            if (len > uni_len) {\r
-                sfree(uni_buf);\r
-                uni_len = len;\r
-                uni_buf = snewn(uni_len, wchar_t);\r
-            }\r
-\r
-            for(nlen = mptr = 0; mptr<len; mptr++) {\r
-                uni_buf[nlen] = 0xFFFD;\r
-                if (IsDBCSLeadByteEx(ucsdata.font_codepage,\r
-                                     (BYTE) text[mptr])) {\r
-                    char dbcstext[2];\r
-                    dbcstext[0] = text[mptr] & 0xFF;\r
-                    dbcstext[1] = text[mptr+1] & 0xFF;\r
-                    lpDx[nlen] += char_width;\r
-                    MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,\r
-                                        dbcstext, 2, uni_buf+nlen, 1);\r
-                    mptr++;\r
-                }\r
-                else\r
-                {\r
-                    char dbcstext[1];\r
-                    dbcstext[0] = text[mptr] & 0xFF;\r
-                    MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,\r
-                                        dbcstext, 1, uni_buf+nlen, 1);\r
-                }\r
-                nlen++;\r
-            }\r
-            if (nlen <= 0)\r
-                return;                       /* Eeek! */\r
-\r
-            ExtTextOutW(hdc, x + xoffset,\r
-                        y - font_height * (lattr == LATTR_BOT) + text_adjust,\r
-                        ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),\r
-                        &line_box, uni_buf, nlen,\r
-                        lpDx_maybe);\r
-            if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {\r
-                SetBkMode(hdc, TRANSPARENT);\r
-                ExtTextOutW(hdc, x + xoffset - 1,\r
-                            y - font_height * (lattr ==\r
-                                               LATTR_BOT) + text_adjust,\r
-                            ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);\r
-            }\r
-\r
-            lpDx[0] = -1;\r
-        } else if (DIRECT_FONT(text[0])) {\r
-            static char *directbuf = NULL;\r
-            static int directlen = 0;\r
-            int i;\r
-            if (len > directlen) {\r
-                directlen = len;\r
-                directbuf = sresize(directbuf, directlen, char);\r
-            }\r
-\r
-            for (i = 0; i < len; i++)\r
-                directbuf[i] = text[i] & 0xFF;\r
-\r
-            ExtTextOut(hdc, x + xoffset,\r
-                       y - font_height * (lattr == LATTR_BOT) + text_adjust,\r
-                       ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),\r
-                       &line_box, directbuf, len, lpDx_maybe);\r
-            if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {\r
-                SetBkMode(hdc, TRANSPARENT);\r
-\r
-                /* GRR: This draws the character outside its box and\r
-                 * can leave 'droppings' even with the clip box! I\r
-                 * suppose I could loop it one character at a time ...\r
-                 * yuk.\r
-                 * \r
-                 * Or ... I could do a test print with "W", and use +1\r
-                 * or -1 for this shift depending on if the leftmost\r
-                 * column is blank...\r
-                 */\r
-                ExtTextOut(hdc, x + xoffset - 1,\r
-                           y - font_height * (lattr ==\r
-                                              LATTR_BOT) + text_adjust,\r
-                           ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);\r
-            }\r
-        } else {\r
-            /* And 'normal' unicode characters */\r
-            static WCHAR *wbuf = NULL;\r
-            static int wlen = 0;\r
-            int i;\r
-\r
-            if (wlen < len) {\r
-                sfree(wbuf);\r
-                wlen = len;\r
-                wbuf = snewn(wlen, WCHAR);\r
-            }\r
-\r
-            for (i = 0; i < len; i++)\r
-                wbuf[i] = text[i];\r
-\r
-            /* print Glyphs as they are, without Windows' Shaping*/\r
-            general_textout(hdc, x + xoffset,\r
-                            y - font_height * (lattr==LATTR_BOT) + text_adjust,\r
-                            &line_box, wbuf, len, lpDx,\r
-                            opaque && !(attr & TATTR_COMBINING));\r
-\r
-            /* And the shadow bold hack. */\r
-            if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {\r
-                SetBkMode(hdc, TRANSPARENT);\r
-                ExtTextOutW(hdc, x + xoffset - 1,\r
-                            y - font_height * (lattr ==\r
-                                               LATTR_BOT) + text_adjust,\r
-                            ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);\r
-            }\r
-        }\r
-\r
-        /*\r
-         * If we're looping round again, stop erasing the background\r
-         * rectangle.\r
-         */\r
-        SetBkMode(hdc, TRANSPARENT);\r
-        opaque = FALSE;\r
-    }\r
-    if (lattr != LATTR_TOP && (force_manual_underline ||\r
-                              (und_mode == UND_LINE\r
-                               && (attr & ATTR_UNDER)))) {\r
-       HPEN oldpen;\r
-       int dec = descent;\r
-       if (lattr == LATTR_BOT)\r
-           dec = dec * 2 - font_height;\r
-\r
-       oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));\r
-       MoveToEx(hdc, x, y + dec, NULL);\r
-       LineTo(hdc, x + len * char_width, y + dec);\r
-       oldpen = SelectObject(hdc, oldpen);\r
-       DeleteObject(oldpen);\r
-    }\r
-}\r
-\r
-/*\r
- * Wrapper that handles combining characters.\r
- */\r
-void do_text(Context ctx, int x, int y, wchar_t *text, int len,\r
-            unsigned long attr, int lattr)\r
-{\r
-    if (attr & TATTR_COMBINING) {\r
-       unsigned long a = 0;\r
-       attr &= ~TATTR_COMBINING;\r
-       while (len--) {\r
-           do_text_internal(ctx, x, y, text, 1, attr | a, lattr);\r
-           text++;\r
-           a = TATTR_COMBINING;\r
-       }\r
-    } else\r
-       do_text_internal(ctx, x, y, text, len, attr, lattr);\r
-}\r
-\r
-void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,\r
-              unsigned long attr, int lattr)\r
-{\r
-\r
-    int fnt_width;\r
-    int char_width;\r
-    HDC hdc = ctx;\r
-    int ctype = cfg.cursor_type;\r
-\r
-    lattr &= LATTR_MODE;\r
-\r
-    if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {\r
-       if (*text != UCSWIDE) {\r
-           do_text(ctx, x, y, text, len, attr, lattr);\r
-           return;\r
-       }\r
-       ctype = 2;\r
-       attr |= TATTR_RIGHTCURS;\r
-    }\r
-\r
-    fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));\r
-    if (attr & ATTR_WIDE)\r
-       char_width *= 2;\r
-    x *= fnt_width;\r
-    y *= font_height;\r
-    x += offset_width;\r
-    y += offset_height;\r
-\r
-    if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {\r
-       POINT pts[5];\r
-       HPEN oldpen;\r
-       pts[0].x = pts[1].x = pts[4].x = x;\r
-       pts[2].x = pts[3].x = x + char_width - 1;\r
-       pts[0].y = pts[3].y = pts[4].y = y;\r
-       pts[1].y = pts[2].y = y + font_height - 1;\r
-       oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));\r
-       Polyline(hdc, pts, 5);\r
-       oldpen = SelectObject(hdc, oldpen);\r
-       DeleteObject(oldpen);\r
-    } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {\r
-       int startx, starty, dx, dy, length, i;\r
-       if (ctype == 1) {\r
-           startx = x;\r
-           starty = y + descent;\r
-           dx = 1;\r
-           dy = 0;\r
-           length = char_width;\r
-       } else {\r
-           int xadjust = 0;\r
-           if (attr & TATTR_RIGHTCURS)\r
-               xadjust = char_width - 1;\r
-           startx = x + xadjust;\r
-           starty = y;\r
-           dx = 0;\r
-           dy = 1;\r
-           length = font_height;\r
-       }\r
-       if (attr & TATTR_ACTCURS) {\r
-           HPEN oldpen;\r
-           oldpen =\r
-               SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));\r
-           MoveToEx(hdc, startx, starty, NULL);\r
-           LineTo(hdc, startx + dx * length, starty + dy * length);\r
-           oldpen = SelectObject(hdc, oldpen);\r
-           DeleteObject(oldpen);\r
-       } else {\r
-           for (i = 0; i < length; i++) {\r
-               if (i % 2 == 0) {\r
-                   SetPixel(hdc, startx, starty, colours[261]);\r
-               }\r
-               startx += dx;\r
-               starty += dy;\r
-           }\r
-       }\r
-    }\r
-}\r
-\r
-/* This function gets the actual width of a character in the normal font.\r
- */\r
-int char_width(Context ctx, int uc) {\r
-    HDC hdc = ctx;\r
-    int ibuf = 0;\r
-\r
-    /* If the font max is the same as the font ave width then this\r
-     * function is a no-op.\r
-     */\r
-    if (!font_dualwidth) return 1;\r
-\r
-    switch (uc & CSET_MASK) {\r
-      case CSET_ASCII:\r
-       uc = ucsdata.unitab_line[uc & 0xFF];\r
-       break;\r
-      case CSET_LINEDRW:\r
-       uc = ucsdata.unitab_xterm[uc & 0xFF];\r
-       break;\r
-      case CSET_SCOACS:\r
-       uc = ucsdata.unitab_scoacs[uc & 0xFF];\r
-       break;\r
-    }\r
-    if (DIRECT_FONT(uc)) {\r
-       if (ucsdata.dbcs_screenfont) return 1;\r
-\r
-       /* Speedup, I know of no font where ascii is the wrong width */\r
-       if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')\r
-           return 1;\r
-\r
-       if ( (uc & CSET_MASK) == CSET_ACP ) {\r
-           SelectObject(hdc, fonts[FONT_NORMAL]);\r
-       } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {\r
-           another_font(FONT_OEM);\r
-           if (!fonts[FONT_OEM]) return 0;\r
-\r
-           SelectObject(hdc, fonts[FONT_OEM]);\r
-       } else\r
-           return 0;\r
-\r
-       if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&\r
-            GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)\r
-           return 0;\r
-    } else {\r
-       /* Speedup, I know of no font where ascii is the wrong width */\r
-       if (uc >= ' ' && uc <= '~') return 1;\r
-\r
-       SelectObject(hdc, fonts[FONT_NORMAL]);\r
-       if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )\r
-           /* Okay that one worked */ ;\r
-       else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )\r
-           /* This should work on 9x too, but it's "less accurate" */ ;\r
-       else\r
-           return 0;\r
-    }\r
-\r
-    ibuf += font_width / 2 -1;\r
-    ibuf /= font_width;\r
-\r
-    return ibuf;\r
-}\r
-\r
-/*\r
- * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII\r
- * codes. Returns number of bytes used, zero to drop the message,\r
- * -1 to forward the message to Windows, or another negative number\r
- * to indicate a NUL-terminated "special" string.\r
- */\r
-static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,\r
-                       unsigned char *output)\r
-{\r
-    BYTE keystate[256];\r
-    int scan, left_alt = 0, key_down, shift_state;\r
-    int r, i, code;\r
-    unsigned char *p = output;\r
-    static int alt_sum = 0;\r
-\r
-    HKL kbd_layout = GetKeyboardLayout(0);\r
-\r
-    /* keys is for ToAsciiEx. There's some ick here, see below. */\r
-    static WORD keys[3];\r
-    static int compose_char = 0;\r
-    static WPARAM compose_key = 0;\r
-\r
-    r = GetKeyboardState(keystate);\r
-    if (!r)\r
-       memset(keystate, 0, sizeof(keystate));\r
-    else {\r
-#if 0\r
-#define SHOW_TOASCII_RESULT\r
-       {                              /* Tell us all about key events */\r
-           static BYTE oldstate[256];\r
-           static int first = 1;\r
-           static int scan;\r
-           int ch;\r
-           if (first)\r
-               memcpy(oldstate, keystate, sizeof(oldstate));\r
-           first = 0;\r
-\r
-           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {\r
-               debug(("+"));\r
-           } else if ((HIWORD(lParam) & KF_UP)\r
-                      && scan == (HIWORD(lParam) & 0xFF)) {\r
-               debug((". U"));\r
-           } else {\r
-               debug((".\n"));\r
-               if (wParam >= VK_F1 && wParam <= VK_F20)\r
-                   debug(("K_F%d", wParam + 1 - VK_F1));\r
-               else\r
-                   switch (wParam) {\r
-                     case VK_SHIFT:\r
-                       debug(("SHIFT"));\r
-                       break;\r
-                     case VK_CONTROL:\r
-                       debug(("CTRL"));\r
-                       break;\r
-                     case VK_MENU:\r
-                       debug(("ALT"));\r
-                       break;\r
-                     default:\r
-                       debug(("VK_%02x", wParam));\r
-                   }\r
-               if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)\r
-                   debug(("*"));\r
-               debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));\r
-\r
-               ch = MapVirtualKeyEx(wParam, 2, kbd_layout);\r
-               if (ch >= ' ' && ch <= '~')\r
-                   debug((", '%c'", ch));\r
-               else if (ch)\r
-                   debug((", $%02x", ch));\r
-\r
-               if (keys[0])\r
-                   debug((", KB0=%02x", keys[0]));\r
-               if (keys[1])\r
-                   debug((", KB1=%02x", keys[1]));\r
-               if (keys[2])\r
-                   debug((", KB2=%02x", keys[2]));\r
-\r
-               if ((keystate[VK_SHIFT] & 0x80) != 0)\r
-                   debug((", S"));\r
-               if ((keystate[VK_CONTROL] & 0x80) != 0)\r
-                   debug((", C"));\r
-               if ((HIWORD(lParam) & KF_EXTENDED))\r
-                   debug((", E"));\r
-               if ((HIWORD(lParam) & KF_UP))\r
-                   debug((", U"));\r
-           }\r
-\r
-           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);\r
-           else if ((HIWORD(lParam) & KF_UP))\r
-               oldstate[wParam & 0xFF] ^= 0x80;\r
-           else\r
-               oldstate[wParam & 0xFF] ^= 0x81;\r
-\r
-           for (ch = 0; ch < 256; ch++)\r
-               if (oldstate[ch] != keystate[ch])\r
-                   debug((", M%02x=%02x", ch, keystate[ch]));\r
-\r
-           memcpy(oldstate, keystate, sizeof(oldstate));\r
-       }\r
-#endif\r
-\r
-       if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {\r
-           keystate[VK_RMENU] = keystate[VK_MENU];\r
-       }\r
-\r
-\r
-       /* Nastyness with NUMLock - Shift-NUMLock is left alone though */\r
-       if ((cfg.funky_type == FUNKY_VT400 ||\r
-            (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&\r
-             !cfg.no_applic_k))\r
-           && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {\r
-\r
-           wParam = VK_EXECUTE;\r
-\r
-           /* UnToggle NUMLock */\r
-           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)\r
-               keystate[VK_NUMLOCK] ^= 1;\r
-       }\r
-\r
-       /* And write back the 'adjusted' state */\r
-       SetKeyboardState(keystate);\r
-    }\r
-\r
-    /* Disable Auto repeat if required */\r
-    if (term->repeat_off &&\r
-       (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)\r
-       return 0;\r
-\r
-    if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)\r
-       left_alt = 1;\r
-\r
-    key_down = ((HIWORD(lParam) & KF_UP) == 0);\r
-\r
-    /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */\r
-    if (left_alt && (keystate[VK_CONTROL] & 0x80)) {\r
-       if (cfg.ctrlaltkeys)\r
-           keystate[VK_MENU] = 0;\r
-       else {\r
-           keystate[VK_RMENU] = 0x80;\r
-           left_alt = 0;\r
-       }\r
-    }\r
-\r
-    scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));\r
-    shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)\r
-       + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;\r
-\r
-    /* Note if AltGr was pressed and if it was used as a compose key */\r
-    if (!compose_state) {\r
-       compose_key = 0x100;\r
-       if (cfg.compose_key) {\r
-           if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))\r
-               compose_key = wParam;\r
-       }\r
-       if (wParam == VK_APPS)\r
-           compose_key = wParam;\r
-    }\r
-\r
-    if (wParam == compose_key) {\r
-       if (compose_state == 0\r
-           && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =\r
-               1;\r
-       else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))\r
-           compose_state = 2;\r
-       else\r
-           compose_state = 0;\r
-    } else if (compose_state == 1 && wParam != VK_CONTROL)\r
-       compose_state = 0;\r
-\r
-    if (compose_state > 1 && left_alt)\r
-       compose_state = 0;\r
-\r
-    /* Sanitize the number pad if not using a PC NumPad */\r
-    if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k\r
-                    && cfg.funky_type != FUNKY_XTERM)\r
-       || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {\r
-       if ((HIWORD(lParam) & KF_EXTENDED) == 0) {\r
-           int nParam = 0;\r
-           switch (wParam) {\r
-             case VK_INSERT:\r
-               nParam = VK_NUMPAD0;\r
-               break;\r
-             case VK_END:\r
-               nParam = VK_NUMPAD1;\r
-               break;\r
-             case VK_DOWN:\r
-               nParam = VK_NUMPAD2;\r
-               break;\r
-             case VK_NEXT:\r
-               nParam = VK_NUMPAD3;\r
-               break;\r
-             case VK_LEFT:\r
-               nParam = VK_NUMPAD4;\r
-               break;\r
-             case VK_CLEAR:\r
-               nParam = VK_NUMPAD5;\r
-               break;\r
-             case VK_RIGHT:\r
-               nParam = VK_NUMPAD6;\r
-               break;\r
-             case VK_HOME:\r
-               nParam = VK_NUMPAD7;\r
-               break;\r
-             case VK_UP:\r
-               nParam = VK_NUMPAD8;\r
-               break;\r
-             case VK_PRIOR:\r
-               nParam = VK_NUMPAD9;\r
-               break;\r
-             case VK_DELETE:\r
-               nParam = VK_DECIMAL;\r
-               break;\r
-           }\r
-           if (nParam) {\r
-               if (keystate[VK_NUMLOCK] & 1)\r
-                   shift_state |= 1;\r
-               wParam = nParam;\r
-           }\r
-       }\r
-    }\r
-\r
-    /* If a key is pressed and AltGr is not active */\r
-    if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {\r
-       /* Okay, prepare for most alts then ... */\r
-       if (left_alt)\r
-           *p++ = '\033';\r
-\r
-       /* Lets see if it's a pattern we know all about ... */\r
-       if (wParam == VK_PRIOR && shift_state == 1) {\r
-           SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);\r
-           return 0;\r
-       }\r
-       if (wParam == VK_PRIOR && shift_state == 2) {\r
-           SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);\r
-           return 0;\r
-       }\r
-       if (wParam == VK_NEXT && shift_state == 1) {\r
-           SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);\r
-           return 0;\r
-       }\r
-       if (wParam == VK_NEXT && shift_state == 2) {\r
-           SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);\r
-           return 0;\r
-       }\r
-       if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {\r
-           term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));\r
-           return 0;\r
-       }\r
-       if (wParam == VK_INSERT && shift_state == 1) {\r
-           request_paste(NULL);\r
-           return 0;\r
-       }\r
-       if (left_alt && wParam == VK_F4 && cfg.alt_f4) {\r
-           return -1;\r
-       }\r
-       if (left_alt && wParam == VK_SPACE && cfg.alt_space) {\r
-           SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);\r
-           return -1;\r
-       }\r
-       if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&\r
-           (cfg.resize_action != RESIZE_DISABLED)) {\r
-           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)\r
-               flip_full_screen();\r
-           return -1;\r
-       }\r
-       /* Control-Numlock for app-keypad mode switch */\r
-       if (wParam == VK_PAUSE && shift_state == 2) {\r
-           term->app_keypad_keys ^= 1;\r
-           return 0;\r
-       }\r
-\r
-       /* Nethack keypad */\r
-       if (cfg.nethack_keypad && !left_alt) {\r
-           switch (wParam) {\r
-             case VK_NUMPAD1:\r
-               *p++ = "bB\002\002"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD2:\r
-               *p++ = "jJ\012\012"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD3:\r
-               *p++ = "nN\016\016"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD4:\r
-               *p++ = "hH\010\010"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD5:\r
-               *p++ = shift_state ? '.' : '.';\r
-               return p - output;\r
-             case VK_NUMPAD6:\r
-               *p++ = "lL\014\014"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD7:\r
-               *p++ = "yY\031\031"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD8:\r
-               *p++ = "kK\013\013"[shift_state & 3];\r
-               return p - output;\r
-             case VK_NUMPAD9:\r
-               *p++ = "uU\025\025"[shift_state & 3];\r
-               return p - output;\r
-           }\r
-       }\r
-\r
-       /* Application Keypad */\r
-       if (!left_alt) {\r
-           int xkey = 0;\r
-\r
-           if (cfg.funky_type == FUNKY_VT400 ||\r
-               (cfg.funky_type <= FUNKY_LINUX &&\r
-                term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {\r
-                 case VK_EXECUTE:\r
-                   xkey = 'P';\r
-                   break;\r
-                 case VK_DIVIDE:\r
-                   xkey = 'Q';\r
-                   break;\r
-                 case VK_MULTIPLY:\r
-                   xkey = 'R';\r
-                   break;\r
-                 case VK_SUBTRACT:\r
-                   xkey = 'S';\r
-                   break;\r
-               }\r
-           if (term->app_keypad_keys && !cfg.no_applic_k)\r
-               switch (wParam) {\r
-                 case VK_NUMPAD0:\r
-                   xkey = 'p';\r
-                   break;\r
-                 case VK_NUMPAD1:\r
-                   xkey = 'q';\r
-                   break;\r
-                 case VK_NUMPAD2:\r
-                   xkey = 'r';\r
-                   break;\r
-                 case VK_NUMPAD3:\r
-                   xkey = 's';\r
-                   break;\r
-                 case VK_NUMPAD4:\r
-                   xkey = 't';\r
-                   break;\r
-                 case VK_NUMPAD5:\r
-                   xkey = 'u';\r
-                   break;\r
-                 case VK_NUMPAD6:\r
-                   xkey = 'v';\r
-                   break;\r
-                 case VK_NUMPAD7:\r
-                   xkey = 'w';\r
-                   break;\r
-                 case VK_NUMPAD8:\r
-                   xkey = 'x';\r
-                   break;\r
-                 case VK_NUMPAD9:\r
-                   xkey = 'y';\r
-                   break;\r
-\r
-                 case VK_DECIMAL:\r
-                   xkey = 'n';\r
-                   break;\r
-                 case VK_ADD:\r
-                   if (cfg.funky_type == FUNKY_XTERM) {\r
-                       if (shift_state)\r
-                           xkey = 'l';\r
-                       else\r
-                           xkey = 'k';\r
-                   } else if (shift_state)\r
-                       xkey = 'm';\r
-                   else\r
-                       xkey = 'l';\r
-                   break;\r
-\r
-                 case VK_DIVIDE:\r
-                   if (cfg.funky_type == FUNKY_XTERM)\r
-                       xkey = 'o';\r
-                   break;\r
-                 case VK_MULTIPLY:\r
-                   if (cfg.funky_type == FUNKY_XTERM)\r
-                       xkey = 'j';\r
-                   break;\r
-                 case VK_SUBTRACT:\r
-                   if (cfg.funky_type == FUNKY_XTERM)\r
-                       xkey = 'm';\r
-                   break;\r
-\r
-                 case VK_RETURN:\r
-                   if (HIWORD(lParam) & KF_EXTENDED)\r
-                       xkey = 'M';\r
-                   break;\r
-               }\r
-           if (xkey) {\r
-               if (term->vt52_mode) {\r
-                   if (xkey >= 'P' && xkey <= 'S')\r
-                       p += sprintf((char *) p, "\x1B%c", xkey);\r
-                   else\r
-                       p += sprintf((char *) p, "\x1B?%c", xkey);\r
-               } else\r
-                   p += sprintf((char *) p, "\x1BO%c", xkey);\r
-               return p - output;\r
-           }\r
-       }\r
-\r
-       if (wParam == VK_BACK && shift_state == 0) {    /* Backspace */\r
-           *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);\r
-           *p++ = 0;\r
-           return -2;\r
-       }\r
-       if (wParam == VK_BACK && shift_state == 1) {    /* Shift Backspace */\r
-           /* We do the opposite of what is configured */\r
-           *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);\r
-           *p++ = 0;\r
-           return -2;\r
-       }\r
-       if (wParam == VK_TAB && shift_state == 1) {     /* Shift tab */\r
-           *p++ = 0x1B;\r
-           *p++ = '[';\r
-           *p++ = 'Z';\r
-           return p - output;\r
-       }\r
-       if (wParam == VK_SPACE && shift_state == 2) {   /* Ctrl-Space */\r
-           *p++ = 0;\r
-           return p - output;\r
-       }\r
-       if (wParam == VK_SPACE && shift_state == 3) {   /* Ctrl-Shift-Space */\r
-           *p++ = 160;\r
-           return p - output;\r
-       }\r
-       if (wParam == VK_CANCEL && shift_state == 2) {  /* Ctrl-Break */\r
-           if (back)\r
-               back->special(backhandle, TS_BRK);\r
-           return 0;\r
-       }\r
-       if (wParam == VK_PAUSE) {      /* Break/Pause */\r
-           *p++ = 26;\r
-           *p++ = 0;\r
-           return -2;\r
-       }\r
-       /* Control-2 to Control-8 are special */\r
-       if (shift_state == 2 && wParam >= '2' && wParam <= '8') {\r
-           *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];\r
-           return p - output;\r
-       }\r
-       if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {\r
-           *p++ = 0x1F;\r
-           return p - output;\r
-       }\r
-       if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {\r
-           *p++ = 0x1C;\r
-           return p - output;\r
-       }\r
-       if (shift_state == 3 && wParam == 0xDE) {\r
-           *p++ = 0x1E;               /* Ctrl-~ == Ctrl-^ in xterm at least */\r
-           return p - output;\r
-       }\r
-       if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {\r
-           *p++ = '\r';\r
-           *p++ = '\n';\r
-           return p - output;\r
-       }\r
-\r
-       /*\r
-        * Next, all the keys that do tilde codes. (ESC '[' nn '~',\r
-        * for integer decimal nn.)\r
-        *\r
-        * We also deal with the weird ones here. Linux VCs replace F1\r
-        * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but\r
-        * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w\r
-        * respectively.\r
-        */\r
-       code = 0;\r
-       switch (wParam) {\r
-         case VK_F1:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);\r
-           break;\r
-         case VK_F2:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);\r
-           break;\r
-         case VK_F3:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);\r
-           break;\r
-         case VK_F4:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);\r
-           break;\r
-         case VK_F5:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);\r
-           break;\r
-         case VK_F6:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);\r
-           break;\r
-         case VK_F7:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);\r
-           break;\r
-         case VK_F8:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);\r
-           break;\r
-         case VK_F9:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);\r
-           break;\r
-         case VK_F10:\r
-           code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);\r
-           break;\r
-         case VK_F11:\r
-           code = 23;\r
-           break;\r
-         case VK_F12:\r
-           code = 24;\r
-           break;\r
-         case VK_F13:\r
-           code = 25;\r
-           break;\r
-         case VK_F14:\r
-           code = 26;\r
-           break;\r
-         case VK_F15:\r
-           code = 28;\r
-           break;\r
-         case VK_F16:\r
-           code = 29;\r
-           break;\r
-         case VK_F17:\r
-           code = 31;\r
-           break;\r
-         case VK_F18:\r
-           code = 32;\r
-           break;\r
-         case VK_F19:\r
-           code = 33;\r
-           break;\r
-         case VK_F20:\r
-           code = 34;\r
-           break;\r
-       }\r
-       if ((shift_state&2) == 0) switch (wParam) {\r
-         case VK_HOME:\r
-           code = 1;\r
-           break;\r
-         case VK_INSERT:\r
-           code = 2;\r
-           break;\r
-         case VK_DELETE:\r
-           code = 3;\r
-           break;\r
-         case VK_END:\r
-           code = 4;\r
-           break;\r
-         case VK_PRIOR:\r
-           code = 5;\r
-           break;\r
-         case VK_NEXT:\r
-           code = 6;\r
-           break;\r
-       }\r
-       /* Reorder edit keys to physical order */\r
-       if (cfg.funky_type == FUNKY_VT400 && code <= 6)\r
-           code = "\0\2\1\4\5\3\6"[code];\r
-\r
-       if (term->vt52_mode && code > 0 && code <= 6) {\r
-           p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);\r
-           return p - output;\r
-       }\r
-\r
-       if (cfg.funky_type == FUNKY_SCO &&     /* SCO function keys */\r
-           code >= 11 && code <= 34) {\r
-           char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";\r
-           int index = 0;\r
-           switch (wParam) {\r
-             case VK_F1: index = 0; break;\r
-             case VK_F2: index = 1; break;\r
-             case VK_F3: index = 2; break;\r
-             case VK_F4: index = 3; break;\r
-             case VK_F5: index = 4; break;\r
-             case VK_F6: index = 5; break;\r
-             case VK_F7: index = 6; break;\r
-             case VK_F8: index = 7; break;\r
-             case VK_F9: index = 8; break;\r
-             case VK_F10: index = 9; break;\r
-             case VK_F11: index = 10; break;\r
-             case VK_F12: index = 11; break;\r
-           }\r
-           if (keystate[VK_SHIFT] & 0x80) index += 12;\r
-           if (keystate[VK_CONTROL] & 0x80) index += 24;\r
-           p += sprintf((char *) p, "\x1B[%c", codes[index]);\r
-           return p - output;\r
-       }\r
-       if (cfg.funky_type == FUNKY_SCO &&     /* SCO small keypad */\r
-           code >= 1 && code <= 6) {\r
-           char codes[] = "HL.FIG";\r
-           if (code == 3) {\r
-               *p++ = '\x7F';\r
-           } else {\r
-               p += sprintf((char *) p, "\x1B[%c", codes[code-1]);\r
-           }\r
-           return p - output;\r
-       }\r
-       if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {\r
-           int offt = 0;\r
-           if (code > 15)\r
-               offt++;\r
-           if (code > 21)\r
-               offt++;\r
-           if (term->vt52_mode)\r
-               p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);\r
-           else\r
-               p +=\r
-                   sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);\r
-           return p - output;\r
-       }\r
-       if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {\r
-           p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);\r
-           return p - output;\r
-       }\r
-       if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {\r
-           if (term->vt52_mode)\r
-               p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);\r
-           else\r
-               p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);\r
-           return p - output;\r
-       }\r
-       if (cfg.rxvt_homeend && (code == 1 || code == 4)) {\r
-           p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");\r
-           return p - output;\r
-       }\r
-       if (code) {\r
-           p += sprintf((char *) p, "\x1B[%d~", code);\r
-           return p - output;\r
-       }\r
-\r
-       /*\r
-        * Now the remaining keys (arrows and Keypad 5. Keypad 5 for\r
-        * some reason seems to send VK_CLEAR to Windows...).\r
-        */\r
-       {\r
-           char xkey = 0;\r
-           switch (wParam) {\r
-             case VK_UP:\r
-               xkey = 'A';\r
-               break;\r
-             case VK_DOWN:\r
-               xkey = 'B';\r
-               break;\r
-             case VK_RIGHT:\r
-               xkey = 'C';\r
-               break;\r
-             case VK_LEFT:\r
-               xkey = 'D';\r
-               break;\r
-             case VK_CLEAR:\r
-               xkey = 'G';\r
-               break;\r
-           }\r
-           if (xkey) {\r
-               p += format_arrow_key(p, term, xkey, shift_state);\r
-               return p - output;\r
-           }\r
-       }\r
-\r
-       /*\r
-        * Finally, deal with Return ourselves. (Win95 seems to\r
-        * foul it up when Alt is pressed, for some reason.)\r
-        */\r
-       if (wParam == VK_RETURN) {     /* Return */\r
-           *p++ = 0x0D;\r
-           *p++ = 0;\r
-           return -2;\r
-       }\r
-\r
-       if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)\r
-           alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;\r
-       else\r
-           alt_sum = 0;\r
-    }\r
-\r
-    /* Okay we've done everything interesting; let windows deal with \r
-     * the boring stuff */\r
-    {\r
-       BOOL capsOn=0;\r
-\r
-       /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */\r
-       if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {\r
-           capsOn= !left_alt;\r
-           keystate[VK_CAPITAL] = 0;\r
-       }\r
-\r
-       /* XXX how do we know what the max size of the keys array should\r
-        * be is? There's indication on MS' website of an Inquire/InquireEx\r
-        * functioning returning a KBINFO structure which tells us. */\r
-       if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {\r
-           /* XXX 'keys' parameter is declared in MSDN documentation as\r
-            * 'LPWORD lpChar'.\r
-            * The experience of a French user indicates that on\r
-            * Win98, WORD[] should be passed in, but on Win2K, it should\r
-            * be BYTE[]. German WinXP and my Win2K with "US International"\r
-            * driver corroborate this.\r
-            * Experimentally I've conditionalised the behaviour on the\r
-            * Win9x/NT split, but I suspect it's worse than that.\r
-            * See wishlist item `win-dead-keys' for more horrible detail\r
-            * and speculations. */\r
-           BYTE keybs[3];\r
-           int i;\r
-           r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);\r
-           for (i=0; i<3; i++) keys[i] = keybs[i];\r
-       } else {\r
-           r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);\r
-       }\r
-#ifdef SHOW_TOASCII_RESULT\r
-       if (r == 1 && !key_down) {\r
-           if (alt_sum) {\r
-               if (in_utf(term) || ucsdata.dbcs_screenfont)\r
-                   debug((", (U+%04x)", alt_sum));\r
-               else\r
-                   debug((", LCH(%d)", alt_sum));\r
-           } else {\r
-               debug((", ACH(%d)", keys[0]));\r
-           }\r
-       } else if (r > 0) {\r
-           int r1;\r
-           debug((", ASC("));\r
-           for (r1 = 0; r1 < r; r1++) {\r
-               debug(("%s%d", r1 ? "," : "", keys[r1]));\r
-           }\r
-           debug((")"));\r
-       }\r
-#endif\r
-       if (r > 0) {\r
-           WCHAR keybuf;\r
-\r
-           /*\r
-            * Interrupt an ongoing paste. I'm not sure this is\r
-            * sensible, but for the moment it's preferable to\r
-            * having to faff about buffering things.\r
-            */\r
-           term_nopaste(term);\r
-\r
-           p = output;\r
-           for (i = 0; i < r; i++) {\r
-               unsigned char ch = (unsigned char) keys[i];\r
-\r
-               if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {\r
-                   compose_char = ch;\r
-                   compose_state++;\r
-                   continue;\r
-               }\r
-               if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {\r
-                   int nc;\r
-                   compose_state = 0;\r
-\r
-                   if ((nc = check_compose(compose_char, ch)) == -1) {\r
-                       MessageBeep(MB_ICONHAND);\r
-                       return 0;\r
-                   }\r
-                   keybuf = nc;\r
-                   term_seen_key_event(term);\r
-                   if (ldisc)\r
-                       luni_send(ldisc, &keybuf, 1, 1);\r
-                   continue;\r
-               }\r
-\r
-               compose_state = 0;\r
-\r
-               if (!key_down) {\r
-                   if (alt_sum) {\r
-                       if (in_utf(term) || ucsdata.dbcs_screenfont) {\r
-                           keybuf = alt_sum;\r
-                           term_seen_key_event(term);\r
-                           if (ldisc)\r
-                               luni_send(ldisc, &keybuf, 1, 1);\r
-                       } else {\r
-                           ch = (char) alt_sum;\r
-                           /*\r
-                            * We need not bother about stdin\r
-                            * backlogs here, because in GUI PuTTY\r
-                            * we can't do anything about it\r
-                            * anyway; there's no means of asking\r
-                            * Windows to hold off on KEYDOWN\r
-                            * messages. We _have_ to buffer\r
-                            * everything we're sent.\r
-                            */\r
-                           term_seen_key_event(term);\r
-                           if (ldisc)\r
-                               ldisc_send(ldisc, &ch, 1, 1);\r
-                       }\r
-                       alt_sum = 0;\r
-                   } else {\r
-                       term_seen_key_event(term);\r
-                       if (ldisc)\r
-                           lpage_send(ldisc, kbd_codepage, &ch, 1, 1);\r
-                   }\r
-               } else {\r
-                   if(capsOn && ch < 0x80) {\r
-                       WCHAR cbuf[2];\r
-                       cbuf[0] = 27;\r
-                       cbuf[1] = xlat_uskbd2cyrllic(ch);\r
-                       term_seen_key_event(term);\r
-                       if (ldisc)\r
-                           luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);\r
-                   } else {\r
-                       char cbuf[2];\r
-                       cbuf[0] = '\033';\r
-                       cbuf[1] = ch;\r
-                       term_seen_key_event(term);\r
-                       if (ldisc)\r
-                           lpage_send(ldisc, kbd_codepage,\r
-                                      cbuf+!left_alt, 1+!!left_alt, 1);\r
-                   }\r
-               }\r
-               show_mouseptr(0);\r
-           }\r
-\r
-           /* This is so the ALT-Numpad and dead keys work correctly. */\r
-           keys[0] = 0;\r
-\r
-           return p - output;\r
-       }\r
-       /* If we're definitly not building up an ALT-54321 then clear it */\r
-       if (!left_alt)\r
-           keys[0] = 0;\r
-       /* If we will be using alt_sum fix the 256s */\r
-       else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))\r
-           keys[0] = 10;\r
-    }\r
-\r
-    /*\r
-     * ALT alone may or may not want to bring up the System menu.\r
-     * If it's not meant to, we return 0 on presses or releases of\r
-     * ALT, to show that we've swallowed the keystroke. Otherwise\r
-     * we return -1, which means Windows will give the keystroke\r
-     * its default handling (i.e. bring up the System menu).\r
-     */\r
-    if (wParam == VK_MENU && !cfg.alt_only)\r
-       return 0;\r
-\r
-    return -1;\r
-}\r
-\r
-void set_title(void *frontend, char *title)\r
-{\r
-    sfree(window_name);\r
-    window_name = snewn(1 + strlen(title), char);\r
-    strcpy(window_name, title);\r
-    if (cfg.win_name_always || !IsIconic(hwnd))\r
-       SetWindowText(hwnd, title);\r
-}\r
-\r
-void set_icon(void *frontend, char *title)\r
-{\r
-    sfree(icon_name);\r
-    icon_name = snewn(1 + strlen(title), char);\r
-    strcpy(icon_name, title);\r
-    if (!cfg.win_name_always && IsIconic(hwnd))\r
-       SetWindowText(hwnd, title);\r
-}\r
-\r
-void set_sbar(void *frontend, int total, int start, int page)\r
-{\r
-    SCROLLINFO si;\r
-\r
-    if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)\r
-       return;\r
-\r
-    si.cbSize = sizeof(si);\r
-    si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;\r
-    si.nMin = 0;\r
-    si.nMax = total - 1;\r
-    si.nPage = page;\r
-    si.nPos = start;\r
-    if (hwnd)\r
-       SetScrollInfo(hwnd, SB_VERT, &si, TRUE);\r
-}\r
-\r
-Context get_ctx(void *frontend)\r
-{\r
-    HDC hdc;\r
-    if (hwnd) {\r
-       hdc = GetDC(hwnd);\r
-       if (hdc && pal)\r
-           SelectPalette(hdc, pal, FALSE);\r
-       return hdc;\r
-    } else\r
-       return NULL;\r
-}\r
-\r
-void free_ctx(Context ctx)\r
-{\r
-    SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);\r
-    ReleaseDC(hwnd, ctx);\r
-}\r
-\r
-static void real_palette_set(int n, int r, int g, int b)\r
-{\r
-    if (pal) {\r
-       logpal->palPalEntry[n].peRed = r;\r
-       logpal->palPalEntry[n].peGreen = g;\r
-       logpal->palPalEntry[n].peBlue = b;\r
-       logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;\r
-       colours[n] = PALETTERGB(r, g, b);\r
-       SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);\r
-    } else\r
-       colours[n] = RGB(r, g, b);\r
-}\r
-\r
-void palette_set(void *frontend, int n, int r, int g, int b)\r
-{\r
-    if (n >= 16)\r
-       n += 256 - 16;\r
-    if (n > NALLCOLOURS)\r
-       return;\r
-    real_palette_set(n, r, g, b);\r
-    if (pal) {\r
-       HDC hdc = get_ctx(frontend);\r
-       UnrealizeObject(pal);\r
-       RealizePalette(hdc);\r
-       free_ctx(hdc);\r
-    } else {\r
-       if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))\r
-           /* If Default Background changes, we need to ensure any\r
-            * space between the text area and the window border is\r
-            * redrawn. */\r
-           InvalidateRect(hwnd, NULL, TRUE);\r
-    }\r
-}\r
-\r
-void palette_reset(void *frontend)\r
-{\r
-    int i;\r
-\r
-    /* And this */\r
-    for (i = 0; i < NALLCOLOURS; i++) {\r
-       if (pal) {\r
-           logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;\r
-           logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;\r
-           logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;\r
-           logpal->palPalEntry[i].peFlags = 0;\r
-           colours[i] = PALETTERGB(defpal[i].rgbtRed,\r
-                                   defpal[i].rgbtGreen,\r
-                                   defpal[i].rgbtBlue);\r
-       } else\r
-           colours[i] = RGB(defpal[i].rgbtRed,\r
-                            defpal[i].rgbtGreen, defpal[i].rgbtBlue);\r
-    }\r
-\r
-    if (pal) {\r
-       HDC hdc;\r
-       SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);\r
-       hdc = get_ctx(frontend);\r
-       RealizePalette(hdc);\r
-       free_ctx(hdc);\r
-    } else {\r
-       /* Default Background may have changed. Ensure any space between\r
-        * text area and window border is redrawn. */\r
-       InvalidateRect(hwnd, NULL, TRUE);\r
-    }\r
-}\r
-\r
-void write_aclip(void *frontend, char *data, int len, int must_deselect)\r
-{\r
-    HGLOBAL clipdata;\r
-    void *lock;\r
-\r
-    clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);\r
-    if (!clipdata)\r
-       return;\r
-    lock = GlobalLock(clipdata);\r
-    if (!lock)\r
-       return;\r
-    memcpy(lock, data, len);\r
-    ((unsigned char *) lock)[len] = 0;\r
-    GlobalUnlock(clipdata);\r
-\r
-    if (!must_deselect)\r
-       SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);\r
-\r
-    if (OpenClipboard(hwnd)) {\r
-       EmptyClipboard();\r
-       SetClipboardData(CF_TEXT, clipdata);\r
-       CloseClipboard();\r
-    } else\r
-       GlobalFree(clipdata);\r
-\r
-    if (!must_deselect)\r
-       SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);\r
-}\r
-\r
-/*\r
- * Note: unlike write_aclip() this will not append a nul.\r
- */\r
-void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)\r
-{\r
-    HGLOBAL clipdata, clipdata2, clipdata3;\r
-    int len2;\r
-    void *lock, *lock2, *lock3;\r
-\r
-    len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);\r
-\r
-    clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,\r
-                          len * sizeof(wchar_t));\r
-    clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);\r
-\r
-    if (!clipdata || !clipdata2) {\r
-       if (clipdata)\r
-           GlobalFree(clipdata);\r
-       if (clipdata2)\r
-           GlobalFree(clipdata2);\r
-       return;\r
-    }\r
-    if (!(lock = GlobalLock(clipdata)))\r
-       return;\r
-    if (!(lock2 = GlobalLock(clipdata2)))\r
-       return;\r
-\r
-    memcpy(lock, data, len * sizeof(wchar_t));\r
-    WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);\r
-\r
-    if (cfg.rtf_paste) {\r
-       wchar_t unitab[256];\r
-       char *rtf = NULL;\r
-       unsigned char *tdata = (unsigned char *)lock2;\r
-       wchar_t *udata = (wchar_t *)lock;\r
-       int rtflen = 0, uindex = 0, tindex = 0;\r
-       int rtfsize = 0;\r
-       int multilen, blen, alen, totallen, i;\r
-       char before[16], after[4];\r
-       int fgcolour,  lastfgcolour  = 0;\r
-       int bgcolour,  lastbgcolour  = 0;\r
-       int attrBold,  lastAttrBold  = 0;\r
-       int attrUnder, lastAttrUnder = 0;\r
-       int palette[NALLCOLOURS];\r
-       int numcolours;\r
-\r
-       get_unitab(CP_ACP, unitab, 0);\r
-\r
-       rtfsize = 100 + strlen(cfg.font.name);\r
-       rtf = snewn(rtfsize, char);\r
-       rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",\r
-                        cfg.font.name, cfg.font.height*2);\r
-\r
-       /*\r
-        * Add colour palette\r
-        * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}\r
-        */\r
-\r
-       /*\r
-        * First - Determine all colours in use\r
-        *    o  Foregound and background colours share the same palette\r
-        */\r
-       if (attr) {\r
-           memset(palette, 0, sizeof(palette));\r
-           for (i = 0; i < (len-1); i++) {\r
-               fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);\r
-               bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);\r
-\r
-               if (attr[i] & ATTR_REVERSE) {\r
-                   int tmpcolour = fgcolour;   /* Swap foreground and background */\r
-                   fgcolour = bgcolour;\r
-                   bgcolour = tmpcolour;\r
-               }\r
-\r
-               if (bold_mode == BOLD_COLOURS && (attr[i] & ATTR_BOLD)) {\r
-                   if (fgcolour  <   8)        /* ANSI colours */\r
-                       fgcolour +=   8;\r
-                   else if (fgcolour >= 256)   /* Default colours */\r
-                       fgcolour ++;\r
-               }\r
-\r
-               if (attr[i] & ATTR_BLINK) {\r
-                   if (bgcolour  <   8)        /* ANSI colours */\r
-                       bgcolour +=   8;\r
-                   else if (bgcolour >= 256)   /* Default colours */\r
-                       bgcolour ++;\r
-               }\r
-\r
-               palette[fgcolour]++;\r
-               palette[bgcolour]++;\r
-           }\r
-\r
-           /*\r
-            * Next - Create a reduced palette\r
-            */\r
-           numcolours = 0;\r
-           for (i = 0; i < NALLCOLOURS; i++) {\r
-               if (palette[i] != 0)\r
-                   palette[i]  = ++numcolours;\r
-           }\r
-\r
-           /*\r
-            * Finally - Write the colour table\r
-            */\r
-           rtf = sresize(rtf, rtfsize + (numcolours * 25), char);\r
-           strcat(rtf, "{\\colortbl ;");\r
-           rtflen = strlen(rtf);\r
-\r
-           for (i = 0; i < NALLCOLOURS; i++) {\r
-               if (palette[i] != 0) {\r
-                   rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);\r
-               }\r
-           }\r
-           strcpy(&rtf[rtflen], "}");\r
-           rtflen ++;\r
-       }\r
-\r
-       /*\r
-        * We want to construct a piece of RTF that specifies the\r
-        * same Unicode text. To do this we will read back in\r
-        * parallel from the Unicode data in `udata' and the\r
-        * non-Unicode data in `tdata'. For each character in\r
-        * `tdata' which becomes the right thing in `udata' when\r
-        * looked up in `unitab', we just copy straight over from\r
-        * tdata. For each one that doesn't, we must WCToMB it\r
-        * individually and produce a \u escape sequence.\r
-        * \r
-        * It would probably be more robust to just bite the bullet\r
-        * and WCToMB each individual Unicode character one by one,\r
-        * then MBToWC each one back to see if it was an accurate\r
-        * translation; but that strikes me as a horrifying number\r
-        * of Windows API calls so I want to see if this faster way\r
-        * will work. If it screws up badly we can always revert to\r
-        * the simple and slow way.\r
-        */\r
-       while (tindex < len2 && uindex < len &&\r
-              tdata[tindex] && udata[uindex]) {\r
-           if (tindex + 1 < len2 &&\r
-               tdata[tindex] == '\r' &&\r
-               tdata[tindex+1] == '\n') {\r
-               tindex++;\r
-               uindex++;\r
-            }\r
-\r
-            /*\r
-             * Set text attributes\r
-             */\r
-            if (attr) {\r
-                if (rtfsize < rtflen + 64) {\r
-                   rtfsize = rtflen + 512;\r
-                   rtf = sresize(rtf, rtfsize, char);\r
-                }\r
-\r
-                /*\r
-                 * Determine foreground and background colours\r
-                 */\r
-                fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);\r
-                bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);\r
-\r
-               if (attr[tindex] & ATTR_REVERSE) {\r
-                   int tmpcolour = fgcolour;       /* Swap foreground and background */\r
-                   fgcolour = bgcolour;\r
-                   bgcolour = tmpcolour;\r
-               }\r
-\r
-               if (bold_mode == BOLD_COLOURS && (attr[tindex] & ATTR_BOLD)) {\r
-                   if (fgcolour  <   8)            /* ANSI colours */\r
-                       fgcolour +=   8;\r
-                   else if (fgcolour >= 256)       /* Default colours */\r
-                       fgcolour ++;\r
-                }\r
-\r
-               if (attr[tindex] & ATTR_BLINK) {\r
-                   if (bgcolour  <   8)            /* ANSI colours */\r
-                       bgcolour +=   8;\r
-                   else if (bgcolour >= 256)       /* Default colours */\r
-                       bgcolour ++;\r
-                }\r
-\r
-                /*\r
-                 * Collect other attributes\r
-                 */\r
-               if (bold_mode != BOLD_COLOURS)\r
-                   attrBold  = attr[tindex] & ATTR_BOLD;\r
-               else\r
-                   attrBold  = 0;\r
-                \r
-               attrUnder = attr[tindex] & ATTR_UNDER;\r
-\r
-                /*\r
-                 * Reverse video\r
-                *   o  If video isn't reversed, ignore colour attributes for default foregound\r
-                *      or background.\r
-                *   o  Special case where bolded text is displayed using the default foregound\r
-                *      and background colours - force to bolded RTF.\r
-                 */\r
-               if (!(attr[tindex] & ATTR_REVERSE)) {\r
-                   if (bgcolour >= 256)            /* Default color */\r
-                       bgcolour  = -1;             /* No coloring */\r
-\r
-                   if (fgcolour >= 256) {          /* Default colour */\r
-                       if (bold_mode == BOLD_COLOURS && (fgcolour & 1) && bgcolour == -1)\r
-                           attrBold = ATTR_BOLD;   /* Emphasize text with bold attribute */\r
-\r
-                       fgcolour  = -1;             /* No coloring */\r
-                   }\r
-               }\r
-\r
-                /*\r
-                 * Write RTF text attributes\r
-                 */\r
-               if (lastfgcolour != fgcolour) {\r
-                    lastfgcolour  = fgcolour;\r
-                   rtflen       += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);\r
-                }\r
-\r
-                if (lastbgcolour != bgcolour) {\r
-                    lastbgcolour  = bgcolour;\r
-                    rtflen       += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);\r
-                }\r
-\r
-               if (lastAttrBold != attrBold) {\r
-                   lastAttrBold  = attrBold;\r
-                   rtflen       += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");\r
-               }\r
-\r
-                if (lastAttrUnder != attrUnder) {\r
-                    lastAttrUnder  = attrUnder;\r
-                    rtflen        += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");\r
-                }\r
-           }\r
-\r
-           if (unitab[tdata[tindex]] == udata[uindex]) {\r
-               multilen = 1;\r
-               before[0] = '\0';\r
-               after[0] = '\0';\r
-               blen = alen = 0;\r
-           } else {\r
-               multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,\r
-                                              NULL, 0, NULL, NULL);\r
-               if (multilen != 1) {\r
-                   blen = sprintf(before, "{\\uc%d\\u%d", multilen,\r
-                                  udata[uindex]);\r
-                   alen = 1; strcpy(after, "}");\r
-               } else {\r
-                   blen = sprintf(before, "\\u%d", udata[uindex]);\r
-                   alen = 0; after[0] = '\0';\r
-               }\r
-           }\r
-           assert(tindex + multilen <= len2);\r
-           totallen = blen + alen;\r
-           for (i = 0; i < multilen; i++) {\r
-               if (tdata[tindex+i] == '\\' ||\r
-                   tdata[tindex+i] == '{' ||\r
-                   tdata[tindex+i] == '}')\r
-                   totallen += 2;\r
-               else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)\r
-                   totallen += 6;     /* \par\r\n */\r
-               else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)\r
-                   totallen += 4;\r
-               else\r
-                   totallen++;\r
-           }\r
-\r
-           if (rtfsize < rtflen + totallen + 3) {\r
-               rtfsize = rtflen + totallen + 512;\r
-               rtf = sresize(rtf, rtfsize, char);\r
-           }\r
-\r
-           strcpy(rtf + rtflen, before); rtflen += blen;\r
-           for (i = 0; i < multilen; i++) {\r
-               if (tdata[tindex+i] == '\\' ||\r
-                   tdata[tindex+i] == '{' ||\r
-                   tdata[tindex+i] == '}') {\r
-                   rtf[rtflen++] = '\\';\r
-                   rtf[rtflen++] = tdata[tindex+i];\r
-               } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {\r
-                   rtflen += sprintf(rtf+rtflen, "\\par\r\n");\r
-               } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {\r
-                   rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);\r
-               } else {\r
-                   rtf[rtflen++] = tdata[tindex+i];\r
-               }\r
-           }\r
-           strcpy(rtf + rtflen, after); rtflen += alen;\r
-\r
-           tindex += multilen;\r
-           uindex++;\r
-       }\r
-\r
-        rtf[rtflen++] = '}';          /* Terminate RTF stream */\r
-        rtf[rtflen++] = '\0';\r
-        rtf[rtflen++] = '\0';\r
-\r
-       clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);\r
-       if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {\r
-           memcpy(lock3, rtf, rtflen);\r
-           GlobalUnlock(clipdata3);\r
-       }\r
-       sfree(rtf);\r
-    } else\r
-       clipdata3 = NULL;\r
-\r
-    GlobalUnlock(clipdata);\r
-    GlobalUnlock(clipdata2);\r
-\r
-    if (!must_deselect)\r
-       SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);\r
-\r
-    if (OpenClipboard(hwnd)) {\r
-       EmptyClipboard();\r
-       SetClipboardData(CF_UNICODETEXT, clipdata);\r
-       SetClipboardData(CF_TEXT, clipdata2);\r
-       if (clipdata3)\r
-           SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);\r
-       CloseClipboard();\r
-    } else {\r
-       GlobalFree(clipdata);\r
-       GlobalFree(clipdata2);\r
-    }\r
-\r
-    if (!must_deselect)\r
-       SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);\r
-}\r
-\r
-static DWORD WINAPI clipboard_read_threadfunc(void *param)\r
-{\r
-    HWND hwnd = (HWND)param;\r
-    HGLOBAL clipdata;\r
-\r
-    if (OpenClipboard(NULL)) {\r
-       if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {\r
-           SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);\r
-       } else if ((clipdata = GetClipboardData(CF_TEXT))) {\r
-           SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);\r
-       }\r
-       CloseClipboard();\r
-    }\r
-\r
-    return 0;\r
-}\r
-\r
-static int process_clipdata(HGLOBAL clipdata, int unicode)\r
-{\r
-    sfree(clipboard_contents);\r
-    clipboard_contents = NULL;\r
-    clipboard_length = 0;\r
-\r
-    if (unicode) {\r
-       wchar_t *p = GlobalLock(clipdata);\r
-       wchar_t *p2;\r
-\r
-       if (p) {\r
-           /* Unwilling to rely on Windows having wcslen() */\r
-           for (p2 = p; *p2; p2++);\r
-           clipboard_length = p2 - p;\r
-           clipboard_contents = snewn(clipboard_length + 1, wchar_t);\r
-           memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));\r
-           clipboard_contents[clipboard_length] = L'\0';\r
-           return TRUE;\r
-       }\r
-    } else {\r
-       char *s = GlobalLock(clipdata);\r
-       int i;\r
-\r
-       if (s) {\r
-           i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);\r
-           clipboard_contents = snewn(i, wchar_t);\r
-           MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,\r
-                               clipboard_contents, i);\r
-           clipboard_length = i - 1;\r
-           clipboard_contents[clipboard_length] = L'\0';\r
-           return TRUE;\r
-       }\r
-    }\r
-\r
-    return FALSE;\r
-}\r
-\r
-void request_paste(void *frontend)\r
-{\r
-    /*\r
-     * I always thought pasting was synchronous in Windows; the\r
-     * clipboard access functions certainly _look_ synchronous,\r
-     * unlike the X ones. But in fact it seems that in some\r
-     * situations the contents of the clipboard might not be\r
-     * immediately available, and the clipboard-reading functions\r
-     * may block. This leads to trouble if the application\r
-     * delivering the clipboard data has to get hold of it by -\r
-     * for example - talking over a network connection which is\r
-     * forwarded through this very PuTTY.\r
-     *\r
-     * Hence, we spawn a subthread to read the clipboard, and do\r
-     * our paste when it's finished. The thread will send a\r
-     * message back to our main window when it terminates, and\r
-     * that tells us it's OK to paste.\r
-     */\r
-    DWORD in_threadid; /* required for Win9x */\r
-    CreateThread(NULL, 0, clipboard_read_threadfunc,\r
-                hwnd, 0, &in_threadid);\r
-}\r
-\r
-void get_clip(void *frontend, wchar_t **p, int *len)\r
-{\r
-    if (p) {\r
-       *p = clipboard_contents;\r
-       *len = clipboard_length;\r
-    }\r
-}\r
-\r
-#if 0\r
-/*\r
- * Move `lines' lines from position `from' to position `to' in the\r
- * window.\r
- */\r
-void optimised_move(void *frontend, int to, int from, int lines)\r
-{\r
-    RECT r;\r
-    int min, max;\r
-\r
-    min = (to < from ? to : from);\r
-    max = to + from - min;\r
-\r
-    r.left = offset_width;\r
-    r.right = offset_width + term->cols * font_width;\r
-    r.top = offset_height + min * font_height;\r
-    r.bottom = offset_height + (max + lines) * font_height;\r
-    ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);\r
-}\r
-#endif\r
-\r
-/*\r
- * Print a message box and perform a fatal exit.\r
- */\r
-void fatalbox(char *fmt, ...)\r
-{\r
-    va_list ap;\r
-    char *stuff, morestuff[100];\r
-\r
-    va_start(ap, fmt);\r
-    stuff = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    sprintf(morestuff, "%.70s Fatal Error", appname);\r
-    MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);\r
-    sfree(stuff);\r
-    cleanup_exit(1);\r
-}\r
-\r
-/*\r
- * Print a modal (Really Bad) message box and perform a fatal exit.\r
- */\r
-void modalfatalbox(char *fmt, ...)\r
-{\r
-    va_list ap;\r
-    char *stuff, morestuff[100];\r
-\r
-    va_start(ap, fmt);\r
-    stuff = dupvprintf(fmt, ap);\r
-    va_end(ap);\r
-    sprintf(morestuff, "%.70s Fatal Error", appname);\r
-    MessageBox(hwnd, stuff, morestuff,\r
-              MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);\r
-    sfree(stuff);\r
-    cleanup_exit(1);\r
-}\r
-\r
-DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));\r
-\r
-static void init_flashwindow(void)\r
-{\r
-    HMODULE user32_module = load_system32_dll("user32.dll");\r
-    GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);\r
-}\r
-\r
-static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)\r
-{\r
-    if (p_FlashWindowEx) {\r
-       FLASHWINFO fi;\r
-       fi.cbSize = sizeof(fi);\r
-       fi.hwnd = hwnd;\r
-       fi.dwFlags = dwFlags;\r
-       fi.uCount = uCount;\r
-       fi.dwTimeout = dwTimeout;\r
-       return (*p_FlashWindowEx)(&fi);\r
-    }\r
-    else\r
-       return FALSE; /* shrug */\r
-}\r
-\r
-static void flash_window(int mode);\r
-static long next_flash;\r
-static int flashing = 0;\r
-\r
-/*\r
- * Timer for platforms where we must maintain window flashing manually\r
- * (e.g., Win95).\r
- */\r
-static void flash_window_timer(void *ctx, long now)\r
-{\r
-    if (flashing && now - next_flash >= 0) {\r
-       flash_window(1);\r
-    }\r
-}\r
-\r
-/*\r
- * Manage window caption / taskbar flashing, if enabled.\r
- * 0 = stop, 1 = maintain, 2 = start\r
- */\r
-static void flash_window(int mode)\r
-{\r
-    if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {\r
-       /* stop */\r
-       if (flashing) {\r
-           flashing = 0;\r
-           if (p_FlashWindowEx)\r
-               flash_window_ex(FLASHW_STOP, 0, 0);\r
-           else\r
-               FlashWindow(hwnd, FALSE);\r
-       }\r
-\r
-    } else if (mode == 2) {\r
-       /* start */\r
-       if (!flashing) {\r
-           flashing = 1;\r
-           if (p_FlashWindowEx) {\r
-               /* For so-called "steady" mode, we use uCount=2, which\r
-                * seems to be the traditional number of flashes used\r
-                * by user notifications (e.g., by Explorer).\r
-                * uCount=0 appears to enable continuous flashing, per\r
-                * "flashing" mode, although I haven't seen this\r
-                * documented. */\r
-               flash_window_ex(FLASHW_ALL | FLASHW_TIMER,\r
-                               (cfg.beep_ind == B_IND_FLASH ? 0 : 2),\r
-                               0 /* system cursor blink rate */);\r
-               /* No need to schedule timer */\r
-           } else {\r
-               FlashWindow(hwnd, TRUE);\r
-               next_flash = schedule_timer(450, flash_window_timer, hwnd);\r
-           }\r
-       }\r
-\r
-    } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {\r
-       /* maintain */\r
-       if (flashing && !p_FlashWindowEx) {\r
-           FlashWindow(hwnd, TRUE);    /* toggle */\r
-           next_flash = schedule_timer(450, flash_window_timer, hwnd);\r
-       }\r
-    }\r
-}\r
-\r
-/*\r
- * Beep.\r
- */\r
-void do_beep(void *frontend, int mode)\r
-{\r
-    if (mode == BELL_DEFAULT) {\r
-       /*\r
-        * For MessageBeep style bells, we want to be careful of\r
-        * timing, because they don't have the nice property of\r
-        * PlaySound bells that each one cancels the previous\r
-        * active one. So we limit the rate to one per 50ms or so.\r
-        */\r
-       static long lastbeep = 0;\r
-       long beepdiff;\r
-\r
-       beepdiff = GetTickCount() - lastbeep;\r
-       if (beepdiff >= 0 && beepdiff < 50)\r
-           return;\r
-       MessageBeep(MB_OK);\r
-       /*\r
-        * The above MessageBeep call takes time, so we record the\r
-        * time _after_ it finishes rather than before it starts.\r
-        */\r
-       lastbeep = GetTickCount();\r
-    } else if (mode == BELL_WAVEFILE) {\r
-       if (!PlaySound(cfg.bell_wavefile.path, NULL,\r
-                      SND_ASYNC | SND_FILENAME)) {\r
-           char buf[sizeof(cfg.bell_wavefile.path) + 80];\r
-           char otherbuf[100];\r
-           sprintf(buf, "Unable to play sound file\n%s\n"\r
-                   "Using default sound instead", cfg.bell_wavefile.path);\r
-           sprintf(otherbuf, "%.70s Sound Error", appname);\r
-           MessageBox(hwnd, buf, otherbuf,\r
-                      MB_OK | MB_ICONEXCLAMATION);\r
-           cfg.beep = BELL_DEFAULT;\r
-       }\r
-    } else if (mode == BELL_PCSPEAKER) {\r
-       static long lastbeep = 0;\r
-       long beepdiff;\r
-\r
-       beepdiff = GetTickCount() - lastbeep;\r
-       if (beepdiff >= 0 && beepdiff < 50)\r
-           return;\r
-\r
-       /*\r
-        * We must beep in different ways depending on whether this\r
-        * is a 95-series or NT-series OS.\r
-        */\r
-       if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)\r
-           Beep(800, 100);\r
-       else\r
-           MessageBeep(-1);\r
-       lastbeep = GetTickCount();\r
-    }\r
-    /* Otherwise, either visual bell or disabled; do nothing here */\r
-    if (!term->has_focus) {\r
-       flash_window(2);               /* start */\r
-    }\r
-}\r
-\r
-/*\r
- * Minimise or restore the window in response to a server-side\r
- * request.\r
- */\r
-void set_iconic(void *frontend, int iconic)\r
-{\r
-    if (IsIconic(hwnd)) {\r
-       if (!iconic)\r
-           ShowWindow(hwnd, SW_RESTORE);\r
-    } else {\r
-       if (iconic)\r
-           ShowWindow(hwnd, SW_MINIMIZE);\r
-    }\r
-}\r
-\r
-/*\r
- * Move the window in response to a server-side request.\r
- */\r
-void move_window(void *frontend, int x, int y)\r
-{\r
-    if (cfg.resize_action == RESIZE_DISABLED || \r
-        cfg.resize_action == RESIZE_FONT ||\r
-       IsZoomed(hwnd))\r
-       return;\r
-\r
-    SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\r
-}\r
-\r
-/*\r
- * Move the window to the top or bottom of the z-order in response\r
- * to a server-side request.\r
- */\r
-void set_zorder(void *frontend, int top)\r
-{\r
-    if (cfg.alwaysontop)\r
-       return;                        /* ignore */\r
-    SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,\r
-                SWP_NOMOVE | SWP_NOSIZE);\r
-}\r
-\r
-/*\r
- * Refresh the window in response to a server-side request.\r
- */\r
-void refresh_window(void *frontend)\r
-{\r
-    InvalidateRect(hwnd, NULL, TRUE);\r
-}\r
-\r
-/*\r
- * Maximise or restore the window in response to a server-side\r
- * request.\r
- */\r
-void set_zoomed(void *frontend, int zoomed)\r
-{\r
-    if (IsZoomed(hwnd)) {\r
-        if (!zoomed)\r
-           ShowWindow(hwnd, SW_RESTORE);\r
-    } else {\r
-       if (zoomed)\r
-           ShowWindow(hwnd, SW_MAXIMIZE);\r
-    }\r
-}\r
-\r
-/*\r
- * Report whether the window is iconic, for terminal reports.\r
- */\r
-int is_iconic(void *frontend)\r
-{\r
-    return IsIconic(hwnd);\r
-}\r
-\r
-/*\r
- * Report the window's position, for terminal reports.\r
- */\r
-void get_window_pos(void *frontend, int *x, int *y)\r
-{\r
-    RECT r;\r
-    GetWindowRect(hwnd, &r);\r
-    *x = r.left;\r
-    *y = r.top;\r
-}\r
-\r
-/*\r
- * Report the window's pixel size, for terminal reports.\r
- */\r
-void get_window_pixels(void *frontend, int *x, int *y)\r
-{\r
-    RECT r;\r
-    GetWindowRect(hwnd, &r);\r
-    *x = r.right - r.left;\r
-    *y = r.bottom - r.top;\r
-}\r
-\r
-/*\r
- * Return the window or icon title.\r
- */\r
-char *get_window_title(void *frontend, int icon)\r
-{\r
-    return icon ? icon_name : window_name;\r
-}\r
-\r
-/*\r
- * See if we're in full-screen mode.\r
- */\r
-static int is_full_screen()\r
-{\r
-    if (!IsZoomed(hwnd))\r
-       return FALSE;\r
-    if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)\r
-       return FALSE;\r
-    return TRUE;\r
-}\r
-\r
-/* Get the rect/size of a full screen window using the nearest available\r
- * monitor in multimon systems; default to something sensible if only\r
- * one monitor is present. */\r
-static int get_fullscreen_rect(RECT * ss)\r
-{\r
-#if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)\r
-       HMONITOR mon;\r
-       MONITORINFO mi;\r
-       mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);\r
-       mi.cbSize = sizeof(mi);\r
-       GetMonitorInfo(mon, &mi);\r
-\r
-       /* structure copy */\r
-       *ss = mi.rcMonitor;\r
-       return TRUE;\r
-#else\r
-/* could also use code like this:\r
-       ss->left = ss->top = 0;\r
-       ss->right = GetSystemMetrics(SM_CXSCREEN);\r
-       ss->bottom = GetSystemMetrics(SM_CYSCREEN);\r
-*/ \r
-       return GetClientRect(GetDesktopWindow(), ss);\r
-#endif\r
-}\r
-\r
-\r
-/*\r
- * Go full-screen. This should only be called when we are already\r
- * maximised.\r
- */\r
-static void make_full_screen()\r
-{\r
-    DWORD style;\r
-       RECT ss;\r
-\r
-    assert(IsZoomed(hwnd));\r
-\r
-       if (is_full_screen())\r
-               return;\r
-       \r
-    /* Remove the window furniture. */\r
-    style = GetWindowLongPtr(hwnd, GWL_STYLE);\r
-    style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);\r
-    if (cfg.scrollbar_in_fullscreen)\r
-       style |= WS_VSCROLL;\r
-    else\r
-       style &= ~WS_VSCROLL;\r
-    SetWindowLongPtr(hwnd, GWL_STYLE, style);\r
-\r
-    /* Resize ourselves to exactly cover the nearest monitor. */\r
-       get_fullscreen_rect(&ss);\r
-    SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,\r
-                       ss.right - ss.left,\r
-                       ss.bottom - ss.top,\r
-                       SWP_FRAMECHANGED);\r
-\r
-    /* We may have changed size as a result */\r
-\r
-    reset_window(0);\r
-\r
-    /* Tick the menu item in the System and context menus. */\r
-    {\r
-       int i;\r
-       for (i = 0; i < lenof(popup_menus); i++)\r
-           CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);\r
-    }\r
-}\r
-\r
-/*\r
- * Clear the full-screen attributes.\r
- */\r
-static void clear_full_screen()\r
-{\r
-    DWORD oldstyle, style;\r
-\r
-    /* Reinstate the window furniture. */\r
-    style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);\r
-    style |= WS_CAPTION | WS_BORDER;\r
-    if (cfg.resize_action == RESIZE_DISABLED)\r
-        style &= ~WS_THICKFRAME;\r
-    else\r
-        style |= WS_THICKFRAME;\r
-    if (cfg.scrollbar)\r
-       style |= WS_VSCROLL;\r
-    else\r
-       style &= ~WS_VSCROLL;\r
-    if (style != oldstyle) {\r
-       SetWindowLongPtr(hwnd, GWL_STYLE, style);\r
-       SetWindowPos(hwnd, NULL, 0, 0, 0, 0,\r
-                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |\r
-                    SWP_FRAMECHANGED);\r
-    }\r
-\r
-    /* Untick the menu item in the System and context menus. */\r
-    {\r
-       int i;\r
-       for (i = 0; i < lenof(popup_menus); i++)\r
-           CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);\r
-    }\r
-}\r
-\r
-/*\r
- * Toggle full-screen mode.\r
- */\r
-static void flip_full_screen()\r
-{\r
-    if (is_full_screen()) {\r
-       ShowWindow(hwnd, SW_RESTORE);\r
-    } else if (IsZoomed(hwnd)) {\r
-       make_full_screen();\r
-    } else {\r
-       SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);\r
-       ShowWindow(hwnd, SW_MAXIMIZE);\r
-    }\r
-}\r
-\r
-void frontend_keypress(void *handle)\r
-{\r
-    /*\r
-     * Keypress termination in non-Close-On-Exit mode is not\r
-     * currently supported in PuTTY proper, because the window\r
-     * always has a perfectly good Close button anyway. So we do\r
-     * nothing here.\r
-     */\r
-    return;\r
-}\r
-\r
-int from_backend(void *frontend, int is_stderr, const char *data, int len)\r
-{\r
-    return term_data(term, is_stderr, data, len);\r
-}\r
-\r
-int from_backend_untrusted(void *frontend, const char *data, int len)\r
-{\r
-    return term_data_untrusted(term, data, len);\r
-}\r
-\r
-int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)\r
-{\r
-    int ret;\r
-    ret = cmdline_get_passwd_input(p, in, inlen);\r
-    if (ret == -1)\r
-       ret = term_get_userpass_input(term, p, in, inlen);\r
-    return ret;\r
-}\r
-\r
-void agent_schedule_callback(void (*callback)(void *, void *, int),\r
-                            void *callback_ctx, void *data, int len)\r
-{\r
-    struct agent_callback *c = snew(struct agent_callback);\r
-    c->callback = callback;\r
-    c->callback_ctx = callback_ctx;\r
-    c->data = data;\r
-    c->len = len;\r
-    PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);\r
-}\r