Add TextShaper API

TextShaper API provides a primitive text layout result, e.g. what glyph is used etc.

Here is the new APIs and its description

- PositionedGlyphs
This is a native instance backed object that gives layout information to developers.

- GlyphStyle
The glyph style is an object that holds the parameters that will be used for drawing.
This object is a subset of the Paint object for avoiding creating lots of Paint copy.

- TextShaper#shapeText
This does a text shaping and gives TextShaper.Result. This is a native backed primitive
shaping API.

- StyledTextShaper
This is a text shaper for a styled text. This will be the top-level developer facing
API for shaping text.

Bug: 168048923
Test: atest FontTest TextShaperTest StyledTextShaperTest
Change-Id: I2e91d1ef8503b25b28efc94da7de7cad49c4c1a9
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index 90d2537..d2f4562 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -334,6 +334,7 @@
         "jni/fonts/FontFamily.cpp",
         "jni/text/LineBreaker.cpp",
         "jni/text/MeasuredText.cpp",
+        "jni/text/TextShaper.cpp",
     ],
 
     header_libs: [ "android_graphics_jni_headers" ],
diff --git a/libs/hwui/apex/jni_runtime.cpp b/libs/hwui/apex/jni_runtime.cpp
index 12e2e81..f05c6aa 100644
--- a/libs/hwui/apex/jni_runtime.cpp
+++ b/libs/hwui/apex/jni_runtime.cpp
@@ -73,6 +73,7 @@
 extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
 extern int register_android_graphics_text_MeasuredText(JNIEnv* env);
 extern int register_android_graphics_text_LineBreaker(JNIEnv *env);
+extern int register_android_graphics_text_TextShaper(JNIEnv *env);
 
 extern int register_android_util_PathParser(JNIEnv* env);
 extern int register_android_view_DisplayListCanvas(JNIEnv* env);
@@ -137,6 +138,7 @@
     REG_JNI(register_android_graphics_pdf_PdfRenderer),
     REG_JNI(register_android_graphics_text_MeasuredText),
     REG_JNI(register_android_graphics_text_LineBreaker),
+    REG_JNI(register_android_graphics_text_TextShaper),
 
     REG_JNI(register_android_util_PathParser),
     REG_JNI(register_android_view_RenderNode),
diff --git a/libs/hwui/hwui/MinikinUtils.h b/libs/hwui/hwui/MinikinUtils.h
index 6cde9c5..a15803a 100644
--- a/libs/hwui/hwui/MinikinUtils.h
+++ b/libs/hwui/hwui/MinikinUtils.h
@@ -72,7 +72,7 @@
         size_t start = 0;
         size_t nGlyphs = layout.nGlyphs();
         for (size_t i = 0; i < nGlyphs; i++) {
-            const minikin::MinikinFont* nextFont = layout.getFont(i);
+            const minikin::MinikinFont* nextFont = layout.getFont(i)->typeface().get();
             if (i > 0 && nextFont != curFont) {
                 SkFont* skfont = &paint->getSkFont();
                 MinikinFontSkia::populateSkFont(skfont, curFont, layout.getFakery(start));
diff --git a/libs/hwui/jni/FontUtils.h b/libs/hwui/jni/FontUtils.h
index b36b4e6..f93a0da 100644
--- a/libs/hwui/jni/FontUtils.h
+++ b/libs/hwui/jni/FontUtils.h
@@ -38,6 +38,14 @@
   minikin::Font font;
 };
 
+// We assume FontWrapper's address is the same as underlying Font's address.
+// This assumption is used for looking up Java font object from native address.
+// The Font object can be created without Java's Font object but all Java's Font objects point to
+// the native FontWrapper. So when looking up Java object from minikin::Layout which gives us Font
+// address, we lookup Font Java object from Font address with assumption that it is the same as
+// FontWrapper address.
+static_assert(offsetof(FontWrapper, font) == 0);
+
 // Utility wrapper for java.util.List
 class ListHelper {
 public:
diff --git a/libs/hwui/jni/fonts/Font.cpp b/libs/hwui/jni/fonts/Font.cpp
index bcdb4f5..0eb4095 100644
--- a/libs/hwui/jni/fonts/Font.cpp
+++ b/libs/hwui/jni/fonts/Font.cpp
@@ -198,6 +198,59 @@
     return spacing;
 }
 
+// Critical Native
+static jlong Font_getFontInfo(CRITICAL_JNI_PARAMS_COMMA jlong fontHandle) {
+    FontWrapper* font = reinterpret_cast<FontWrapper*>(fontHandle);
+    MinikinFontSkia* minikinSkia = static_cast<MinikinFontSkia*>(font->font.typeface().get());
+
+    uint64_t result = font->font.style().weight();
+    result |= font->font.style().slant() == minikin::FontStyle::Slant::ITALIC ? 0x10000 : 0x00000;
+    result |= ((static_cast<uint64_t>(minikinSkia->GetFontIndex())) << 32);
+    result |= ((static_cast<uint64_t>(minikinSkia->GetAxes().size())) << 48);
+    return result;
+}
+
+// Critical Native
+static jlong Font_getAxisInfo(CRITICAL_JNI_PARAMS_COMMA jlong fontHandle, jint index) {
+    FontWrapper* font = reinterpret_cast<FontWrapper*>(fontHandle);
+    MinikinFontSkia* minikinSkia = static_cast<MinikinFontSkia*>(font->font.typeface().get());
+    const minikin::FontVariation& var = minikinSkia->GetAxes().at(index);
+    uint32_t floatBinary = *reinterpret_cast<const uint32_t*>(&var.value);
+    return (static_cast<uint64_t>(var.axisTag) << 32) | static_cast<uint64_t>(floatBinary);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+struct FontBufferWrapper {
+    FontBufferWrapper(const std::shared_ptr<minikin::MinikinFont>& font) : minikinFont(font) {}
+    // MinikinFont holds a shared pointer of SkTypeface which has reference to font data.
+    std::shared_ptr<minikin::MinikinFont> minikinFont;
+};
+
+static void unrefBuffer(jlong nativePtr) {
+    FontBufferWrapper* wrapper = reinterpret_cast<FontBufferWrapper*>(nativePtr);
+    delete wrapper;
+}
+
+// Critical Native
+static jlong FontBufferHelper_refFontBuffer(CRITICAL_JNI_PARAMS_COMMA jlong fontHandle) {
+    FontWrapper* font = reinterpret_cast<FontWrapper*>(fontHandle);
+    return reinterpret_cast<jlong>(new FontBufferWrapper(font->font.typeface()));
+}
+
+// Fast Native
+static jobject FontBufferHelper_wrapByteBuffer(JNIEnv* env, jobject, jlong nativePtr) {
+    FontBufferWrapper* wrapper = reinterpret_cast<FontBufferWrapper*>(nativePtr);
+    return env->NewDirectByteBuffer(
+        const_cast<void*>(wrapper->minikinFont->GetFontData()),
+        wrapper->minikinFont->GetFontSize());
+}
+
+// Critical Native
+static jlong FontBufferHelper_getReleaseFunc(CRITICAL_JNI_PARAMS) {
+    return reinterpret_cast<jlong>(unrefBuffer);
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 
 static const JNINativeMethod gFontBuilderMethods[] = {
@@ -211,13 +264,23 @@
 static const JNINativeMethod gFontMethods[] = {
     { "nGetGlyphBounds", "(JIJLandroid/graphics/RectF;)F", (void*) Font_getGlyphBounds },
     { "nGetFontMetrics", "(JJLandroid/graphics/Paint$FontMetrics;)F", (void*) Font_getFontMetrics },
+    { "nGetFontInfo", "(J)J", (void*) Font_getFontInfo },
+    { "nGetAxisInfo", "(JI)J", (void*) Font_getAxisInfo },
+};
+
+static const JNINativeMethod gFontBufferHelperMethods[] = {
+    { "nRefFontBuffer", "(J)J", (void*) FontBufferHelper_refFontBuffer },
+    { "nWrapByteBuffer", "(J)Ljava/nio/ByteBuffer;", (void*) FontBufferHelper_wrapByteBuffer },
+    { "nGetReleaseFunc", "()J", (void*) FontBufferHelper_getReleaseFunc },
 };
 
 int register_android_graphics_fonts_Font(JNIEnv* env) {
     return RegisterMethodsOrDie(env, "android/graphics/fonts/Font$Builder", gFontBuilderMethods,
             NELEM(gFontBuilderMethods)) +
             RegisterMethodsOrDie(env, "android/graphics/fonts/Font", gFontMethods,
-            NELEM(gFontMethods));
+            NELEM(gFontMethods)) +
+            RegisterMethodsOrDie(env, "android/graphics/fonts/NativeFontBufferHelper",
+            gFontBufferHelperMethods, NELEM(gFontBufferHelperMethods));
 }
 
 }
diff --git a/libs/hwui/jni/text/TextShaper.cpp b/libs/hwui/jni/text/TextShaper.cpp
new file mode 100644
index 0000000..9d9e91f
--- /dev/null
+++ b/libs/hwui/jni/text/TextShaper.cpp
@@ -0,0 +1,206 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#undef LOG_TAG
+#define LOG_TAG "TextShaper"
+
+#include "graphics_jni_helpers.h"
+#include <nativehelper/ScopedStringChars.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <set>
+#include <algorithm>
+
+#include "SkPaint.h"
+#include "SkTypeface.h"
+#include <hwui/MinikinSkia.h>
+#include <hwui/MinikinUtils.h>
+#include <hwui/Paint.h>
+#include <minikin/MinikinPaint.h>
+#include <minikin/MinikinFont.h>
+
+namespace android {
+
+struct LayoutWrapper {
+    LayoutWrapper(minikin::Layout&& layout, float ascent, float descent)
+        : layout(std::move(layout)), ascent(ascent), descent(descent)  {}
+    minikin::Layout layout;
+    float ascent;
+    float descent;
+};
+
+static void releaseLayout(jlong ptr) {
+    delete reinterpret_cast<LayoutWrapper*>(ptr);
+}
+
+static jlong shapeTextRun(const uint16_t* text, int textSize, int start, int count,
+    int contextStart, int contextCount, minikin::Bidi bidiFlags,
+    const Paint& paint, const Typeface* typeface) {
+
+    minikin::MinikinPaint minikinPaint = MinikinUtils::prepareMinikinPaint(&paint, typeface);
+
+    minikin::Layout layout = MinikinUtils::doLayout(&paint, bidiFlags, typeface,
+        text, textSize, start, count, contextStart, contextCount, nullptr);
+
+    std::set<const minikin::Font*> seenFonts;
+    float overallAscent = 0;
+    float overallDescent = 0;
+    for (int i = 0; i < layout.nGlyphs(); ++i) {
+        const minikin::Font* font = layout.getFont(i);
+        if (seenFonts.find(font) != seenFonts.end()) continue;
+        minikin::MinikinExtent extent = {};
+        font->typeface()->GetFontExtent(&extent, minikinPaint, layout.getFakery(i));
+        overallAscent = std::min(overallAscent, extent.ascent);
+        overallDescent = std::max(overallDescent, extent.descent);
+    }
+
+    std::unique_ptr<LayoutWrapper> ptr = std::make_unique<LayoutWrapper>(
+        std::move(layout), overallAscent, overallDescent
+    );
+
+    return reinterpret_cast<jlong>(ptr.release());
+}
+
+static jlong TextShaper_shapeTextRunChars(JNIEnv *env, jobject, jcharArray charArray,
+    jint start, jint count, jint contextStart, jint contextCount, jboolean isRtl,
+    jlong paintPtr) {
+    ScopedCharArrayRO text(env, charArray);
+    Paint* paint = reinterpret_cast<Paint*>(paintPtr);
+    const Typeface* typeface = paint->getAndroidTypeface();
+    const minikin::Bidi bidiFlags = isRtl ? minikin::Bidi::FORCE_RTL : minikin::Bidi::FORCE_LTR;
+    return shapeTextRun(
+        text.get(), text.size(),
+        start, count,
+        contextStart, contextCount,
+        bidiFlags,
+        *paint, typeface);
+
+}
+
+static jlong TextShaper_shapeTextRunString(JNIEnv *env, jobject, jstring string,
+    jint start, jint count, jint contextStart, jint contextCount, jboolean isRtl,
+    jlong paintPtr) {
+    ScopedStringChars text(env, string);
+    Paint* paint = reinterpret_cast<Paint*>(paintPtr);
+    const Typeface* typeface = paint->getAndroidTypeface();
+    const minikin::Bidi bidiFlags = isRtl ? minikin::Bidi::FORCE_RTL : minikin::Bidi::FORCE_LTR;
+    return shapeTextRun(
+        text.get(), text.size(),
+        start, count,
+        contextStart, contextCount,
+        bidiFlags,
+        *paint, typeface);
+}
+
+// CriticalNative
+static jint TextShaper_Result_getGlyphCount(CRITICAL_JNI_PARAMS_COMMA jlong ptr) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->layout.nGlyphs();
+}
+
+// CriticalNative
+static jfloat TextShaper_Result_getTotalAdvance(CRITICAL_JNI_PARAMS_COMMA jlong ptr) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->layout.getAdvance();
+}
+
+// CriticalNative
+static jfloat TextShaper_Result_getAscent(CRITICAL_JNI_PARAMS_COMMA jlong ptr) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->ascent;
+}
+
+// CriticalNative
+static jfloat TextShaper_Result_getDescent(CRITICAL_JNI_PARAMS_COMMA jlong ptr) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->descent;
+}
+
+// CriticalNative
+static jint TextShaper_Result_getGlyphId(CRITICAL_JNI_PARAMS_COMMA jlong ptr, jint i) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->layout.getGlyphId(i);
+}
+
+// CriticalNative
+static jfloat TextShaper_Result_getX(CRITICAL_JNI_PARAMS_COMMA jlong ptr, jint i) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->layout.getX(i);
+}
+
+// CriticalNative
+static jfloat TextShaper_Result_getY(CRITICAL_JNI_PARAMS_COMMA jlong ptr, jint i) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return layout->layout.getY(i);
+}
+
+// CriticalNative
+static jlong TextShaper_Result_getFont(CRITICAL_JNI_PARAMS_COMMA jlong ptr, jint i) {
+    const LayoutWrapper* layout = reinterpret_cast<LayoutWrapper*>(ptr);
+    return reinterpret_cast<jlong>(layout->layout.getFont(i));
+}
+
+// CriticalNative
+static jlong TextShaper_Result_nReleaseFunc(CRITICAL_JNI_PARAMS) {
+    return reinterpret_cast<jlong>(releaseLayout);
+}
+
+static const JNINativeMethod gMethods[] = {
+    // Fast Natives
+    {"nativeShapeTextRun", "("
+        "[C"  // text
+        "I"  // start
+        "I"  // count
+        "I"  // contextStart
+        "I"  // contextCount
+        "Z"  // isRtl
+        "J)"  // paint
+        "J",  // LayoutPtr
+        (void*) TextShaper_shapeTextRunChars},
+
+    {"nativeShapeTextRun", "("
+        "Ljava/lang/String;"  // text
+        "I"  // start
+        "I"  // count
+        "I"  // contextStart
+        "I"  // contextCount
+        "Z"  // isRtl
+        "J)"  // paint
+        "J",  // LayoutPtr
+        (void*) TextShaper_shapeTextRunString},
+
+};
+
+static const JNINativeMethod gResultMethods[] = {
+    { "nGetGlyphCount", "(J)I", (void*)TextShaper_Result_getGlyphCount },
+    { "nGetTotalAdvance", "(J)F", (void*)TextShaper_Result_getTotalAdvance },
+    { "nGetAscent", "(J)F", (void*)TextShaper_Result_getAscent },
+    { "nGetDescent", "(J)F", (void*)TextShaper_Result_getDescent },
+    { "nGetGlyphId", "(JI)I", (void*)TextShaper_Result_getGlyphId },
+    { "nGetX", "(JI)F", (void*)TextShaper_Result_getX },
+    { "nGetY", "(JI)F", (void*)TextShaper_Result_getY },
+    { "nGetFont", "(JI)J", (void*)TextShaper_Result_getFont },
+    { "nReleaseFunc", "()J", (void*)TextShaper_Result_nReleaseFunc },
+};
+
+int register_android_graphics_text_TextShaper(JNIEnv* env) {
+    return RegisterMethodsOrDie(env, "android/graphics/text/TextShaper", gMethods,
+                                NELEM(gMethods))
+        + RegisterMethodsOrDie(env, "android/graphics/text/PositionedGlyphs",
+            gResultMethods, NELEM(gResultMethods));
+}
+
+}
+