Revamp SSH authentication code so that user interaction is more
[u/mdw/putty] / mac / macterm.c
index d30031e..68d8276 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: macterm.c,v 1.67 2003/02/04 02:08:03 ben Exp $ */
+/* $Id$ */
 /*
  * Copyright (c) 1999 Simon Tatham
  * Copyright (c) 1999, 2002 Ben Harris
 #include "mac.h"
 #include "terminal.h"
 
-#define NCOLOURS (lenof(((Config *)0)->colours))
-
-#define DEFAULT_FG     16
-#define DEFAULT_FG_BOLD        17
-#define DEFAULT_BG     18
-#define DEFAULT_BG_BOLD        19
-#define CURSOR_FG      20
-#define CURSOR_BG      21
+#define DEFAULT_FG     256
+#define DEFAULT_FG_BOLD        257
+#define DEFAULT_BG     258
+#define DEFAULT_BG_BOLD        259
+#define CURSOR_FG      260
+#define CURSOR_BG      261
 
 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
                            (x) / s->font_width)
@@ -89,15 +87,27 @@ static void mac_drawgrowicon(Session *s);
 static pascal void mac_growtermdraghook(void);
 static pascal void mac_scrolltracker(ControlHandle, short);
 static pascal void do_text_for_device(short, short, GDHandle, long);
+static void do_text_internal(Context, int, int, wchar_t *, int,
+                            unsigned long, int);
 static void text_click(Session *, EventRecord *);
+static void mac_activateterm(WindowPtr, EventRecord *);
+static void mac_adjusttermcursor(WindowPtr, Point, RgnHandle);
+static void mac_adjusttermmenus(WindowPtr);
+static void mac_updateterm(WindowPtr);
+static void mac_clickterm(WindowPtr, EventRecord *);
+static void mac_growterm(WindowPtr, EventRecord *);
+static void mac_keyterm(WindowPtr, EventRecord *);
+static void mac_menuterm(WindowPtr, short, short);
+static void mac_closeterm(WindowPtr);
 
 void pre_paint(Session *s);
 void post_paint(Session *s);
 
 void mac_startsession(Session *s)
 {
-    char *errmsg;
+    const char *errmsg;
     int i;
+    WinInfo *wi;
 
     init_ucs(s);
 
@@ -119,7 +129,20 @@ void mac_startsession(Session *s)
        s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
     else
        s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
-    SetWRefCon(s->window, (long)s);
+    wi = snew(WinInfo);
+    memset(wi, 0, sizeof(*wi));
+    wi->s = s;
+    wi->wtype = wTerminal;
+    wi->activate = &mac_activateterm;
+    wi->adjustcursor = &mac_adjusttermcursor;
+    wi->adjustmenus = &mac_adjusttermmenus;
+    wi->update = &mac_updateterm;
+    wi->click = &mac_clickterm;
+    wi->grow = &mac_growterm;
+    wi->key = &mac_keyterm;
+    wi->menu = &mac_menuterm;
+    wi->close = &mac_closeterm;
+    SetWRefCon(s->window, (long)wi);
     s->scrollbar = GetNewControl(cVScroll, s->window);
     s->term = term_init(&s->cfg, &s->ucsdata, s);
 
@@ -131,11 +154,12 @@ void mac_startsession(Session *s)
        ActivatePalette(s->window);
     }
 
-    s->logctx = log_init(s, &s->cfg);
+    s->logctx = log_init(s->term, &s->cfg);
     term_provide_logctx(s->term, s->logctx);
 
-    errmsg = s->back->init(s->term, &s->backhandle, &s->cfg, s->cfg.host,
-                          s->cfg.port, &s->realhost, s->cfg.tcp_nodelay);
+    errmsg = s->back->init(s, &s->backhandle, &s->cfg, s->cfg.host,
+                          s->cfg.port, &s->realhost, s->cfg.tcp_nodelay,
+                          s->cfg.tcp_keepalives);
     if (errmsg != NULL)
        fatalbox("%s", errmsg);
     s->back->provide_logctx(s->backhandle, s->logctx);
@@ -170,9 +194,9 @@ static void mac_workoutfontscale(Session *s, int wantwidth,
     const char text = 'W';
     FontInfo fi;
 #if TARGET_API_MAC_CARBON
-    CQDProcsPtr gp = GetPortGrafProcs(GetWindowPort(s->window));;
+    CQDProcsPtr gp = GetPortGrafProcs(GetWindowPort(s->window));
 #else
-    QDProcsPtr gp = s->window->grafProcs;;
+    QDProcsPtr gp = s->window->grafProcs;
 #endif
 
     numer.v = denom.v = 1; /* always */
@@ -199,7 +223,8 @@ static void mac_workoutfontscale(Session *s, int wantwidth,
 
 static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
 
-static void mac_initfont(Session *s) {
+static void mac_initfont(Session *s)
+{
     FontInfo fi;
     TextEncoding enc;
     OptionBits fbflags;
@@ -282,19 +307,6 @@ static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
 }
 
 /*
- * Called every time round the event loop.
- */
-void mac_pollterm(void)
-{
-    Session *s;
-
-    for (s = sesslist; s != NULL; s = s->next) {
-       term_out(s->term);
-       term_update(s->term);
-    }
-}
-
-/*
  * To be called whenever the window size changes.
  * rows and cols should be desired values.
  * It's assumed the terminal emulator will be informed, and will set rows
@@ -302,18 +314,23 @@ void mac_pollterm(void)
  */
 static void mac_adjustsize(Session *s, int newrows, int newcols) {
     int winwidth, winheight;
+    int extraforscroll;
 
-    winwidth = newcols * s->font_width + 15;
+    extraforscroll=s->cfg.scrollbar ? 15 : 0;
+    winwidth = newcols * s->font_width + extraforscroll;
     winheight = newrows * s->font_height;
     SizeWindow(s->window, winwidth, winheight, true);
-    HideControl(s->scrollbar);
-    MoveControl(s->scrollbar, winwidth - 15, -1);
-    SizeControl(s->scrollbar, 16, winheight - 13);
-    ShowControl(s->scrollbar);
+    if (s->cfg.scrollbar) {
+        HideControl(s->scrollbar);
+        MoveControl(s->scrollbar, winwidth - extraforscroll, -1);
+        SizeControl(s->scrollbar, extraforscroll + 1, winheight - 13);
+        ShowControl(s->scrollbar);
+    }
     mac_drawgrowicon(s);
 }
 
-static void mac_initpalette(Session *s) {
+static void mac_initpalette(Session *s)
+{
 
     if (!HAVE_COLOR_QD())
        return;
@@ -325,7 +342,7 @@ static void mac_initpalette(Session *s) {
 #define PM_NORMAL      ( pmTolerant | pmInhibitC2 |                    \
                          pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
 #define PM_TOLERANCE   0x2000
-    s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
+    s->palette = NewPalette(262, NULL, PM_NORMAL, PM_TOLERANCE);
     if (s->palette == NULL)
        fatalbox("Unable to create palette");
     /* In 2bpp, these are the colours we want most. */
@@ -344,7 +361,8 @@ static void mac_initpalette(Session *s) {
  * Set the background colour of the window correctly.  Should be
  * called whenever the default background changes.
  */
-static void mac_adjustwinbg(Session *s) {
+static void mac_adjustwinbg(Session *s)
+{
 
     if (!HAVE_COLOR_QD())
        return;
@@ -373,7 +391,9 @@ static void mac_adjustwinbg(Session *s) {
 /*
  * Set the cursor shape correctly
  */
-void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
+static void mac_adjusttermcursor(WindowPtr window, Point mouse,
+                                RgnHandle cursrgn)
+{
     Session *s;
     ControlHandle control;
     short part;
@@ -385,7 +405,7 @@ void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
 #endif
 
     SetPort((GrafPtr)GetWindowPort(window));
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
     GlobalToLocal(&mouse);
     part = FindControl(mouse, window, &control);
     if (control == s->scrollbar) {
@@ -428,17 +448,19 @@ void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
 #define DisableItem DisableMenuItem
 #define EnableItem EnableMenuItem
 #endif
-void mac_adjusttermmenus(WindowPtr window) {
+static void mac_adjusttermmenus(WindowPtr window)
+{
     Session *s;
     MenuHandle menu;
 #if !TARGET_API_MAC_CARBON
     long offset;
 #endif
 
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
     menu = GetMenuHandle(mFile);
     DisableItem(menu, iSave); /* XXX enable if modified */
     EnableItem(menu, iSaveAs);
+    EnableItem(menu, iChange);
     EnableItem(menu, iDuplicate);
     menu = GetMenuHandle(mEdit);
     EnableItem(menu, 0);
@@ -458,12 +480,16 @@ void mac_adjusttermmenus(WindowPtr window) {
        EnableItem(menu, iPaste);
     DisableItem(menu, iClear);
     EnableItem(menu, iSelectAll);
+    menu = GetMenuHandle(mWindow);
+    EnableItem(menu, 0);
+    EnableItem(menu, iShowEventLog);
 }
 
-void mac_menuterm(WindowPtr window, short menu, short item) {
+static void mac_menuterm(WindowPtr window, short menu, short item)
+{
     Session *s;
 
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
     switch (menu) {
       case mEdit:
        switch (item) {
@@ -474,17 +500,26 @@ void mac_menuterm(WindowPtr window, short menu, short item) {
            term_do_paste(s->term);
            break;
        }
+       break;
+      case mWindow:
+       switch(item) {
+         case iShowEventLog:
+           mac_showeventlog(s);
+           break;
+       }
+       break;
     }
 }
            
-void mac_clickterm(WindowPtr window, EventRecord *event) {
+static void mac_clickterm(WindowPtr window, EventRecord *event)
+{
     Session *s;
     Point mouse;
     ControlHandle control;
     int part;
     static ControlActionUPP mac_scrolltracker_upp = NULL;
 
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
     SetPort((GrafPtr)GetWindowPort(window));
     mouse = event->where;
     GlobalToLocal(&mouse);
@@ -510,7 +545,8 @@ void mac_clickterm(WindowPtr window, EventRecord *event) {
     }
 }
 
-static void text_click(Session *s, EventRecord *event) {
+static void text_click(Session *s, EventRecord *event)
+{
     Point localwhere;
     int row, col;
     static UInt32 lastwhen = 0;
@@ -586,7 +622,7 @@ void write_clip(void *cookie, wchar_t *data, int len, int must_deselect)
        if (data[i] == 0x2028)
            data[i] = 0x000d;
 
-    mactextbuf = smalloc(len); /* XXX DBCS */
+    mactextbuf = snewn(len, char); /* XXX DBCS */
     if (s->uni_to_font != NULL) {
        err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
                                       (UniChar *)data,
@@ -621,7 +657,8 @@ void write_clip(void *cookie, wchar_t *data, int len, int must_deselect)
 #endif
 }
 
-void get_clip(void *frontend, wchar_t **p, int *lenp) {
+void get_clip(void *frontend, wchar_t **p, int *lenp)
+{
 #if TARGET_API_MAC_CARBON
     *lenp = 0;
 #else
@@ -658,7 +695,7 @@ void get_clip(void *frontend, wchar_t **p, int *lenp) {
            texth = NewHandle(0);
            textlen = GetScrap(texth, kScrapFlavorTypeText, &offset);
            HLock(texth);
-           data = smalloc(textlen * 2);
+           data = snewn(textlen, wchar_t);
            /* XXX should use 'styl' scrap if it's there. */
            if (mac_gestalts.encvvers != 0 &&
                UpgradeScriptInfoToTextEncoding(smSystemScript,
@@ -701,13 +738,14 @@ void get_clip(void *frontend, wchar_t **p, int *lenp) {
 #endif
 }
 
-static pascal void mac_scrolltracker(ControlHandle control, short part) {
+static pascal void mac_scrolltracker(ControlHandle control, short part)
+{
     Session *s;
 
 #if TARGET_API_MAC_CARBON
-    s = (Session *)GetWRefCon(GetControlOwner(control));
+    s = mac_windowsession(GetControlOwner(control));
 #else
-    s = (Session *)GetWRefCon((*control)->contrlOwner);
+    s = mac_windowsession((*control)->contrlOwner);
 #endif
     switch (part) {
       case kControlUpButtonPart:
@@ -725,8 +763,9 @@ static pascal void mac_scrolltracker(ControlHandle control, short part) {
     }
 }
 
-void mac_keyterm(WindowPtr window, EventRecord *event) {
-    Session *s = (Session *)GetWRefCon(window);
+static void mac_keyterm(WindowPtr window, EventRecord *event)
+{
+    Session *s = mac_windowsession(window);
     Key_Sym keysym = PK_NULL;
     unsigned int mods = 0, flags = PKF_NUMLOCK;
     UniChar utxt[1];
@@ -885,7 +924,8 @@ static struct {
     char oldmsg[20];
 } growterm_state;
 
-void mac_growterm(WindowPtr window, EventRecord *event) {
+static void mac_growterm(WindowPtr window, EventRecord *event)
+{
     Rect limits;
     long grow_result;
     int newrows, newcols;
@@ -896,7 +936,7 @@ void mac_growterm(WindowPtr window, EventRecord *event) {
     FontInfo fi;
 #endif
 
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
 
 #if !TARGET_API_MAC_CARBON
     draghooksave = LMGetDragHook();
@@ -935,6 +975,8 @@ void mac_growterm(WindowPtr window, EventRecord *event) {
        newcols = (LoWord(grow_result) - 15) / s->font_width;
        mac_adjustsize(s, newrows, newcols);
        term_size(s->term, newrows, newcols, s->cfg.savelines);
+       s->cfg.height=s->term->rows;
+       s->cfg.width=s->term->cols;
     }
 }
 
@@ -970,30 +1012,46 @@ static pascal void mac_growtermdraghook(void)
 
 void mac_closeterm(WindowPtr window)
 {
-    Session *s = (Session *)GetWRefCon(window);
+    int alertret;
+    Session *s = mac_windowsession(window);
+
+    if (s->cfg.warn_on_close && !s->session_closed) {
+       ParamText("\pAre you sure you want to close this session?",
+                 NULL, NULL, NULL);
+       alertret=CautionAlert(wQuestion, NULL);
+       if (alertret == 2) {
+           /* Cancel */
+           return;
+       }
+    }
 
-    /* XXX warn on close */
     HideWindow(s->window);
     *s->prev = s->next;
     s->next->prev = s->prev;
-    ldisc_free(s->ldisc);
-    s->back->free(s->backhandle);
+    if (s->ldisc)
+       ldisc_free(s->ldisc);
+    if (s->back)
+       s->back->free(s->backhandle);
     log_free(s->logctx);
     if (s->uni_to_font != NULL)
        DisposeUnicodeToTextInfo(&s->uni_to_font);
     term_free(s->term);
+    mac_freeeventlog(s);
+    sfree((WinInfo *)GetWRefCon(s->window));
     DisposeWindow(s->window);
     DisposePalette(s->palette);
     sfree(s);
 }
 
-void mac_activateterm(WindowPtr window, Boolean active) {
+static void mac_activateterm(WindowPtr window, EventRecord *event)
+{
     Session *s;
+    Boolean active = (event->modifiers & activeFlag) != 0;
 
-    s = (Session *)GetWRefCon(window);
-    s->term->has_focus = active;
+    s = mac_windowsession(window);
+    term_set_focus(s->term, active);
     term_update(s->term);
-    if (active)
+    if (active && s->cfg.scrollbar)
        ShowControl(s->scrollbar);
     else {
        if (HAVE_COLOR_QD())
@@ -1005,14 +1063,15 @@ void mac_activateterm(WindowPtr window, Boolean active) {
     mac_drawgrowicon(s);
 }
 
-void mac_updateterm(WindowPtr window) {
+static void mac_updateterm(WindowPtr window)
+{
     Session *s;
     Rect bbox;
 #if TARGET_API_MAC_CARBON
     RgnHandle visrgn;
 #endif
 
-    s = (Session *)GetWRefCon(window);
+    s = mac_windowsession(window);
     SetPort((GrafPtr)GetWindowPort(window));
     BeginUpdate(window);
     pre_paint(s);
@@ -1047,7 +1106,8 @@ void mac_updateterm(WindowPtr window) {
     EndUpdate(window);
 }
 
-static void mac_drawgrowicon(Session *s) {
+static void mac_drawgrowicon(Session *s)
+{
     Rect clip;
     RgnHandle savergn;
 
@@ -1085,8 +1145,9 @@ struct do_text_args {
  *
  * x and y are text row and column (zero-based)
  */
-void do_text(Context ctx, int x, int y, char *text, int len,
-            unsigned long attr, int lattr) {
+static void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
+                     unsigned long attr, int lattr)
+{
     Session *s = ctx;
     int style;
     struct do_text_args a;
@@ -1095,9 +1156,8 @@ void do_text(Context ctx, int x, int y, char *text, int len,
     RgnHandle visrgn;
 #endif
     char mactextbuf[1024];
-    UniChar unitextbuf[1024];
     wchar_t *unitextptr;
-    int i, fontwidth;
+    int fontwidth;
     ByteCount iread, olen;
     OSStatus err;
     static DeviceLoopDrawingUPP do_text_for_device_upp = NULL;
@@ -1130,20 +1190,16 @@ void do_text(Context ctx, int x, int y, char *text, int len,
        return;
 #endif
 
-    /* Unpack Unicode from the mad format we get passed */
-    for (i = 0; i < len; i++)
-       unitextbuf[i] = (unsigned char)text[i] | (attr & CSET_MASK);
-
     if (s->uni_to_font != NULL) {
        err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
-                                      unitextbuf, kUnicodeUseFallbacksMask,
+                                      text, kUnicodeUseFallbacksMask,
                                       0, NULL, NULL, NULL,
                                       1024, &iread, &olen, mactextbuf);
        if (err != noErr && err != kTECUsedFallbacksStatus)
            olen = 0;
     } else  if (s->font_charset != CS_NONE) {
        /* XXX this is bogus if wchar_t and UniChar are different sizes. */
-       unitextptr = (wchar_t *)unitextbuf;
+       unitextptr = (wchar_t *)text;
        olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
                                    s->font_charset, NULL, ".", 1);
     } else
@@ -1212,8 +1268,27 @@ void do_text(Context ctx, int x, int y, char *text, int len,
 #endif
 }
 
+/*
+ * Wrapper that handles combining characters.
+ */
+void do_text(Context ctx, int x, int y, wchar_t *text, int len,
+            unsigned long attr, int lattr)
+{
+    if (attr & TATTR_COMBINING) {
+       unsigned long a = 0;
+       attr &= ~TATTR_COMBINING;
+       while (len--) {
+           do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
+           text++;
+           a = TATTR_COMBINING;
+       }
+    } else
+       do_text_internal(ctx, x, y, text, len, attr, lattr);
+}
+
 static pascal void do_text_for_device(short depth, short devflags,
-                                     GDHandle device, long cookie) {
+                                     GDHandle device, long cookie)
+{
     struct do_text_args *a = (struct do_text_args *)cookie;
     int bgcolour, fgcolour, bright, reverse, tmp;
 #if TARGET_API_MAC_CARBON
@@ -1231,9 +1306,7 @@ static pascal void do_text_for_device(short depth, short devflags,
     if (HAVE_COLOR_QD()) {
        if (depth > 2) {
            fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
-           fgcolour = (fgcolour & 0xF) * 2 + (fgcolour & 0x10 ? 1 : 0);
            bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
-           bgcolour = (bgcolour & 0xF) * 2 + (bgcolour & 0x10 ? 1 : 0);
        } else {
            /*
             * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
@@ -1248,7 +1321,8 @@ static pascal void do_text_for_device(short depth, short devflags,
            bgcolour = tmp;
        }
        if (bright && depth > 2)
-           fgcolour |= 1;
+           if (fgcolour < 16) fgcolour |=8;
+           else if (fgcolour >= 256) fgcolour |=1;
        if ((a->attr & TATTR_ACTCURS) && depth > 1) {
            fgcolour = CURSOR_FG;
            bgcolour = CURSOR_BG;
@@ -1266,7 +1340,8 @@ static pascal void do_text_for_device(short depth, short devflags,
        }
     }
 
-    EraseRect(&a->textrect);
+    if (!(a->attr & TATTR_COMBINING))
+       EraseRect(&a->textrect);
     switch (a->lattr & LATTR_MODE) {
       case LATTR_NORM:
       case LATTR_WIDE:
@@ -1300,7 +1375,7 @@ static pascal void do_text_for_device(short depth, short devflags,
     }
 }
 
-void do_cursor(Context ctx, int x, int y, char *text, int len,
+void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
             unsigned long attr, int lattr)
 {
 
@@ -1311,7 +1386,8 @@ void do_cursor(Context ctx, int x, int y, char *text, int len,
  * Call from the terminal emulator to get its graphics context.
  * Should probably be called start_redraw or something.
  */
-void pre_paint(Session *s) {
+void pre_paint(Session *s)
+{
     GDHandle gdh;
     Rect myrect, tmprect;
 #if TARGET_API_MAC_CARBON
@@ -1357,21 +1433,24 @@ void pre_paint(Session *s) {
                                (s->cfg.bold_colour ? ATTR_BOLD : 0));
 }
 
-Context get_ctx(void *frontend) {
+Context get_ctx(void *frontend)
+{
     Session *s = frontend;
 
     pre_paint(s);
     return s;
 }
 
-void free_ctx(Context ctx) {
+void free_ctx(Context ctx)
+{
 
 }
 
 /*
  * Presumably this does something in Windows
  */
-void post_paint(Session *s) {
+void post_paint(Session *s)
+{
 
 }
 
@@ -1382,7 +1461,8 @@ void post_paint(Session *s) {
  * start is the line number of the top of the display
  * page is the length of the displayed page
  */
-void set_sbar(void *frontend, int total, int start, int page) {
+void set_sbar(void *frontend, int total, int start, int page)
+{
     Session *s = frontend;
 
     /* We don't redraw until we've set everything up, to avoid glitches */
@@ -1438,7 +1518,8 @@ void set_icon(void *frontend, char *icon) {
 /*
  * Set the window title
  */
-void set_title(void *frontend, char *title) {
+void set_title(void *frontend, char *title)
+{
     Session *s = frontend;
     Str255 mactitle;
 
@@ -1447,6 +1528,14 @@ void set_title(void *frontend, char *title) {
 }
 
 /*
+ * Used by backend to indicate busy-ness
+ */
+void set_busy_status(void *frontend, int status)
+{
+    /* FIXME do something */
+}
+
+/*
  * set or clear the "raw mouse message" mode
  */
 void set_raw_mouse_mode(void *frontend, int activate)
@@ -1460,9 +1549,24 @@ void set_raw_mouse_mode(void *frontend, int activate)
 /*
  * Resize the window at the emulator's request
  */
-void request_resize(void *frontend, int w, int h) {
+void request_resize(void *frontend, int w, int h)
+{
     Session *s = frontend;
+    RgnHandle grayrgn;
+    Rect graybox;
+    int wlim, hlim;
 
+    /* Arbitrarily clip to the size of the desktop. */
+    grayrgn = GetGrayRgn();
+#if TARGET_API_MAC_CARBON
+    GetRegionBounds(grayrgn, &graybox);
+#else
+    graybox = (*grayrgn)->rgnBBox;
+#endif
+    wlim = (graybox.right - graybox.left) / s->font_width;
+    hlim = (graybox.bottom - graybox.top) / s->font_height;
+    if (w > wlim) w = wlim;
+    if (h > hlim) h = hlim;
     term_size(s->term, h, w, s->cfg.savelines);
     mac_initfont(s);
 }
@@ -1614,48 +1718,59 @@ static void real_palette_set(Session *s, int n, int r, int g, int b)
 /*
  * Set the logical palette.  Called by the terminal emulator.
  */
-void palette_set(void *frontend, int n, int r, int g, int b) {
+void palette_set(void *frontend, int n, int r, int g, int b)
+{
     Session *s = frontend;
-    static const int first[21] = {
-       0, 2, 4, 6, 8, 10, 12, 14,
-       1, 3, 5, 7, 9, 11, 13, 15,
-       16, 17, 18, 20, 21
-    };
     
     if (!HAVE_COLOR_QD())
        return;
-    real_palette_set(s, first[n], r, g, b);
-    if (first[n] == 18)
-       real_palette_set(s, first[n]+1, r, g, b);
-    if (first[n] == DEFAULT_BG)
-       mac_adjustwinbg(s);
+    real_palette_set(s, n, r, g, b);
+    if (n == DEFAULT_BG)
+       mac_adjustwinbg(s);
+
     ActivatePalette(s->window);
 }
 
 /*
  * Reset to the default palette
  */
-void palette_reset(void *frontend) {
+void palette_reset(void *frontend)
+{
     Session *s = frontend;
     /* This maps colour indices in cfg to those used in our palette. */
     static const int ww[] = {
-       6, 7, 8, 9, 10, 11, 12, 13,
-        14, 15, 16, 17, 18, 19, 20, 21,
-       0, 1, 2, 3, 4, 5
+       256, 257, 258, 259, 260, 261,
+       0, 8, 1, 9, 2, 10, 3, 11,
+       4, 12, 5, 13, 6, 14, 7, 15
     };
+
     int i;
 
     if (!HAVE_COLOR_QD())
        return;
 
-    assert(lenof(ww) == NCOLOURS);
-
-    for (i = 0; i < NCOLOURS; i++) {
-       real_palette_set(s, i,
-                        s->cfg.colours[ww[i]][0],
-                        s->cfg.colours[ww[i]][1],
-                        s->cfg.colours[ww[i]][2]);
+    for (i = 0; i < 22; i++) {
+        int w = ww[i];
+        real_palette_set(s,w,
+                        s->cfg.colours[i][0],
+                        s->cfg.colours[i][1],
+                        s->cfg.colours[i][2]);
     }
+    for (i = 0; i < 240; i++) {
+       if (i < 216) {
+           int r = i / 36, g = (i / 6) % 6, b = i % 6;
+           real_palette_set(s,i+16,
+                            r * 0x33,
+                            g * 0x33,
+                            b * 0x33);
+       } else {
+           int shade = i - 216;
+           shade = (shade + 1) * 0xFF / (240 - 216 + 1);
+           real_palette_set(s,i+16,shade,shade,shade);
+       }
+    }
+
+
     mac_adjustwinbg(s);
     ActivatePalette(s->window);
     /* Palette Manager will generate update events as required. */
@@ -1665,7 +1780,8 @@ void palette_reset(void *frontend) {
  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
  * for backward.)
  */
-void do_scroll(Context ctx, int topline, int botline, int lines) {
+void do_scroll(Context ctx, int topline, int botline, int lines)
+{
     Session *s = ctx;
     Rect r;
     RgnHandle scrollrgn = NewRgn();
@@ -1724,16 +1840,17 @@ void do_scroll(Context ctx, int topline, int botline, int lines) {
     DisposeRgn(update);
 }
 
-void logevent(void *frontend, char *str) {
-
-    fprintf(stderr, "%s\n", str);
-}
-
 /* Dummy routine, only required in plink. */
 void ldisc_update(void *frontend, int echo, int edit)
 {
 }
 
+char *get_ttymode(void *frontend, const char *mode)
+{
+    Session *s = frontend;
+    return term_get_ttymode(s->term, mode);
+}
+
 /*
  * Mac PuTTY doesn't support printing yet.
  */
@@ -1766,13 +1883,27 @@ void frontend_keypress(void *handle)
  * Ask whether to wipe a session log file before writing to it.
  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
  */
-int askappend(void *frontend, Filename filename)
+int askappend(void *frontend, Filename filename,
+             void (*callback)(void *ctx, int result), void *ctx)
 {
 
     /* FIXME: not implemented yet. */
     return 2;
 }
 
+int from_backend(void *frontend, int is_stderr, const char *data, int len)
+{
+    Session *s = frontend;
+
+    return term_data(s->term, is_stderr, data, len);
+}
+
+int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
+{
+    Session *s = p->frontend;
+    return term_get_userpass_input(s->term, p, in, inlen);
+}
+
 /*
  * Emacs magic:
  * Local Variables: