SkTextBlob

Initial implementation.

R=bungeman@google.com, jbroman@chromium.org, mtklein@google.com, reed@google.com, robertphillips@google.com

Author: fmalita@chromium.org

Review URL: https://codereview.chromium.org/473633002
diff --git a/gm/textblob.cpp b/gm/textblob.cpp
new file mode 100644
index 0000000..e7a0a1d
--- /dev/null
+++ b/gm/textblob.cpp
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "gm.h"
+
+#include "SkCanvas.h"
+#include "SkPoint.h"
+#include "SkTextBlob.h"
+#include "SkTDArray.h"
+
+namespace  {
+
+enum Pos {
+    kDefault_Pos = 0,
+    kScalar_Pos  = 1,
+    kPoint_Pos   = 2,
+};
+
+const struct BlobCfg {
+    unsigned count;
+    Pos      pos;
+    SkScalar scale;
+} blobConfigs[][3][3] = {
+    {
+        { { 1024, kDefault_Pos, 1 }, { 0, kDefault_Pos, 0 }, { 0, kDefault_Pos, 0 } },
+        { { 1024,  kScalar_Pos, 1 }, { 0,  kScalar_Pos, 0 }, { 0,  kScalar_Pos, 0 } },
+        { { 1024,   kPoint_Pos, 1 }, { 0,   kPoint_Pos, 0 }, { 0,   kPoint_Pos, 0 } },
+    },
+    {
+        { { 4, kDefault_Pos, 1},     { 4, kDefault_Pos, 1},  { 4, kDefault_Pos, 1} },
+        { { 4,  kScalar_Pos, 1},     { 4,  kScalar_Pos, 1},  { 4,  kScalar_Pos, 1} },
+        { { 4,   kPoint_Pos, 1},     { 4,   kPoint_Pos, 1},  { 4,   kPoint_Pos, 1} },
+    },
+
+    {
+        { { 4, kDefault_Pos, 1},     { 4, kDefault_Pos, 1},  { 4,  kScalar_Pos, 1} },
+        { { 4,  kScalar_Pos, 1},     { 4,  kScalar_Pos, 1},  { 4,   kPoint_Pos, 1} },
+        { { 4,   kPoint_Pos, 1},     { 4,   kPoint_Pos, 1},  { 4, kDefault_Pos, 1} },
+    },
+
+    {
+        { { 4, kDefault_Pos, 1},     { 4,  kScalar_Pos, 1},  { 4,   kPoint_Pos, 1} },
+        { { 4,  kScalar_Pos, 1},     { 4,   kPoint_Pos, 1},  { 4, kDefault_Pos, 1} },
+        { { 4,   kPoint_Pos, 1},     { 4, kDefault_Pos, 1},  { 4,  kScalar_Pos, 1} },
+    },
+};
+
+const SkScalar kFontSize = 16;
+}
+
+class TextBlobGM : public skiagm::GM {
+public:
+    TextBlobGM(const char* txt) {
+        SkPaint p;
+        size_t txtLen = strlen(txt);
+        int glyphCount = p.textToGlyphs(txt, txtLen, NULL);
+
+        fGlyphs.append(glyphCount);
+        p.textToGlyphs(txt, txtLen, fGlyphs.begin());
+    }
+
+protected:
+    virtual SkString onShortName() SK_OVERRIDE {
+        return SkString("textblob");
+    }
+
+    virtual SkISize onISize() SK_OVERRIDE {
+        return SkISize::Make(640, 480);
+    }
+
+    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
+        for (unsigned b = 0; b < SK_ARRAY_COUNT(blobConfigs); ++b) {
+            SkAutoTUnref<const SkTextBlob> blob(makeBlob(b));
+
+            SkPaint p;
+            p.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
+            p.setTextSize(kFontSize);
+            p.setAntiAlias(true);
+            p.setSubpixelText(true);
+
+            SkPoint offset = SkPoint::Make(SkIntToScalar(10 + 300 * (b % 2)),
+                                           SkIntToScalar(20 + 150 * (b / 2)));
+
+            canvas->drawTextBlob(blob, offset.x(), offset.y(), p);
+
+            p.setColor(SK_ColorBLUE);
+            p.setStyle(SkPaint::kStroke_Style);
+            SkRect box = blob->bounds();
+            box.offset(offset);
+            canvas->drawRect(box, p);
+
+        }
+    }
+
+private:
+    const SkTextBlob* makeBlob(unsigned blobIndex) {
+        SkTextBlobBuilder builder;
+
+        SkPaint font;
+        font.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
+
+        for (unsigned l = 0; l < SK_ARRAY_COUNT(blobConfigs[blobIndex]); ++l) {
+            unsigned currentGlyph = 0;
+
+            for (unsigned c = 0; c < SK_ARRAY_COUNT(blobConfigs[blobIndex][l]); ++c) {
+                const BlobCfg* cfg = &blobConfigs[blobIndex][l][c];
+                unsigned count = cfg->count;
+
+                if (count > fGlyphs.count() - currentGlyph) {
+                    count = fGlyphs.count() - currentGlyph;
+                }
+                if (0 == count) {
+                    break;
+                }
+
+                font.setTextSize(kFontSize * cfg->scale);
+                const SkScalar advanceX = font.getTextSize() * 0.85f;
+                const SkScalar advanceY = font.getTextSize() * 1.5f;
+
+                SkPoint offset = SkPoint::Make(currentGlyph * advanceX + c * advanceX,
+                                               advanceY * l);
+                switch (cfg->pos) {
+                case kDefault_Pos: {
+                    const SkTextBlobBuilder::RunBuffer& buf = builder.allocRun(font, count,
+                                                                               offset.x(),
+                                                                               offset.y());
+                    memcpy(buf.glyphs, fGlyphs.begin() + currentGlyph, count * sizeof(uint16_t));
+                } break;
+                case kScalar_Pos: {
+                    const SkTextBlobBuilder::RunBuffer& buf = builder.allocRunPosH(font, count,
+                                                                                   offset.y());
+                    SkTDArray<SkScalar> pos;
+                    for (unsigned i = 0; i < count; ++i) {
+                        *pos.append() = offset.x() + i * advanceX;
+                    }
+
+                    memcpy(buf.glyphs, fGlyphs.begin() + currentGlyph, count * sizeof(uint16_t));
+                    memcpy(buf.pos, pos.begin(), count * sizeof(SkScalar));
+                } break;
+                case kPoint_Pos: {
+                    const SkTextBlobBuilder::RunBuffer& buf = builder.allocRunPos(font, count);
+
+                    SkTDArray<SkScalar> pos;
+                    for (unsigned i = 0; i < count; ++i) {
+                        *pos.append() = offset.x() + i * advanceX;
+                        *pos.append() = offset.y() + i * (advanceY / count);
+                    }
+
+                    memcpy(buf.glyphs, fGlyphs.begin() + currentGlyph, count * sizeof(uint16_t));
+                    memcpy(buf.pos, pos.begin(), count * sizeof(SkScalar) * 2);
+                } break;
+                default:
+                    SkFAIL("unhandled pos value");
+                }
+
+                currentGlyph += count;
+            }
+        }
+
+        return builder.build();
+    }
+
+    SkTDArray<uint16_t> fGlyphs;
+
+    typedef skiagm::GM INHERITED;
+};
+
+DEF_GM( return SkNEW_ARGS(TextBlobGM, ("hamburgefons")); )
diff --git a/gyp/core.gypi b/gyp/core.gypi
index 057691c..a188c33 100644
--- a/gyp/core.gypi
+++ b/gyp/core.gypi
@@ -196,6 +196,7 @@
         '<(skia_src_path)/core/SkStrokeRec.cpp',
         '<(skia_src_path)/core/SkStrokerPriv.cpp',
         '<(skia_src_path)/core/SkStrokerPriv.h',
+        '<(skia_src_path)/core/SkTextBlob.cpp',
         '<(skia_src_path)/core/SkTextFormatParams.h',
         '<(skia_src_path)/core/SkTextMapStateProc.h',
         '<(skia_src_path)/core/SkTileGrid.cpp',
@@ -305,6 +306,7 @@
         '<(skia_include_path)/core/SkTRegistry.h',
         '<(skia_include_path)/core/SkTSearch.h',
         '<(skia_include_path)/core/SkTemplates.h',
+        '<(skia_include_path)/core/SkTextBlob.h',
         '<(skia_include_path)/core/SkThread.h',
         '<(skia_include_path)/core/SkTime.h',
         '<(skia_include_path)/core/SkTLazy.h',
diff --git a/gyp/gmslides.gypi b/gyp/gmslides.gypi
index c1f527f..f4003e3 100644
--- a/gyp/gmslides.gypi
+++ b/gyp/gmslides.gypi
@@ -173,6 +173,7 @@
         '../gm/testimagefilters.cpp',
         '../gm/texdata.cpp',
         '../gm/variedtext.cpp',
+        '../gm/textblob.cpp',
         '../gm/texturedomaineffect.cpp',
         '../gm/thinrects.cpp',
         '../gm/thinstrokedrects.cpp',
diff --git a/include/core/SkCanvas.h b/include/core/SkCanvas.h
index ceb85f6..a619904 100644
--- a/include/core/SkCanvas.h
+++ b/include/core/SkCanvas.h
@@ -33,6 +33,7 @@
 class SkRRect;
 class SkSurface;
 class SkSurface_Base;
+class SkTextBlob;
 class GrContext;
 class GrRenderTarget;
 
@@ -956,6 +957,14 @@
                                 const SkPath& path, const SkMatrix* matrix,
                                 const SkPaint& paint);
 
+    /** Draw the text blob, offset by (x,y), using the specified paint.
+        @param blob     The text blob to be drawn
+        @param x        The x-offset of the text being drawn
+        @param y        The y-offset of the text being drawn
+        @param paint    The paint used for the text (e.g. color, size, style)
+    */
+    void drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint);
+
     /** PRIVATE / EXPERIMENTAL -- do not call
         Perform back-end analysis/optimization of a picture. This may attach
         optimization data to the picture which can be used by a later
@@ -1220,6 +1229,9 @@
                                   const SkPath& path, const SkMatrix* matrix,
                                   const SkPaint& paint);
 
+    virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
+                                const SkPaint& paint);
+
     virtual void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
                            const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
 
diff --git a/include/core/SkTextBlob.h b/include/core/SkTextBlob.h
new file mode 100644
index 0000000..c78fb24
--- /dev/null
+++ b/include/core/SkTextBlob.h
@@ -0,0 +1,179 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkTextBlob_DEFINED
+#define SkTextBlob_DEFINED
+
+#include "SkPaint.h"
+#include "SkRefCnt.h"
+#include "SkTArray.h"
+#include "SkTDArray.h"
+
+/** \class SkTextBlob
+
+    SkTextBlob combines multiple text runs into an immutable, ref-counted structure.
+*/
+class SkTextBlob : public SkRefCnt {
+public:
+    /**
+     *  Returns the blob bounding box.
+     */
+    const SkRect& bounds() const { return fBounds; }
+
+    /**
+     *  Return a non-zero, unique value representing the text blob.
+     */
+    uint32_t uniqueID() const;
+
+private:
+    enum GlyphPositioning {
+        kDefault_Positioning      = 0, // Default glyph advances -- zero scalars per glyph.
+        kHorizontal_Positioning   = 1, // Horizontal positioning -- one scalar per glyph.
+        kFull_Positioning         = 2  // Point positioning -- two scalars per glyph.
+    };
+
+    class RunIterator {
+    public:
+        RunIterator(const SkTextBlob* blob);
+
+        bool done() const;
+        void next();
+
+        uint32_t glyphCount() const;
+        const uint16_t* glyphs() const;
+        const SkScalar* pos() const;
+        const SkPoint& offset() const;
+        const SkPaint& font() const;
+        GlyphPositioning positioning() const;
+
+    private:
+        const SkTextBlob* fBlob;
+        int               fIndex;
+    };
+
+    // A run is a sequence of glyphs sharing the same font metrics and positioning mode.
+    struct Run {
+        uint32_t         count;
+        uint32_t         glyphStart; // index into fGlyphBuffer
+        uint32_t         posStart;   // index into fPosBuffer
+        SkPoint          offset;     // run offset (unsued for fully positioned glyphs)
+        SkPaint          font;
+        GlyphPositioning positioning;
+    };
+
+    SkTextBlob(uint16_t* glyphs, SkScalar* pos, const SkTArray<Run>* runs, const SkRect& bounds);
+
+    friend class SkCanvas;
+    friend class SkTextBlobBuilder;
+
+    const SkAutoTMalloc<uint16_t>       fGlyphBuffer;
+    const SkAutoTMalloc<SkScalar>       fPosBuffer;
+
+    // SkTArray required here for run font destruction.
+    SkAutoTDelete<const SkTArray<Run> > fRuns;
+    const SkRect                        fBounds;
+
+    mutable uint32_t                    fUniqueID;
+
+    typedef SkRefCnt INHERITED;
+};
+
+/** \class SkTextBlobBuilder
+
+    Helper class for constructing SkTextBlobs.
+ */
+class SkTextBlobBuilder {
+public:
+    /**
+     *  @param runs The number of runs to be added, if known. This is a storage hint and
+     *              not a limit.
+     */
+    SkTextBlobBuilder(unsigned runs = 0);
+
+    ~SkTextBlobBuilder();
+
+    /**
+     *  Returns an immutable SkTextBlob for the current runs/glyphs. The builder is reset and
+     *  can be reused.
+     */
+    const SkTextBlob* build();
+
+    /**
+     *  Glyph and position buffers associated with a run.
+     *
+     *  A run is a sequence of glyphs sharing the same font metrics and positioning mode.
+     */
+    struct RunBuffer {
+        uint16_t* glyphs;
+        SkScalar* pos;
+    };
+
+    /**
+     *  Allocates a new default-positioned run and returns its writable glyph buffer
+     *  for direct manipulation.
+     *
+     *  @param font    The font to be used for this run.
+     *  @param count   Number of glyphs.
+     *  @param x,y     Position within the blob.
+     *  @param bounds  Optional run bounding box. If known in advance (!= NULL), it will
+     *                 be used when computing the blob bounds, to avoid re-measuring.
+     *
+     *  @return        A writable glyph buffer, valid until the next allocRun() or
+     *                 build() call. The buffer is guaranteed to hold @count@ glyphs.
+     */
+    const RunBuffer& allocRun(const SkPaint& font, int count, SkScalar x, SkScalar y,
+                              const SkRect* bounds = NULL);
+
+    /**
+     *  Allocates a new horizontally-positioned run and returns its writable glyph and position
+     *  buffers for direct manipulation.
+     *
+     *  @param font    The font to be used for this run.
+     *  @param count   Number of glyphs.
+     *  @param y       Vertical offset within the blob.
+     *  @param bounds  Optional run bounding box. If known in advance (!= NULL), it will
+     *                 be used when computing the blob bounds, to avoid re-measuring.
+     *
+     *  @return        Writable glyph and position buffers, valid until the next allocRun()
+     *                 or build() call. The buffers are guaranteed to hold @count@ elements.
+     */
+    const RunBuffer& allocRunPosH(const SkPaint& font, int count, SkScalar y,
+                                  const SkRect* bounds = NULL);
+
+    /**
+     *  Allocates a new fully-positioned run and returns its writable glyph and position
+     *  buffers for direct manipulation.
+     *
+     *  @param font   The font to be used for this run.
+     *  @param count  Number of glyphs.
+     *  @param bounds Optional run bounding box. If known in advance (!= NULL), it will
+     *                be used when computing the blob bounds, to avoid re-measuring.
+     *
+     *  @return       Writable glyph and position buffers, valid until the next allocRun()
+     *                or build() call. The glyph buffer and position buffer are
+     *                guaranteed to hold @count@ and 2 * @count@ elements, respectively.
+     */
+    const RunBuffer& allocRunPos(const SkPaint& font, int count, const SkRect* bounds = NULL);
+
+private:
+    void allocInternal(const SkPaint& font, SkTextBlob::GlyphPositioning positioning,
+                       int count, SkPoint offset, const SkRect* bounds);
+    void ensureRun(const SkPaint& font, SkTextBlob::GlyphPositioning positioning,
+                   const SkPoint& offset);
+    void updateDeferredBounds();
+
+    SkTDArray<uint16_t>        fGlyphBuffer;
+    SkTDArray<SkScalar>        fPosBuffer;
+    SkTArray<SkTextBlob::Run>* fRuns;
+
+    SkRect                     fBounds;
+    bool                       fDeferredBounds;
+
+    RunBuffer                  fCurrentRunBuffer;
+};
+
+#endif // SkTextBlob_DEFINED
diff --git a/src/core/SkCanvas.cpp b/src/core/SkCanvas.cpp
index 104dfc4..5a694db 100644
--- a/src/core/SkCanvas.cpp
+++ b/src/core/SkCanvas.cpp
@@ -22,6 +22,7 @@
 #include "SkSmallAllocator.h"
 #include "SkSurface_Base.h"
 #include "SkTemplates.h"
+#include "SkTextBlob.h"
 #include "SkTextFormatParams.h"
 #include "SkTLazy.h"
 #include "SkUtils.h"
@@ -2215,6 +2216,43 @@
     LOOPER_END
 }
 
+void SkCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
+                              const SkPaint& paint) {
+    SkASSERT(blob);
+
+    // FIXME: dispatch to the device instead
+
+    if (x || y) {
+        this->translate(x, y);
+    }
+
+    SkTextBlob::RunIterator it(blob);
+    while (!it.done()) {
+        size_t textLen = it.glyphCount() * sizeof(uint16_t);
+        const SkPoint& offset = it.offset();
+
+        switch (it.positioning()) {
+        case SkTextBlob::kDefault_Positioning:
+            this->drawText(it.glyphs(), textLen, offset.x(), offset.y(), paint);
+            break;
+        case SkTextBlob::kHorizontal_Positioning:
+            this->drawPosTextH(it.glyphs(), textLen, it.pos(), offset.y(), paint);
+            break;
+        case SkTextBlob::kFull_Positioning:
+            this->drawPosText(it.glyphs(), textLen, (const SkPoint*)it.pos(), paint);
+            break;
+        default:
+            SkFAIL("unhandled positioning mode");
+        }
+
+        it.next();
+    }
+
+    if (x || y) {
+        this->translate(-x, -y);
+    }
+}
+
 // These will become non-virtual, so they always call the (virtual) onDraw... method
 void SkCanvas::drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
                         const SkPaint& paint) {
@@ -2232,6 +2270,12 @@
                               const SkMatrix* matrix, const SkPaint& paint) {
     this->onDrawTextOnPath(text, byteLength, path, matrix, paint);
 }
+void SkCanvas::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
+                            const SkPaint& paint) {
+    if (NULL != blob) {
+        this->onDrawTextBlob(blob, x, y, paint);
+    }
+}
 
 void SkCanvas::drawVertices(VertexMode vmode, int vertexCount,
                             const SkPoint verts[], const SkPoint texs[],
diff --git a/src/core/SkRecordDraw.cpp b/src/core/SkRecordDraw.cpp
index a1c148a..aa3e8de 100644
--- a/src/core/SkRecordDraw.cpp
+++ b/src/core/SkRecordDraw.cpp
@@ -89,6 +89,7 @@
 DRAW(DrawRect, drawRect(r.rect, r.paint));
 DRAW(DrawSprite, drawSprite(shallow_copy(r.bitmap), r.left, r.top, r.paint));
 DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
+DRAW(DrawTextBlob, drawTextBlob(r.blob, r.x, r.y, r.paint));
 DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));
 DRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,
                                 r.xmode.get(), r.indices, r.indexCount, r.paint));
diff --git a/src/core/SkRecorder.cpp b/src/core/SkRecorder.cpp
index a2ef00b..2e14c3e 100644
--- a/src/core/SkRecorder.cpp
+++ b/src/core/SkRecorder.cpp
@@ -187,6 +187,11 @@
            this->copy(matrix));
 }
 
+void SkRecorder::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
+                                const SkPaint& paint) {
+    APPEND(DrawTextBlob, delay_copy(paint), blob, x, y);
+}
+
 void SkRecorder::onDrawPicture(const SkPicture* pic, const SkMatrix* matrix, const SkPaint* paint) {
     APPEND(DrawPicture, this->copy(paint), pic, this->copy(matrix));
 }
diff --git a/src/core/SkRecorder.h b/src/core/SkRecorder.h
index 1373f8a..8b1430d 100644
--- a/src/core/SkRecorder.h
+++ b/src/core/SkRecorder.h
@@ -89,6 +89,10 @@
                           const SkPath& path,
                           const SkMatrix* matrix,
                           const SkPaint& paint) SK_OVERRIDE;
+    void onDrawTextBlob(const SkTextBlob* blob,
+                        SkScalar x,
+                        SkScalar y,
+                        const SkPaint& paint);
     void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
                      const SkPoint texCoords[4], SkXfermode* xmode,
                      const SkPaint& paint) SK_OVERRIDE;
diff --git a/src/core/SkRecords.h b/src/core/SkRecords.h
index 6ec6e9c..6baabe6 100644
--- a/src/core/SkRecords.h
+++ b/src/core/SkRecords.h
@@ -10,23 +10,22 @@
 
 #include "SkCanvas.h"
 #include "SkPicture.h"
-
-class SkPictureBox {
-public:
-    SkPictureBox(const SkPicture* obj) : fObj(SkRef(obj)) {}
-    ~SkPictureBox() { fObj->unref(); }
-
-    operator const SkPicture*() const { return fObj; }
-
-private:
-    SkPictureBox(const SkPictureBox&);
-    SkPictureBox& operator=(const SkPictureBox&);
-
-    const SkPicture* fObj;
-};
+#include "SkTextBlob.h"
 
 namespace SkRecords {
 
+template <typename T>
+class RefBox : SkNoncopyable {
+public:
+    RefBox(const T* obj) : fObj(SkRef(obj)) {}
+    ~RefBox() { fObj->unref(); }
+
+    operator const T*() const { return fObj; }
+
+private:
+    const T* fObj;
+};
+
 // A list of all the types of canvas calls we can record.
 // Each of these is reified into a struct below.
 //
@@ -68,6 +67,7 @@
     M(DrawRRect)                                                    \
     M(DrawRect)                                                     \
     M(DrawSprite)                                                   \
+    M(DrawTextBlob)                                                     \
     M(DrawVertices)
 
 // Defines SkRecords::Type, an enum of all record types.
@@ -231,7 +231,7 @@
 RECORD1(DrawPaint, SkPaint, paint);
 RECORD2(DrawPath, SkPaint, paint, SkPath, path);
 //RECORD2(DrawPatch, SkPaint, paint, SkPatch, patch);
-RECORD3(DrawPicture, Optional<SkPaint>, paint, SkPictureBox, picture, Optional<SkMatrix>, matrix);
+RECORD3(DrawPicture, Optional<SkPaint>, paint, RefBox<SkPicture>, picture, Optional<SkMatrix>, matrix);
 RECORD4(DrawPoints, SkPaint, paint, SkCanvas::PointMode, mode, size_t, count, SkPoint*, pts);
 RECORD4(DrawPosText, SkPaint, paint,
                      PODArray<char>, text,
@@ -250,6 +250,10 @@
                   size_t, byteLength,
                   SkScalar, x,
                   SkScalar, y);
+RECORD4(DrawTextBlob, SkPaint, paint,
+                      RefBox<SkTextBlob>, blob,
+                      SkScalar, x,
+                      SkScalar, y);
 RECORD5(DrawTextOnPath, SkPaint, paint,
                         PODArray<char>, text,
                         size_t, byteLength,
diff --git a/src/core/SkTextBlob.cpp b/src/core/SkTextBlob.cpp
new file mode 100644
index 0000000..551d988
--- /dev/null
+++ b/src/core/SkTextBlob.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "SkTextBlob.h"
+
+SkTextBlob::SkTextBlob(uint16_t *glyphs, SkScalar *pos, const SkTArray<Run> *runs,
+                       const SkRect& bounds)
+    : fGlyphBuffer(glyphs)
+    , fPosBuffer(pos)
+    , fRuns(runs)
+    , fBounds(bounds) {
+}
+
+uint32_t SkTextBlob::uniqueID() const {
+    static int32_t  gTextBlobGenerationID; // = 0;
+
+    // loop in case our global wraps around, as we never want to return SK_InvalidGenID
+    while (SK_InvalidGenID == fUniqueID) {
+        fUniqueID = sk_atomic_inc(&gTextBlobGenerationID) + 1;
+    }
+
+    return fUniqueID;
+}
+
+SkTextBlob::RunIterator::RunIterator(const SkTextBlob* blob)
+    : fBlob(blob)
+    , fIndex(0) {
+    SkASSERT(NULL != blob);
+}
+
+bool SkTextBlob::RunIterator::done() const {
+    return NULL == fBlob->fRuns.get() || fIndex >= fBlob->fRuns->count();
+}
+
+void SkTextBlob::RunIterator::next() {
+    SkASSERT(!this->done());
+    fIndex++;
+}
+
+uint32_t SkTextBlob::RunIterator::glyphCount() const {
+    SkASSERT(!this->done());
+    return (*fBlob->fRuns)[fIndex].count;
+}
+
+const uint16_t* SkTextBlob::RunIterator::glyphs() const {
+    SkASSERT(!this->done());
+    return fBlob->fGlyphBuffer.get() + (*fBlob->fRuns)[fIndex].glyphStart;
+}
+
+const SkScalar* SkTextBlob::RunIterator::pos() const {
+    SkASSERT(!this->done());
+    return fBlob->fPosBuffer.get() + (*fBlob->fRuns)[fIndex].posStart;
+}
+
+const SkPoint& SkTextBlob::RunIterator::offset() const {
+    SkASSERT(!this->done());
+    return (*fBlob->fRuns)[fIndex].offset;
+}
+
+const SkPaint& SkTextBlob::RunIterator::font() const {
+    SkASSERT(!this->done());
+    return (*fBlob->fRuns)[fIndex].font;
+}
+
+SkTextBlob::GlyphPositioning SkTextBlob::RunIterator::positioning() const {
+    SkASSERT(!this->done());
+    return (*fBlob->fRuns)[fIndex].positioning;
+}
+
+SkTextBlobBuilder::SkTextBlobBuilder(unsigned runs)
+    : fRuns(NULL)
+    , fDeferredBounds(false) {
+
+    if (runs > 0) {
+        // if the number of runs is known, size our run storage accordingly.
+        fRuns = SkNEW(SkTArray<SkTextBlob::Run>(runs));
+    }
+    fBounds.setEmpty();
+}
+
+SkTextBlobBuilder::~SkTextBlobBuilder() {
+    // unused runs
+    SkDELETE(fRuns);
+}
+
+void SkTextBlobBuilder::updateDeferredBounds() {
+    SkASSERT(!fDeferredBounds || (NULL != fRuns && !fRuns->empty()));
+
+    if (!fDeferredBounds) {
+        return;
+    }
+
+    // FIXME: measure the current run & union bounds
+    fDeferredBounds = false;
+}
+
+void SkTextBlobBuilder::ensureRun(const SkPaint& font, SkTextBlob::GlyphPositioning pos,
+                                  const SkPoint& offset) {
+    SkASSERT(SkPaint::kGlyphID_TextEncoding == font.getTextEncoding());
+
+    if (NULL == fRuns) {
+        fRuns = SkNEW(SkTArray<SkTextBlob::Run>());
+    }
+
+    // we can merge same-font/same-positioning runs in the following cases:
+    //   * fully positioned run following another fully positioned run
+    //   * horizontally postioned run following another horizontally positioned run with the same
+    //     y-offset
+    if (!fRuns->empty()
+        && fRuns->back().positioning == pos
+        && fRuns->back().font == font
+        && (SkTextBlob::kFull_Positioning == fRuns->back().positioning
+            || (SkTextBlob::kHorizontal_Positioning == fRuns->back().positioning
+                && fRuns->back().offset.y() == offset.y()))){
+        return;
+    }
+
+    this->updateDeferredBounds();
+
+    // start a new run
+    SkTextBlob::Run& newRun = fRuns->push_back();
+    newRun.count = 0;
+    newRun.glyphStart = fGlyphBuffer.count();
+    newRun.posStart = fPosBuffer.count();
+    newRun.offset = offset;
+    newRun.font = font;
+    newRun.positioning = pos;
+}
+
+void SkTextBlobBuilder::allocInternal(const SkPaint &font,
+                                      SkTextBlob::GlyphPositioning positioning,
+                                      int count, SkPoint offset, const SkRect* bounds) {
+    SkASSERT(count > 0);
+
+    this->ensureRun(font, positioning, offset);
+
+    // SkTextBlob::GlyphPositioning values are directly mapped to scalars-per-glyph.
+    unsigned posScalarsPerGlyph = positioning;
+    SkASSERT(posScalarsPerGlyph <= 2);
+
+    fGlyphBuffer.append(count);
+    fPosBuffer.append(count * posScalarsPerGlyph);
+
+    SkASSERT(NULL != fRuns && !fRuns->empty());
+    SkTextBlob::Run& run = fRuns->back();
+
+    run.count += count;
+
+    // The current run might have been merged, so the start offset may point to prev run data.
+    // Start from the back (which always points to the end of the current run buffers) instead.
+    fCurrentRunBuffer.glyphs = fGlyphBuffer.isEmpty()
+            ? NULL : fGlyphBuffer.end() - count;
+    SkASSERT(NULL == fCurrentRunBuffer.glyphs || fCurrentRunBuffer.glyphs >= fGlyphBuffer.begin());
+    fCurrentRunBuffer.pos = fPosBuffer.isEmpty()
+            ? NULL : fPosBuffer.end() - count * posScalarsPerGlyph;
+    SkASSERT(NULL == fCurrentRunBuffer.pos || fCurrentRunBuffer.pos >= fPosBuffer.begin());
+
+    if (!fDeferredBounds) {
+        if (NULL != bounds) {
+            fBounds.join(*bounds);
+        } else {
+            fDeferredBounds = true;
+        }
+    }
+}
+
+const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRun(const SkPaint& font, int count,
+                                                                SkScalar x, SkScalar y,
+                                                                const SkRect* bounds) {
+    this->allocInternal(font, SkTextBlob::kDefault_Positioning, count, SkPoint::Make(x, y), bounds);
+
+    return fCurrentRunBuffer;
+}
+
+const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunPosH(const SkPaint& font, int count,
+                                                                    SkScalar y,
+                                                                    const SkRect* bounds) {
+    this->allocInternal(font, SkTextBlob::kHorizontal_Positioning, count, SkPoint::Make(0, y),
+                        bounds);
+
+    return fCurrentRunBuffer;
+}
+
+const SkTextBlobBuilder::RunBuffer& SkTextBlobBuilder::allocRunPos(const SkPaint& font, int count,
+                                                                   const SkRect *bounds) {
+    this->allocInternal(font, SkTextBlob::kFull_Positioning, count, SkPoint::Make(0, 0), bounds);
+
+    return fCurrentRunBuffer;
+}
+
+const SkTextBlob* SkTextBlobBuilder::build() {
+    const SkTextBlob* blob;
+
+    if (fGlyphBuffer.count() > 0) {
+        // we have some glyphs, construct a real blob
+        SkASSERT(NULL != fRuns && !fRuns->empty());
+
+        this->updateDeferredBounds();
+
+        // ownership of all buffers is transferred to the blob
+        blob = SkNEW_ARGS(SkTextBlob, (fGlyphBuffer.detach(),
+                                       fPosBuffer.detach(),
+                                       fRuns,
+                                       fBounds));
+        fRuns = NULL;
+        fBounds.setEmpty();
+    } else {
+        // empty blob
+        SkASSERT(NULL == fRuns || fRuns->empty());
+        SkASSERT(fBounds.isEmpty());
+
+        blob = SkNEW_ARGS(SkTextBlob, (NULL, NULL, NULL, SkRect::MakeEmpty()));
+    }
+
+    return blob;
+}
+