Add a mechanism for determining which charset to use for a given Mac OS font,
[u/mdw/putty] / mac / macterm.c
index 73ce742..2e1a406 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: macterm.c,v 1.3 2002/11/19 23:59:27 ben Exp $ */
+/* $Id: macterm.c,v 1.30 2003/01/01 19:51:13 ben Exp $ */
 /*
  * Copyright (c) 1999 Simon Tatham
  * Copyright (c) 1999, 2002 Ben Harris
@@ -35,6 +35,7 @@
 #include <ControlDefinitions.h>
 #include <Fonts.h>
 #include <Gestalt.h>
+#include <LowMem.h>
 #include <MacMemory.h>
 #include <MacWindows.h>
 #include <MixedMode.h>
 #include <Scrap.h>
 #include <Script.h>
 #include <Sound.h>
+#include <StandardFile.h>
+#include <TextCommon.h>
 #include <Threads.h>
 #include <ToolUtils.h>
+#include <UnicodeConverter.h>
 
 #include <assert.h>
 #include <limits.h>
@@ -56,7 +60,9 @@
 
 #include "macresid.h"
 #include "putty.h"
+#include "charset.h"
 #include "mac.h"
+#include "storage.h"
 #include "terminal.h"
 
 #define NCOLOURS (lenof(((Config *)0)->colours))
                            (y) / s->font_height)
 
 static void mac_initfont(Session *);
+static pascal OSStatus uni_to_font_fallback(UniChar *, ByteCount, ByteCount *,
+                                           TextPtr, ByteCount, ByteCount *,
+                                           LogicalAddress *,
+                                           ConstUnicodeMappingPtr);
 static void mac_initpalette(Session *);
 static void mac_adjustwinbg(Session *);
 static void mac_adjustsize(Session *, int, int);
 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 pascal void mac_set_attr_mask(short, short, GDHandle, long);
 static int mac_keytrans(Session *, EventRecord *, unsigned char *);
 static void text_click(Session *, EventRecord *);
 
@@ -94,13 +104,9 @@ static RoutineDescriptor mac_scrolltracker_upp =
 static RoutineDescriptor do_text_for_device_upp =
     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
                             (ProcPtr)do_text_for_device);
-static RoutineDescriptor mac_set_attr_mask_upp =
-    BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
-                            (ProcPtr)mac_set_attr_mask);
 #else /* not TARGET_RT_MAC_CFM */
 #define mac_scrolltracker_upp  mac_scrolltracker
 #define do_text_for_device_upp do_text_for_device
-#define mac_set_attr_mask_upp  mac_set_attr_mask
 #endif /* not TARGET_RT_MAC_CFM */
 
 static void inbuf_putc(Session *s, int c) {
@@ -116,7 +122,7 @@ static void inbuf_putstr(Session *s, const char *c) {
 
 static void display_resource(Session *s, unsigned long type, short id) {
     Handle h;
-    int len, i;
+    int len;
     char *t;
 
     h = GetResource(type, id);
@@ -132,19 +138,36 @@ static void display_resource(Session *s, unsigned long type, short id) {
     DisposeHandle(h);
 }
        
-
-void mac_newsession(void) {
+void mac_opensession(void) {
     Session *s;
-    UInt32 starttime;
-    char msg[128];
-    OSErr err;
+    StandardFileReply sfr;
+    static const OSType sftypes[] = { 'Sess', 0, 0, 0 };
+    void *sesshandle;
 
-    /* This should obviously be initialised by other means */
     s = smalloc(sizeof(*s));
     memset(s, 0, sizeof(*s));
-    do_defaults(NULL, &s->cfg);
+
+    StandardGetFile(NULL, 1, sftypes, &sfr);
+    if (!sfr.sfGood) goto fail;
+
+    sesshandle = open_settings_r_fsp(&sfr.sfFile);
+    if (sesshandle == NULL) goto fail;
+    load_open_settings(sesshandle, TRUE, &s->cfg);
+    close_settings_r(sesshandle);
     s->back = &loop_backend;
-       
+    mac_startsession(s);
+    return;
+
+  fail:
+    sfree(s);
+    return;
+}
+
+void mac_startsession(Session *s)
+{
+    UInt32 starttime;
+    char msg[128];
+
     /* XXX: Own storage management? */
     if (HAVE_COLOR_QD())
        s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
@@ -152,7 +175,7 @@ void mac_newsession(void) {
        s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
     SetWRefCon(s->window, (long)s);
     s->scrollbar = GetNewControl(cVScroll, s->window);
-    s->term = term_init(s);
+    s->term = term_init(&s->cfg, s);
 
     s->logctx = log_init(s);
     term_provide_logctx(s->term, s->logctx);
@@ -165,12 +188,11 @@ void mac_newsession(void) {
     mac_adjustsize(s, s->cfg.height, s->cfg.width);
     term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
 
-    s->ldisc = ldisc_create(s->term, s->back, s->backhandle, s);
+    s->ldisc = ldisc_create(&s->cfg, s->term, s->back, s->backhandle, s);
     ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
 
     mac_initfont(s);
     mac_initpalette(s);
-    s->attr_mask = ATTR_MASK;
     if (HAVE_COLOR_QD()) {
        /* Set to FALSE to not get palette updates in the background. */
        SetPalette(s->window, s->palette, TRUE); 
@@ -184,10 +206,13 @@ void mac_newsession(void) {
     term_out(s->term);
 }
 
+static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
+
 static void mac_initfont(Session *s) {
     Str255 macfont;
     FontInfo fi;
+    TextEncoding enc;
+
     SetPort(s->window);
     macfont[0] = sprintf((char *)&macfont[1], "%s", s->cfg.font);
     GetFNum(macfont, &s->fontnum);
@@ -204,9 +229,56 @@ static void mac_initfont(Session *s) {
        s->font_boldadjust = s->font_width - CharWidth('W');
     } else
        s->font_boldadjust = 0;
+
+    if (s->uni_to_font != NULL)
+       DisposeUnicodeToTextInfo(&s->uni_to_font);
+    if (mac_gestalts.encvvers != 0 &&
+       UpgradeScriptInfoToTextEncoding(kTextScriptDontCare,
+                                       kTextLanguageDontCare,
+                                       kTextRegionDontCare, macfont,
+                                       &enc) == noErr &&
+       CreateUnicodeToTextInfoByEncoding(enc, &s->uni_to_font) == noErr) {
+       if (uni_to_font_fallback_upp == NULL)
+           uni_to_font_fallback_upp =
+               NewUnicodeToTextFallbackProc(&uni_to_font_fallback);
+       if (SetFallbackUnicodeToText(s->uni_to_font,
+           uni_to_font_fallback_upp, 
+           kUnicodeFallbackCustomOnly | kUnicodeFallbackInterruptSafeMask,
+           NULL) != noErr) {
+           DisposeUnicodeToTextInfo(&s->uni_to_font);
+           s->uni_to_font = NULL;
+       }
+    } else {
+       s->uni_to_font = NULL;
+       s->font_charset =
+           charset_from_macenc(FontToScript(s->fontnum),
+                               GetScriptManagerVariable(smRegionCode),
+                               mac_gestalts.sysvers, s->cfg.font);
+    }
+
     mac_adjustsize(s, s->term->rows, s->term->cols);
 }
 
+static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
+    ByteCount ilen, ByteCount *iusedp, TextPtr obuf, ByteCount olen,
+    ByteCount *ousedp, LogicalAddress *cookie, ConstUnicodeMappingPtr mapping)
+{
+
+    if (olen < 1)
+       return kTECOutputBufferFullStatus;
+    /*
+     * What I'd _like_ to do here is to somehow generate the
+     * missing-character glyph that every font is required to have.
+     * Unfortunately (and somewhat surprisingly), I can't find any way
+     * to actually ask for it explicitly.  Bah.
+     */
+    *obuf = '.';
+    *iusedp = ilen;
+    *ousedp = 1;
+    return noErr;
+}
+
+
 /*
  * To be called whenever the window size changes.
  * rows and cols should be desired values.
@@ -223,18 +295,20 @@ static void mac_adjustsize(Session *s, int newrows, int newcols) {
     MoveControl(s->scrollbar, winwidth - 15, -1);
     SizeControl(s->scrollbar, 16, winheight - 13);
     ShowControl(s->scrollbar);
+    mac_drawgrowicon(s);
 }
 
 static void mac_initpalette(Session *s) {
-    int i;
 
+    if (!HAVE_COLOR_QD())
+       return;
     /*
      * Most colours should be inhibited on 2bpp displays.
      * Palette manager documentation suggests inhibiting all tolerant colours
      * on greyscale displays.
      */
-#define PM_NORMAL      pmTolerant | pmInhibitC2 |                      \
-                       pmInhibitG2 | pmInhibitG4 | pmInhibitG8 | pmInhibitC2
+#define PM_NORMAL      ( pmTolerant | pmInhibitC2 |                    \
+                         pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
 #define PM_TOLERANCE   0x2000
     s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
     if (s->palette == NULL)
@@ -246,7 +320,7 @@ static void mac_initpalette(Session *s) {
                  PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
     SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
                  PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
-    SetEntryUsage(s->palette, CURSOR_FG,
+    SetEntryUsage(s->palette, CURSOR_BG,
                  PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
     palette_reset(s);
 }
@@ -554,7 +628,11 @@ void mac_keyterm(WindowPtr window, EventRecord *event) {
 
     s = (Session *)GetWRefCon(window);
     len = mac_keytrans(s, event, buf);
-    s->back->send(s, (char *)buf, len);
+    ldisc_send(s->ldisc, (char *)buf, len, 1);
+    ObscureCursor();
+    term_seen_key_event(s->term);
+    term_out(s->term);
+    term_update(s->term);
 }
 
 static int mac_keytrans(Session *s, EventRecord *event,
@@ -708,15 +786,51 @@ void request_paste(void *frontend)
     term_do_paste(s->term);
 }
 
+static struct {
+    Rect msgrect;
+    Point msgorigin;
+    Point startmouse;
+    Session *s;
+    char oldmsg[20];
+} growterm_state;
+
 void mac_growterm(WindowPtr window, EventRecord *event) {
     Rect limits;
     long grow_result;
     int newrows, newcols;
     Session *s;
+    DragGrayRgnUPP draghooksave;
+    GrafPtr portsave;
+    FontInfo fi;
 
     s = (Session *)GetWRefCon(window);
+
+    draghooksave = LMGetDragHook();
+    growterm_state.oldmsg[0] = '\0';
+    growterm_state.startmouse = event->where;
+    growterm_state.s = s;
+    GetPort(&portsave);
+    SetPort(s->window);
+    BackColor(whiteColor);
+    ForeColor(blackColor);
+    TextFont(systemFont);
+    TextFace(0);
+    TextSize(12);
+    GetFontInfo(&fi);
+    SetRect(&growterm_state.msgrect, 0, 0,
+           StringWidth("\p99999x99999") + 4, fi.ascent + fi.descent + 4);
+    SetPt(&growterm_state.msgorigin, 2, fi.ascent + 2);
+    LMSetDragHook(NewDragGrayRgnUPP(mac_growtermdraghook));
+
     SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
     grow_result = GrowWindow(window, event->where, &limits);
+
+    DisposeDragGrayRgnUPP(LMGetDragHook());
+    LMSetDragHook(draghooksave);
+    InvalRect(&growterm_state.msgrect);
+
+    SetPort(portsave);
+
     if (grow_result != 0) {
        newrows = HiWord(grow_result) / s->font_height;
        newcols = (LoWord(grow_result) - 15) / s->font_width;
@@ -725,11 +839,40 @@ void mac_growterm(WindowPtr window, EventRecord *event) {
     }
 }
 
+static pascal void mac_growtermdraghook(void)
+{
+    Session *s = growterm_state.s;
+    GrafPtr portsave;
+    Point mouse;
+    char buf[20];
+    int newrows, newcols;
+    
+    GetMouse(&mouse);
+    newrows = (mouse.v - growterm_state.startmouse.v) / s->font_height +
+       s->term->rows;
+    if (newrows < 1) newrows = 1;
+    newcols = (mouse.h - growterm_state.startmouse.h) / s->font_width +
+       s->term->cols;
+    if (newcols < 1) newcols = 1;
+    sprintf(buf, "%dx%d", newcols, newrows);
+    if (strcmp(buf, growterm_state.oldmsg) == 0)
+       return;
+    strcpy(growterm_state.oldmsg, buf);
+    c2pstr(buf);
+
+    GetPort(&portsave);
+    SetPort(growterm_state.s->window);
+    EraseRect(&growterm_state.msgrect);
+    MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
+    DrawString((StringPtr)buf);
+    SetPort(portsave);
+}
+
 void mac_activateterm(WindowPtr window, Boolean active) {
     Session *s;
 
     s = (Session *)GetWRefCon(window);
-    s->has_focus = active;
+    s->term->has_focus = active;
     term_update(s->term);
     if (active)
        ShowControl(s->scrollbar);
@@ -773,25 +916,31 @@ void mac_updateterm(WindowPtr window) {
 
 static void mac_drawgrowicon(Session *s) {
     Rect clip;
+    RgnHandle savergn;
 
     SetPort(s->window);
-    /* Stop DrawGrowIcon giving us space for a horizontal scrollbar */
-    SetRect(&clip, s->window->portRect.right - 15, SHRT_MIN,
-           SHRT_MAX, SHRT_MAX);
+    /*
+     * Stop DrawGrowIcon giving us space for a horizontal scrollbar
+     * See Tech Note TB575 for details.
+     */
+    clip = s->window->portRect;
+    clip.left = clip.right - 15;
+    savergn = NewRgn();
+    GetClip(savergn);
     ClipRect(&clip);
     DrawGrowIcon(s->window);
-    clip.left = SHRT_MIN;
-    ClipRect(&clip);
+    SetClip(savergn);
+    DisposeRgn(savergn);
 }    
 
 struct do_text_args {
     Session *s;
     Rect textrect;
-    Rect leadrect;
     char *text;
     int len;
     unsigned long attr;
     int lattr;
+    Point numer, denom;
 };
 
 /*
@@ -805,6 +954,14 @@ void do_text(Context ctx, int x, int y, char *text, int len,
     int style = 0;
     struct do_text_args a;
     RgnHandle textrgn;
+    char mactextbuf[1024];
+    UniChar unitextbuf[1024];
+    wchar_t *unitextptr;
+    int i;
+    ByteCount iread, olen;
+    OSStatus err;
+
+    assert(len <= 1024);
 
     SetPort(s->window);
     
@@ -816,17 +973,32 @@ void do_text(Context ctx, int x, int y, char *text, int len,
     if (!RectInRgn(&a.textrect, s->window->visRgn))
        return;
 
+    /* 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,
+                                      0, NULL, NULL, NULL,
+                                      1024, &iread, &olen, mactextbuf);
+       if (err != noErr && err != kTECUsedFallbacksStatus)
+           /* XXX Should handle this more sensibly */
+           return;
+    } else  if (s->font_charset != CS_NONE) {
+       /* XXX this is bogus if wchar_t and UniChar are different sizes. */
+       unitextptr = (wchar_t *)unitextbuf;
+       olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
+                                   s->font_charset, NULL, ".", 1);
+    } else
+       return;
+
     a.s = s;
-    a.text = text;
-    a.len = len;
+    a.text = mactextbuf;
+    a.len = olen;
     a.attr = attr;
     a.lattr = lattr;
-    if (s->font_leading > 0)
-       SetRect(&a.leadrect,
-               a.textrect.left, a.textrect.bottom - s->font_leading,
-               a.textrect.right, a.textrect.bottom);
-    else
-       SetRect(&a.leadrect, 0, 0, 0, 0);
+    a.numer.h = a.numer.v = a.denom.h = a.denom.v = 1;
     SetPort(s->window);
     TextFont(s->fontnum);
     if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
@@ -835,7 +1007,7 @@ void do_text(Context ctx, int x, int y, char *text, int len,
        style |= underline;
     TextFace(style);
     TextSize(s->cfg.fontheight);
-    SetFractEnable(FALSE); /* We want characters on pixel boundaries */
+    TextMode(srcOr);
     if (HAVE_COLOR_QD())
        if (style & bold) {
            SpaceExtra(s->font_boldadjust << 16);
@@ -858,58 +1030,60 @@ void do_text(Context ctx, int x, int y, char *text, int len,
 static pascal void do_text_for_device(short depth, short devflags,
                                      GDHandle device, long cookie) {
     struct do_text_args *a;
-    int bgcolour, fgcolour, bright;
+    int bgcolour, fgcolour, bright, reverse, tmp;
 
     a = (struct do_text_args *)cookie;
 
     bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
+    reverse = a->attr & ATTR_REVERSE;
 
-    TextMode(a->attr & ATTR_REVERSE ? notSrcCopy : srcCopy);
+    if (depth == 1 && (a->attr & TATTR_ACTCURS))
+       reverse = !reverse;
 
-    switch (depth) {
-      case 1:
-       /* XXX This should be done with a _little_ more configurability */
-       ForeColor(whiteColor);
-       BackColor(blackColor);
-       if (a->attr & TATTR_ACTCURS)
-           TextMode(a->attr & ATTR_REVERSE ? srcCopy : notSrcCopy);
-       break;
-      case 2:
-       if (a->attr & TATTR_ACTCURS) {
-           PmForeColor(CURSOR_FG);
-           PmBackColor(CURSOR_BG);
-           TextMode(srcCopy);
+    if (HAVE_COLOR_QD()) {
+       if (depth > 2) {
+           fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
+           bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
        } else {
-           PmForeColor(bright ? DEFAULT_FG_BOLD : DEFAULT_FG);
-           PmBackColor(DEFAULT_BG);
+           /*
+            * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
+            * boldens the background, because that's all we can do.
+            */
+           fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
+           bgcolour = DEFAULT_BG;
        }
-       break;
-      default:
-       if (a->attr & TATTR_ACTCURS) {
+       if (reverse) {
+           tmp = fgcolour;
+           fgcolour = bgcolour;
+           bgcolour = tmp;
+       }
+       if (bright && depth > 2)
+           fgcolour++;
+       if ((a->attr & TATTR_ACTCURS) && depth > 1) {
            fgcolour = CURSOR_FG;
            bgcolour = CURSOR_BG;
-           TextMode(srcCopy);
-       } else {
-           fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
-           bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
-           if (bright)
-               if (a->attr & ATTR_REVERSE)
-                   bgcolour++;
-               else
-                   fgcolour++;
        }
        PmForeColor(fgcolour);
        PmBackColor(bgcolour);
-       break;
+    } else { /* No Color Quickdraw */
+       /* XXX This should be done with a _little_ more configurability */
+       if (reverse) {
+           ForeColor(blackColor);
+           BackColor(whiteColor);
+       } else {
+           ForeColor(whiteColor);
+           BackColor(blackColor);
+       }
     }
 
-    if (a->attr & ATTR_REVERSE)
-       PaintRect(&a->leadrect);
-    else
-       EraseRect(&a->leadrect);
+    EraseRect(&a->textrect);
     MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
     /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
-    DrawText(a->text, 0, a->len);
+    if (a->s->window->grafProcs != NULL)
+       InvokeQDTextUPP(a->len, a->text, a->numer, a->denom,
+                       a->s->window->grafProcs->textProc);
+    else
+       StdText(a->len, a->text, a->numer, a->denom);
 
     if (a->attr & TATTR_PASCURS) {
        PenNormal();
@@ -937,12 +1111,39 @@ void do_cursor(Context ctx, int x, int y, char *text, int len,
  * Should probably be called start_redraw or something.
  */
 void pre_paint(Session *s) {
+    GDHandle gdh;
+    Rect myrect, tmprect;
 
-    s->attr_mask = ATTR_INVALID;
-    if (HAVE_COLOR_QD())
-       DeviceLoop(s->window->visRgn, &mac_set_attr_mask_upp, (long)s, 0);
-    else
-       mac_set_attr_mask(1, 0, NULL, (long)s);
+    if (HAVE_COLOR_QD()) {
+       s->term->attr_mask = 0;
+       SetPort(s->window);
+       myrect = (*s->window->visRgn)->rgnBBox;
+       LocalToGlobal((Point *)&myrect.top);
+       LocalToGlobal((Point *)&myrect.bottom);
+       for (gdh = GetDeviceList();
+            gdh != NULL;
+            gdh = GetNextDevice(gdh)) {
+           if (TestDeviceAttribute(gdh, screenDevice) &&
+               TestDeviceAttribute(gdh, screenActive) &&
+               SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
+               switch ((*(*gdh)->gdPMap)->pixelSize) {
+                 case 1:
+                   if (s->cfg.bold_colour)
+                       s->term->attr_mask |= ~(ATTR_COLOURS |
+                           (s->cfg.bold_colour ? ATTR_BOLD : 0));
+                   break;
+                 case 2:
+                   s->term->attr_mask |= ~ATTR_COLOURS;
+                   break;
+                 default:
+                   s->term->attr_mask = ~0;
+                   return; /* No point checking more screens. */
+               }
+           }
+       }
+    } else
+       s->term->attr_mask = ~(ATTR_COLOURS |
+                               (s->cfg.bold_colour ? ATTR_BOLD : 0));
 }
 
 Context get_ctx(void *frontend) {
@@ -956,26 +1157,6 @@ void free_ctx(Context ctx) {
 
 }
 
-static pascal void mac_set_attr_mask(short depth, short devflags,
-                                    GDHandle device, long cookie) {
-
-    Session *s = (Session *)cookie;
-
-    switch (depth) {
-      default:
-       s->attr_mask |= ATTR_FGMASK | ATTR_BGMASK;
-       /* FALLTHROUGH */
-      case 2:
-       s->attr_mask |= ATTR_BOLD;
-       /* FALLTHROUGH */
-      case 1:
-       s->attr_mask |= ATTR_UNDER | ATTR_REVERSE | TATTR_ACTCURS |
-           TATTR_PASCURS | ATTR_ASCII | ATTR_GBCHR | ATTR_LINEDRW |
-           (s->cfg.bold_colour ? 0 : ATTR_BOLD); 
-       break;
-    }
-}
-
 /*
  * Presumably this does something in Windows
  */
@@ -1203,8 +1384,6 @@ static void real_palette_set(Session *s, int n, int r, int g, int b)
     col.red   = r * 0x0101;
     col.green = g * 0x0101;
     col.blue  = b * 0x0101;
-    fprintf(stderr, "p%d <- (0x%x, 0x%x, 0x%x)\n", n, col.red, col.green,
-           col.blue);
     SetEntryColor(s->palette, n, &col);
 }
 
@@ -1265,20 +1444,46 @@ void palette_reset(void *frontend) {
 void do_scroll(void *frontend, int topline, int botline, int lines) {
     Session *s = frontend;
     Rect r;
-    RgnHandle update;
+    RgnHandle scrollrgn = NewRgn();
+    RgnHandle movedupdate = NewRgn();
+    RgnHandle update = NewRgn();
+    Point g2l = { 0, 0 };
 
-    /* FIXME: This is seriously broken on Original QuickDraw.  No idea why. */
     SetPort(s->window);
+
+    /*
+     * Work out the part of the update region that will scrolled by
+     * this operation.
+     */
+    if (lines > 0)
+       SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
+                  s->term->cols * s->font_width,
+                  (botline + 1) * s->font_height);
+    else
+       SetRectRgn(scrollrgn, 0, topline * s->font_height,
+                  s->term->cols * s->font_width,
+                  (botline - lines + 1) * s->font_height);
+    CopyRgn(((WindowPeek)s->window)->updateRgn, movedupdate);
+    GlobalToLocal(&g2l);
+    OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
+    SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
+    ValidRgn(movedupdate);
+    OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
+
+    PenNormal();
     if (HAVE_COLOR_QD())
        PmBackColor(DEFAULT_BG);
     else
-       BackColor(blackColor);
-    update = NewRgn();
+       BackColor(blackColor); /* XXX make configurable */
     SetRect(&r, 0, topline * s->font_height,
            s->term->cols * s->font_width, (botline + 1) * s->font_height);
     ScrollRect(&r, 0, - lines * s->font_height, update);
-    /* XXX: move update region? */
+
     InvalRgn(update);
+    InvalRgn(movedupdate);
+
+    DisposeRgn(scrollrgn);
+    DisposeRgn(movedupdate);
     DisposeRgn(update);
 }