Wire up support for multiple font managers in txt::FontCollection. (flutter/engine#4042)

This commit is contained in:
Chinmay Garde
2017-09-01 11:56:38 -07:00
committed by GitHub
parent d6e340346d
commit 7d184eb710
34 changed files with 894 additions and 584 deletions

View File

@@ -54,8 +54,8 @@ source_set("ui") {
"semantics/semantics_update.h",
"semantics/semantics_update_builder.cc",
"semantics/semantics_update_builder.h",
"text/font_collection_mgr.cc",
"text/font_collection_mgr.h",
"text/font_collection.cc",
"text/font_collection.h",
"text/paragraph.cc",
"text/paragraph.h",
"text/paragraph_builder.cc",
@@ -87,12 +87,14 @@ source_set("ui") {
deps = [
"//dart/runtime/bin:embedded_dart_io",
"//flutter/assets",
"//flutter/common",
"//flutter/flow",
"//flutter/glue",
"//flutter/sky/engine",
"//flutter/third_party/txt",
"//lib/tonic",
"//third_party/rapidjson",
"//third_party/skia",
"//third_party/skia:gpu",
]

View File

@@ -0,0 +1,107 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <mutex>
#include "flutter/lib/ui/text/font_collection.h"
#include "third_party/rapidjson/rapidjson/document.h"
#include "third_party/rapidjson/rapidjson/rapidjson.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
#include "txt/asset_font_manager.h"
namespace blink {
FontCollection& FontCollection::ForProcess() {
static std::once_flag once = {};
static FontCollection* gCollection = nullptr;
std::call_once(once, []() { gCollection = new FontCollection(); });
return *gCollection;
}
FontCollection::FontCollection()
: collection_(std::make_shared<txt::FontCollection>()) {
collection_->PushBack(SkFontMgr::RefDefault());
}
FontCollection::~FontCollection() = default;
std::shared_ptr<txt::FontCollection> FontCollection::GetFontCollection() const {
return collection_;
}
void FontCollection::RegisterFontsFromAssetStore(
ftl::RefPtr<blink::ZipAssetStore> asset_store) {
if (!asset_store) {
return;
}
std::vector<uint8_t> manifest_data;
if (!asset_store->GetAsBuffer("FontManifest.json", &manifest_data)) {
FTL_DLOG(WARNING) << "Could not find the font manifest in the asset store.";
return;
}
rapidjson::Document document;
static_assert(sizeof(decltype(manifest_data)::value_type) ==
sizeof(decltype(document)::Ch),
"");
document.Parse(
reinterpret_cast<decltype(document)::Ch*>(manifest_data.data()),
manifest_data.size());
if (document.HasParseError()) {
FTL_DLOG(WARNING) << "Error parsing the font manifest in the asset store.";
return;
}
// Structure described in https://flutter.io/custom-fonts/
if (!document.IsArray()) {
return;
}
auto font_asset_data_provider = std::make_unique<txt::AssetDataProvider>();
for (const auto& family : document.GetArray()) {
auto family_name = family.FindMember("family");
if (family_name == family.MemberEnd() || !family_name->value.IsString()) {
continue;
}
auto family_fonts = family.FindMember("fonts");
if (family_fonts == family.MemberEnd() || !family_fonts->value.IsArray()) {
continue;
}
for (const auto& family_font : family_fonts->value.GetArray()) {
if (!family_font.IsObject()) {
continue;
}
auto font_asset = family_font.FindMember("asset");
if (font_asset == family_font.MemberEnd() ||
!font_asset->value.IsString()) {
continue;
}
// TODO: Handle weights and styles.
std::vector<uint8_t> font_data;
if (asset_store->GetAsBuffer(font_asset->value.GetString(), &font_data)) {
// The data must be copied because it needs to be moved into the
// typeface as a stream.
auto data =
SkMemoryStream::MakeCopy(font_data.data(), font_data.size());
// Ownership of the stream is transferred.
auto typeface = SkTypeface::MakeFromStream(data.release());
font_asset_data_provider->RegisterTypeface(
std::move(typeface), family_name->value.GetString());
}
}
}
collection_->PushFront(
sk_make_sp<txt::AssetFontManager>(std::move(font_asset_data_provider)));
}
} // namespace blink

View File

@@ -0,0 +1,39 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_
#define FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_
#include <memory>
#include <vector>
#include "flutter/assets/zip_asset_store.h"
#include "lib/ftl/macros.h"
#include "lib/ftl/memory/ref_ptr.h"
#include "txt/asset_data_provider.h"
#include "txt/font_collection.h"
namespace blink {
class FontCollection {
public:
static FontCollection& ForProcess();
std::shared_ptr<txt::FontCollection> GetFontCollection() const;
void RegisterFontsFromAssetStore(
ftl::RefPtr<blink::ZipAssetStore> asset_store);
private:
std::shared_ptr<txt::FontCollection> collection_;
FontCollection();
~FontCollection();
FTL_DISALLOW_COPY_AND_ASSIGN(FontCollection);
};
} // namespace blink
#endif // FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_

View File

@@ -1,52 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This class creates and holds the txt::FontCollection that contains the
// Default and Custom fonts.
#include "flutter/lib/ui/text/font_collection_mgr.h"
#include "lib/tonic/converter/dart_converter.h"
#include "lib/tonic/dart_args.h"
#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace blink {
IMPLEMENT_WRAPPERTYPEINFO(ui, FontCollectionMgr);
#define FOR_EACH_BINDING(V) \
V(FontCollectionMgr, initializeFontCollection) \
V(FontCollectionMgr, initializeFontCollectionSingle) \
V(FontCollectionMgr, initializeFontCollectionMultiple)
DART_BIND_ALL(FontCollectionMgr, FOR_EACH_BINDING)
txt::FontCollection* FontCollectionMgr::kFontCollection = nullptr;
void FontCollectionMgr::addFontDir(std::string font_dir) {
if (kFontCollection == nullptr)
initializeFontCollection();
kFontCollection->AddFontMgr(font_dir);
}
void FontCollectionMgr::initializeFontCollection() {
txt::FontCollection font_collection = txt::FontCollection();
kFontCollection = &font_collection;
}
void FontCollectionMgr::initializeFontCollectionSingle(std::string font_dir) {
txt::FontCollection font_collection = txt::FontCollection(font_dir);
kFontCollection = &font_collection;
}
void FontCollectionMgr::initializeFontCollectionMultiple(
std::vector<std::string> font_dirs) {
txt::FontCollection font_collection = txt::FontCollection(font_dirs);
kFontCollection = &font_collection;
}
} // namespace blink

View File

@@ -1,44 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This class creates and holds the txt::FontCollection that contains the
// Default and Custom fonts.
#ifndef FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_MGR_H_
#define FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_MGR_H_
#include "flutter/sky/engine/wtf/PassOwnPtr.h"
#include "flutter/third_party/txt/src/txt/font_collection.h"
#include "lib/tonic/dart_wrappable.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace blink {
class FontCollectionMgr : public ftl::RefCountedThreadSafe<FontCollectionMgr>,
public tonic::DartWrappable {
DEFINE_WRAPPERTYPEINFO();
FRIEND_MAKE_REF_COUNTED(FontCollectionMgr);
public:
static txt::FontCollection* kFontCollection;
static void addFontDir(std::string font_dir);
static void initializeFontCollection();
static void initializeFontCollectionSingle(std::string font_dir);
static void initializeFontCollectionMultiple(
std::vector<std::string> font_dirs);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
};
} // namespace blink
#endif // FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_MGR_H_

View File

@@ -6,6 +6,7 @@
#include "flutter/common/settings.h"
#include "flutter/common/threads.h"
#include "flutter/lib/ui/text/font_collection.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/sky/engine/core/rendering/RenderInline.h"
#include "flutter/sky/engine/core/rendering/RenderParagraph.h"
@@ -234,7 +235,8 @@ ParagraphBuilder::ParagraphBuilder(tonic::Int32List& encoded,
if (mask & psEllipsisMask)
style.ellipsis = ellipsis;
m_paragraphBuilder.SetParagraphStyle(style);
m_paragraphBuilder = std::make_unique<txt::ParagraphBuilder>(
style, blink::FontCollection::ForProcess().GetFontCollection());
} else {
// Blink version.
createRenderView();
@@ -273,7 +275,7 @@ void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
if (!Settings::Get().using_blink) {
// Set to use the properties of the previous style if the property is not
// explicitly given.
txt::TextStyle style = m_paragraphBuilder.PeekStyle();
txt::TextStyle style = m_paragraphBuilder->PeekStyle();
if (mask & tsColorMask)
style.color = encoded[tsColorIndex];
@@ -322,7 +324,7 @@ void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
style.height = height;
}
m_paragraphBuilder.PushStyle(style);
m_paragraphBuilder->PushStyle(style);
} else {
// Blink Version.
RefPtr<RenderStyle> style = RenderStyle::create();
@@ -400,7 +402,7 @@ void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
void ParagraphBuilder::pop() {
if (!Settings::Get().using_blink) {
m_paragraphBuilder.Pop();
m_paragraphBuilder->Pop();
} else {
// Blink Version.
if (m_currentRenderObject)
@@ -410,7 +412,7 @@ void ParagraphBuilder::pop() {
void ParagraphBuilder::addText(const std::string& text) {
if (!Settings::Get().using_blink) {
m_paragraphBuilder.AddText(text);
m_paragraphBuilder->AddText(text);
} else {
// Blink Version.
if (!m_currentRenderObject)
@@ -426,7 +428,7 @@ void ParagraphBuilder::addText(const std::string& text) {
ftl::RefPtr<Paragraph> ParagraphBuilder::build() {
m_currentRenderObject = nullptr;
if (!Settings::Get().using_blink) {
return Paragraph::Create(m_paragraphBuilder.Build());
return Paragraph::Create(m_paragraphBuilder->Build());
} else {
return Paragraph::Create(m_renderView.release());
}

View File

@@ -5,6 +5,7 @@
#ifndef FLUTTER_LIB_UI_TEXT_PARAGRAPH_BUILDER_H_
#define FLUTTER_LIB_UI_TEXT_PARAGRAPH_BUILDER_H_
#include <memory>
#include "flutter/lib/ui/text/paragraph.h"
#include "flutter/sky/engine/core/rendering/RenderObject.h"
#include "flutter/sky/engine/wtf/OwnPtr.h"
@@ -61,7 +62,7 @@ class ParagraphBuilder : public ftl::RefCountedThreadSafe<ParagraphBuilder>,
OwnPtr<RenderView> m_renderView;
RenderObject* m_renderParagraph;
RenderObject* m_currentRenderObject;
txt::ParagraphBuilder m_paragraphBuilder;
std::unique_ptr<txt::ParagraphBuilder> m_paragraphBuilder;
};
} // namespace blink

View File

@@ -5,7 +5,6 @@
#include "flutter/runtime/asset_font_selector.h"
#include "flutter/assets/zip_asset_store.h"
#include "flutter/lib/ui/text/font_collection_mgr.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/sky/engine/platform/fonts/FontData.h"
#include "flutter/sky/engine/platform/fonts/FontFaceCreationParams.h"

View File

@@ -112,6 +112,7 @@ source_set("common") {
"//flutter/runtime",
"//flutter/sky/engine/wtf",
"//flutter/synchronization",
"//flutter/third_party/txt",
"//garnet/public/lib/ftl",
"//lib/tonic",
"//third_party/rapidjson",

View File

@@ -19,6 +19,7 @@
#include "flutter/common/threads.h"
#include "flutter/glue/trace_event.h"
#include "flutter/lib/snapshot/snapshot.h"
#include "flutter/lib/ui/text/font_collection.h"
#include "flutter/runtime/asset_font_selector.h"
#include "flutter/runtime/dart_controller.h"
#include "flutter/runtime/dart_init.h"
@@ -109,7 +110,8 @@ static const uint8_t* MemMapSnapshot(const std::string& aot_snapshot_path,
}
int mmap_flags = PROT_READ;
if (executable) mmap_flags |= PROT_EXEC;
if (executable)
mmap_flags |= PROT_EXEC;
void* symbol = mmap(NULL, asset_size, mmap_flags, MAP_PRIVATE, fd.get(), 0);
if (symbol == MAP_FAILED) {
@@ -338,7 +340,8 @@ bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) {
}
// Always schedule a frame when the app does become active as per API
// recommendation https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc
// recommendation
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc
if (state == "AppLifecycleState.resumed" && have_surface_) {
ScheduleFrame();
}
@@ -435,12 +438,11 @@ void Engine::ConfigureAssetBundle(const std::string& path) {
}
void Engine::ConfigureRuntime(const std::string& script_uri,
const std::vector<uint8_t>& platform_kernel) {
const std::vector<uint8_t>& platform_kernel) {
runtime_ = blink::RuntimeController::Create(this);
runtime_->CreateDartController(std::move(script_uri),
default_isolate_snapshot_data,
default_isolate_snapshot_instr,
platform_kernel);
runtime_->CreateDartController(
std::move(script_uri), default_isolate_snapshot_data,
default_isolate_snapshot_instr, platform_kernel);
runtime_->SetViewportMetrics(viewport_metrics_);
runtime_->SetLocale(language_code_, country_code_);
runtime_->SetSemanticsEnabled(semantics_enabled_);
@@ -451,6 +453,10 @@ void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
blink::TestFontSelector::Install();
} else if (asset_store_) {
blink::AssetFontSelector::Install(asset_store_);
if (!blink::Settings::Get().using_blink) {
blink::FontCollection::ForProcess().RegisterFontsFromAssetStore(
asset_store_);
}
}
}
@@ -490,11 +496,12 @@ void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
}
void Engine::UpdateSemantics(std::vector<blink::SemanticsNode> update) {
blink::Threads::Platform()->PostTask(ftl::MakeCopyable(
[ platform_view = platform_view_.lock(), update = std::move(update) ]() mutable {
if (platform_view)
platform_view->UpdateSemantics(std::move(update));
}));
blink::Threads::Platform()->PostTask(ftl::MakeCopyable([
platform_view = platform_view_.lock(), update = std::move(update)
]() mutable {
if (platform_view)
platform_view->UpdateSemantics(std::move(update));
}));
}
void Engine::HandlePlatformMessage(

View File

@@ -64,6 +64,14 @@ source_set("txt") {
"src/minikin/SparseBitSet.h",
"src/minikin/WordBreaker.cpp",
"src/minikin/WordBreaker.h",
"src/txt/asset_data_provider.cc",
"src/txt/asset_data_provider.h",
"src/txt/asset_font_manager.cc",
"src/txt/asset_font_manager.h",
"src/txt/asset_font_style_set.cc",
"src/txt/asset_font_style_set.h",
"src/txt/directory_asset_data_provider.cc",
"src/txt/directory_asset_data_provider.h",
"src/txt/font_collection.cc",
"src/txt/font_collection.h",
"src/txt/font_skia.cc",

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2017 Google Inc.
*
* 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.
*/
#include "txt/asset_data_provider.h"
#include "lib/ftl/logging.h"
namespace txt {
AssetDataProvider::AssetDataProvider() = default;
AssetDataProvider::~AssetDataProvider() = default;
size_t AssetDataProvider::GetFamilyCount() const {
return registered_families_.size();
}
AssetFontStyleSet* AssetDataProvider::MatchFamily(
const std::string& family_name) {
auto found = registered_families_.find(family_name);
if (found == registered_families_.end()) {
return nullptr;
}
return &found->second;
}
void AssetDataProvider::RegisterTypeface(sk_sp<SkTypeface> typeface) {
if (typeface == nullptr) {
return;
}
SkString sk_family_name;
typeface->getFamilyName(&sk_family_name);
if (sk_family_name.isEmpty()) {
return;
}
std::string family_name(sk_family_name.c_str(), sk_family_name.size());
RegisterTypeface(std::move(typeface), std::move(family_name));
}
void AssetDataProvider::RegisterTypeface(sk_sp<SkTypeface> typeface,
std::string family_name_alias) {
registered_families_[std::move(family_name_alias)].registerTypeface(
std::move(typeface));
}
} // namespace txt

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2017 Google Inc.
*
* 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.
*/
#ifndef TXT_ASSET_DATA_PROVIDER_H_
#define TXT_ASSET_DATA_PROVIDER_H_
#include <string>
#include <unordered_map>
#include "lib/ftl/macros.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "txt/asset_font_style_set.h"
namespace txt {
class AssetDataProvider {
public:
AssetDataProvider();
virtual ~AssetDataProvider();
size_t GetFamilyCount() const;
AssetFontStyleSet* MatchFamily(const std::string& family_name);
void RegisterTypeface(sk_sp<SkTypeface> typeface);
void RegisterTypeface(sk_sp<SkTypeface> typeface,
std::string family_name_alias);
private:
std::unordered_map<std::string, AssetFontStyleSet> registered_families_;
FTL_DISALLOW_COPY_AND_ASSIGN(AssetDataProvider);
};
} // namespace txt
#endif // TXT_ASSET_DATA_PROVIDER_H_

View File

@@ -0,0 +1,100 @@
/*
* Copyright 2017 Google Inc.
*
* 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.
*/
#include "lib/ftl/logging.h"
#include "txt/asset_font_manager.h"
namespace txt {
AssetFontManager::AssetFontManager(
std::unique_ptr<AssetDataProvider> data_provider)
: data_provider_(std::move(data_provider)) {
FTL_DCHECK(data_provider_ != nullptr);
}
AssetFontManager::~AssetFontManager() = default;
int AssetFontManager::onCountFamilies() const {
return data_provider_->GetFamilyCount();
}
void AssetFontManager::onGetFamilyName(int index, SkString* familyName) const {
FTL_DCHECK(false);
}
SkFontStyleSet* AssetFontManager::onCreateStyleSet(int index) const {
FTL_DCHECK(false);
return nullptr;
}
SkFontStyleSet* AssetFontManager::onMatchFamily(
const char family_name_string[]) const {
std::string family_name(family_name_string);
return data_provider_->MatchFamily(family_name);
}
SkTypeface* AssetFontManager::onMatchFamilyStyle(const char familyName[],
const SkFontStyle&) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onMatchFamilyStyleCharacter(
const char familyName[],
const SkFontStyle&,
const char* bcp47[],
int bcp47Count,
SkUnichar character) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onMatchFaceStyle(const SkTypeface*,
const SkFontStyle&) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onCreateFromData(SkData*, int ttcIndex) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onCreateFromStream(SkStreamAsset*,
int ttcIndex) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onCreateFromStream(SkStreamAsset*,
const SkFontArguments&) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onCreateFromFile(const char path[],
int ttcIndex) const {
FTL_DCHECK(false);
return nullptr;
}
SkTypeface* AssetFontManager::onLegacyCreateTypeface(const char familyName[],
SkFontStyle) const {
FTL_DCHECK(false);
return nullptr;
}
} // namespace txt

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2017 Google Inc.
*
* 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.
*/
#ifndef TXT_ASSET_FONT_MANAGER_H_
#define TXT_ASSET_FONT_MANAGER_H_
#include <memory>
#include "lib/ftl/macros.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
#include "txt/asset_data_provider.h"
namespace txt {
class AssetFontManager : public SkFontMgr {
public:
AssetFontManager(std::unique_ptr<AssetDataProvider> data_provider);
~AssetFontManager() override;
private:
std::unique_ptr<AssetDataProvider> data_provider_;
// |SkFontMgr|
int onCountFamilies() const override;
// |SkFontMgr|
void onGetFamilyName(int index, SkString* familyName) const override;
// |SkFontMgr|
SkFontStyleSet* onCreateStyleSet(int index) const override;
// |SkFontMgr|
SkFontStyleSet* onMatchFamily(const char familyName[]) const override;
// |SkFontMgr|
SkTypeface* onMatchFamilyStyle(const char familyName[],
const SkFontStyle&) const override;
// |SkFontMgr|
SkTypeface* onMatchFamilyStyleCharacter(const char familyName[],
const SkFontStyle&,
const char* bcp47[],
int bcp47Count,
SkUnichar character) const override;
// |SkFontMgr|
SkTypeface* onMatchFaceStyle(const SkTypeface*,
const SkFontStyle&) const override;
// |SkFontMgr|
SkTypeface* onCreateFromData(SkData*, int ttcIndex) const override;
// |SkFontMgr|
SkTypeface* onCreateFromStream(SkStreamAsset*, int ttcIndex) const override;
// |SkFontMgr|
SkTypeface* onCreateFromStream(SkStreamAsset*,
const SkFontArguments&) const override;
// |SkFontMgr|
SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const override;
// |SkFontMgr|
SkTypeface* onLegacyCreateTypeface(const char familyName[],
SkFontStyle) const override;
FTL_DISALLOW_COPY_AND_ASSIGN(AssetFontManager);
};
} // namespace txt
#endif // TXT_ASSET_FONT_MANAGER_H_

View File

@@ -0,0 +1,42 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "txt/asset_font_style_set.h"
#include "lib/ftl/logging.h"
namespace txt {
AssetFontStyleSet::AssetFontStyleSet() = default;
AssetFontStyleSet::~AssetFontStyleSet() = default;
void AssetFontStyleSet::registerTypeface(sk_sp<SkTypeface> typeface) {
if (typeface == nullptr) {
return;
}
typefaces_.emplace_back(std::move(typeface));
}
int AssetFontStyleSet::count() {
return typefaces_.size();
}
void AssetFontStyleSet::getStyle(int index, SkFontStyle*, SkString* style) {
FTL_DCHECK(false);
}
SkTypeface* AssetFontStyleSet::createTypeface(int index) {
auto index_cast = static_cast<size_t>(index);
if (index_cast >= typefaces_.size()) {
return nullptr;
}
return typefaces_[index_cast].get();
}
SkTypeface* AssetFontStyleSet::matchStyle(const SkFontStyle& pattern) {
FTL_DCHECK(false);
return nullptr;
}
} // namespace txt

View File

@@ -0,0 +1,44 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TXT_ASSET_FONT_STYLE_SET_H_
#define TXT_ASSET_FONT_STYLE_SET_H_
#include <vector>
#include "lib/ftl/macros.h"
#include "third_party/skia/include/core/SkFontStyle.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
namespace txt {
class AssetFontStyleSet : public SkFontStyleSet {
public:
AssetFontStyleSet();
~AssetFontStyleSet() override;
void registerTypeface(sk_sp<SkTypeface> typeface);
// |SkFontStyleSet|
int count() override;
// |SkFontStyleSet|
void getStyle(int index, SkFontStyle*, SkString* style) override;
// |SkFontStyleSet|
SkTypeface* createTypeface(int index) override;
// |SkFontStyleSet|
SkTypeface* matchStyle(const SkFontStyle& pattern) override;
private:
std::vector<sk_sp<SkTypeface>> typefaces_;
FTL_DISALLOW_COPY_AND_ASSIGN(AssetFontStyleSet);
};
} // namespace txt
#endif // TXT_ASSET_FONT_STYLE_SET_H_

View File

@@ -0,0 +1,46 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <dirent.h>
#include <sstream>
#include "lib/ftl/logging.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "txt/directory_asset_data_provider.h"
namespace txt {
DirectoryAssetDataProvider::DirectoryAssetDataProvider(
const std::string& directory_path) {
auto directory_closer = [](DIR* directory) {
if (directory != nullptr) {
::closedir(directory);
}
};
std::unique_ptr<DIR, decltype(directory_closer)> directory(
::opendir(directory_path.c_str()), directory_closer);
if (directory == nullptr) {
return;
}
for (struct dirent* entry = ::readdir(directory.get()); entry != nullptr;
entry = ::readdir(directory.get())) {
if (entry->d_type != DT_REG) {
continue;
}
std::string file_name(entry->d_name);
std::stringstream file_path;
file_path << directory_path << "/" << file_name;
RegisterTypeface(SkTypeface::MakeFromFile(file_path.str().c_str()));
}
}
DirectoryAssetDataProvider::~DirectoryAssetDataProvider() = default;
} // namespace txt

View File

@@ -0,0 +1,25 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TXT_DIRECTORY_ASSET_DATA_PROVIDER_H_
#define TXT_DIRECTORY_ASSET_DATA_PROVIDER_H_
#include "lib/ftl/macros.h"
#include "txt/asset_data_provider.h"
namespace txt {
class DirectoryAssetDataProvider : public AssetDataProvider {
public:
DirectoryAssetDataProvider(const std::string& directory);
~DirectoryAssetDataProvider() override;
private:
FTL_DISALLOW_COPY_AND_ASSIGN(DirectoryAssetDataProvider);
};
} // namespace txt
#endif // TXT_DIRECTORY_ASSET_DATA_PROVIDER_H_

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 Google, Inc.
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,227 +23,97 @@
#include <string>
#include <unordered_map>
#include <vector>
#include "font_skia.h"
#include "lib/ftl/logging.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
#include "third_party/skia/include/ports/SkFontMgr_android.h"
#include "third_party/skia/include/ports/SkFontMgr_directory.h"
#include "txt/text_style.h"
namespace txt {
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete.
FontCollection& FontCollection::GetFontCollection(std::string dir) {
std::vector<std::string> dirs = {dir};
return GetFontCollection(std::move(dirs));
}
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete.
FontCollection& FontCollection::GetFontCollection(
std::vector<std::string> dirs) {
static FontCollection* collection = nullptr;
static std::once_flag once;
std::call_once(once, [dirs]() { collection = new FontCollection(dirs); });
return *collection;
}
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete.
FontCollection& FontCollection::GetDefaultFontCollection() {
return GetFontCollection("");
}
FontCollection::FontCollection() {
FontCollection("");
}
FontCollection::FontCollection(CacheMethod cache_method) {
FontCollection("", cache_method);
}
FontCollection::FontCollection(std::string dir, CacheMethod cache_method) {
std::vector<std::string> dirs = {dir};
FontCollection(std::move(dirs), cache_method);
}
FontCollection::FontCollection(const std::vector<std::string>& dirs,
CacheMethod cache_method) {
for (std::string dir : dirs) {
if (dir.length() != 0) {
AddFontMgr(dir, false);
}
}
skia_font_managers_.push_back(SkFontMgr::RefDefault());
DiscoverFamilyNames();
cache_method_ = cache_method;
}
FontCollection::FontCollection() = default;
FontCollection::~FontCollection() = default;
void FontCollection::AddFontMgr(std::string dir, bool rediscover_family_names) {
#ifdef DIRECTORY_FONT_MANAGER_AVAILABLE
// On Linux systems:
skia_font_managers_.push_back(SkFontMgr_New_Custom_Directory(dir.c_str()));
#endif
#ifdef ANDROID_FONT_MANAGER_AVAILABLE
// On Android:
SkFontMgr_Android_CustomFonts android_custom_font_data;
// Ensure the dir string is '/' terminated.
if (dir.back() != '/')
dir += '/';
android_custom_font_data.fBasePath = dir.data();
android_custom_font_data.fSystemFontUse =
SkFontMgr_Android_CustomFonts::SystemFontUse::kOnlyCustom;
skia_font_managers_.push_back(
SkFontMgr_New_Android(&android_custom_font_data));
#endif
if (rediscover_family_names)
DiscoverFamilyNames(skia_font_managers_.back());
size_t FontCollection::GetFontManagersCount() const {
return skia_font_managers_.size();
}
void FontCollection::AddFontMgr(sk_sp<SkFontMgr> font_mgr,
bool rediscover_family_names) {
skia_font_managers_.push_back(font_mgr);
if (rediscover_family_names)
DiscoverFamilyNames(font_mgr);
}
void FontCollection::DiscoverFamilyNames() {
for (sk_sp<SkFontMgr> mgr : skia_font_managers_) {
DiscoverFamilyNames(mgr);
void FontCollection::PushFront(sk_sp<SkFontMgr> skia_font_manager) {
if (!skia_font_manager) {
return;
}
skia_font_managers_.push_front(std::move(skia_font_manager));
}
void FontCollection::DiscoverFamilyNames(sk_sp<SkFontMgr> mgr) {
SkString str;
for (int i = 0; i < mgr->countFamilies(); i++) {
mgr->getFamilyName(i, &str);
family_names_.insert(std::string{str.writable_str()});
void FontCollection::PushBack(sk_sp<SkFontMgr> skia_font_manager) {
if (!skia_font_manager) {
return;
}
}
std::set<std::string> FontCollection::GetFamilyNames() {
return family_names_;
}
bool FontCollection::HasFamily(const std::string family) const {
return family_names_.count(family) == 1;
}
void FontCollection::FlushCache() {
minikin_font_collection_map_.clear();
lru_tracker_.clear();
}
void FontCollection::SetCacheCapacity(const size_t cap) {
cache_capacity_ = cap;
}
void FontCollection::SetLowMemoryMode(bool mode, size_t cap) {
cache_capacity_ = cap;
if (mode) {
cache_method_ = CacheMethod::kLRU;
TrimCache();
} else {
cache_method_ = CacheMethod::kUnlimited;
}
}
void FontCollection::TrimCache() {
while (minikin_font_collection_map_.size() > cache_capacity_) {
std::string family_to_evict = lru_tracker_.back();
lru_tracker_.pop_back();
minikin_font_collection_map_.erase(family_to_evict);
}
}
const std::string FontCollection::ProcessFamilyName(const std::string& family) {
#ifdef DIRECTORY_FONT_MANAGER_AVAILABLE
return family.length() == 0 ? DEFAULT_FAMILY_NAME : family;
#else
if (family.length() > 0 &&
GetFamilyNames().count(family) > 0) { // Ensure family exists.
return family;
} else {
if (GetFamilyNames().count(DEFAULT_FAMILY_NAME) > 0) {
return DEFAULT_FAMILY_NAME;
}
return *GetFamilyNames().begin(); // First family available.
}
#endif
skia_font_managers_.push_back(std::move(skia_font_manager));
}
std::shared_ptr<minikin::FontCollection>
FontCollection::GetMinikinFontCollectionForFamily(const std::string& family) {
FTL_DCHECK(skia_font_managers_.size() > 0);
std::string processed_family_name = ProcessFamilyName(family);
// Only obtain new font family if the font has changed between runs.
if (cache_method_ == CacheMethod::kNone ||
minikin_font_collection_map_.count(processed_family_name) == 0) {
// Ask Skia to resolve a font style set for a font family name.
// FIXME(chinmaygarde): CoreText crashes when passed a null string. This
// seems to be a bug in Skia as SkFontMgr explicitly says passing in
// nullptr gives the default font.
for (sk_sp<SkFontMgr> mgr : skia_font_managers_) {
FTL_DCHECK(mgr != nullptr);
auto font_style_set = mgr->matchFamily(processed_family_name.c_str());
if (font_style_set != nullptr) {
std::vector<minikin::Font> minikin_fonts;
// Look inside the font collections cache first.
auto cached = font_collections_cache_.find(family);
if (cached != font_collections_cache_.end()) {
return cached->second;
}
// Add fonts to the Minikin font family.
for (int i = 0, style_count = font_style_set->count(); i < style_count;
++i) {
// Create the skia typeface
auto skia_typeface =
sk_ref_sp<SkTypeface>(font_style_set->createTypeface(i));
if (skia_typeface == nullptr) {
continue;
}
// Create the minikin font from the skia typeface.
// Divide by 100 because the weights are given as "100", "200", etc.
minikin::Font minikin_font(
std::make_shared<FontSkia>(skia_typeface),
minikin::FontStyle{skia_typeface->fontStyle().weight() / 100,
skia_typeface->isItalic()});
minikin_fonts.emplace_back(std::move(minikin_font));
}
// Create a Minikin font family.
auto minikin_family =
std::make_shared<minikin::FontFamily>(std::move(minikin_fonts));
// Create a vector of font families for the Minkin font collection. For
// now, we only have one family in our collection.
std::vector<std::shared_ptr<minikin::FontFamily>> minikin_families = {
minikin_family,
};
// Assign the font collection.
minikin_font_collection_map_[processed_family_name] =
std::make_shared<minikin::FontCollection>(minikin_families);
return minikin_font_collection_map_[processed_family_name];
}
for (sk_sp<SkFontMgr> manager : skia_font_managers_) {
auto font_style_set = manager->matchFamily(family.c_str());
if (font_style_set == nullptr || font_style_set->count() == 0) {
continue;
}
// Uh oh! Font family not found in any of the font managers!
minikin_font_collection_map_[processed_family_name] = nullptr;
std::vector<minikin::Font> minikin_fonts;
// Add fonts to the Minikin font family.
for (int i = 0, style_count = font_style_set->count(); i < style_count;
++i) {
// Create the skia typeface.
auto skia_typeface =
sk_ref_sp<SkTypeface>(font_style_set->createTypeface(i));
if (skia_typeface == nullptr) {
continue;
}
// Create the minikin font from the skia typeface.
// Divide by 100 because the weights are given as "100", "200", etc.
minikin::Font minikin_font(
std::make_shared<FontSkia>(skia_typeface),
minikin::FontStyle{skia_typeface->fontStyle().weight() / 100,
skia_typeface->isItalic()});
minikin_fonts.emplace_back(std::move(minikin_font));
}
// Create a Minikin font family.
auto minikin_family =
std::make_shared<minikin::FontFamily>(std::move(minikin_fonts));
// Create a vector of font families for the Minikin font collection. For
// now, we only have one family in our collection.
std::vector<std::shared_ptr<minikin::FontFamily>> minikin_families = {
minikin_family,
};
// Create the minikin font collection.
auto font_collection =
std::make_shared<minikin::FontCollection>(std::move(minikin_families));
// Cache the font collection for future queries.
font_collections_cache_[family] = font_collection;
return font_collection;
}
// Maintain LRU and evict old fonts no longer used.
lru_tracker_.remove(processed_family_name);
lru_tracker_.push_front(processed_family_name);
if (cache_method_ == CacheMethod::kLRU) {
TrimCache();
const auto default_font_family = TextStyle::GetDefaultFontFamily();
if (family != default_font_family) {
return GetMinikinFontCollectionForFamily(default_font_family);
}
return minikin_font_collection_map_[processed_family_name];
// No match found in any of our font managers.
return nullptr;
}
} // namespace txt

View File

@@ -17,130 +17,41 @@
#ifndef LIB_TXT_SRC_FONT_COLLECTION_H_
#define LIB_TXT_SRC_FONT_COLLECTION_H_
#define DEFAULT_FAMILY_NAME "Roboto"
#ifdef ANDROID_FONT_MANAGER_AVAILABLE
#undef DEFAULT_FAMILY_NAME
// On Android, Roboto is called 'sans-serif'
#define DEFAULT_FAMILY_NAME "sans-serif"
#endif
#define DEFAULT_CACHE_CAPACITY 20
#include <list>
#include <deque>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "lib/ftl/macros.h"
#include "minikin/FontCollection.h"
#include "minikin/FontFamily.h"
#include "third_party/gtest/include/gtest/gtest_prod.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/ports/SkFontMgr.h"
#include "txt/asset_font_manager.h"
namespace txt {
// FontCollection holds a vector of Skia Font Managers and handles font
// fallback. If no additional font directories are provided, then only the
// default font directory will be available.
class FontCollection {
public:
enum CacheMethod {
kNone,
kLRU, // Least Recently Used.
kUnlimited,
};
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete.
static FontCollection& GetDefaultFontCollection();
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete..
static FontCollection& GetFontCollection(std::string dir = "");
// TODO(garyq): Will be deprecated when full compatibility with Flutter Engine
// is complete.
static FontCollection& GetFontCollection(std::vector<std::string> dirs);
// Provides a pointer to the minikin FontCollection for the given font family.
// If the famly is not in any font manager, this will return a nullptr. Once a
// font is loaded, it is cached and future calls will be very efficient
// (until/if the font is flushed).
std::shared_ptr<minikin::FontCollection> GetMinikinFontCollectionForFamily(
const std::string& family);
FontCollection(const std::vector<std::string>& dirs,
CacheMethod cache_method = CacheMethod::kUnlimited);
FontCollection(std::string dir,
CacheMethod cache_method = CacheMethod::kUnlimited);
FontCollection(CacheMethod cache_method);
FontCollection();
~FontCollection();
// Provides a set of all available family names.
std::set<std::string> GetFamilyNames();
size_t GetFontManagersCount() const;
// Returns true when the supplied font family exists in any of the font
// managers.
bool HasFamily(const std::string family) const;
void PushFront(sk_sp<SkFontMgr> skia_font_manager);
// Adds a new SkFontMgr to the front of the stack of font managers.
void AddFontMgr(std::string dir, bool rediscover_family_names = true);
void PushBack(sk_sp<SkFontMgr> skia_font_manager);
// Adds the provided SkFontMgr to the front of the stack of font managers.
void AddFontMgr(sk_sp<SkFontMgr> font_mgr,
bool rediscover_family_names = true);
// Removes all fonts that do not fit in the cache capacity from memory.
void FlushCache();
// When in LRU mode, the cache will only hold the <cap> most recently used
// fonts. This may be used when the application becomes low on memory or a
// very large number of fonts are used.
void SetCacheCapacity(const size_t cap);
// Call this to limit memory usage by cached fonts. SetLowMemoryMode() will
// enable default LRU policy and flush fonts beyond capacity.
void SetLowMemoryMode(bool mode = true, size_t cap = DEFAULT_CACHE_CAPACITY);
std::shared_ptr<minikin::FontCollection> GetMinikinFontCollectionForFamily(
const std::string& family);
private:
std::vector<sk_sp<SkFontMgr>> skia_font_managers_;
// Cache the names because GetFamilyNames() can be frequently called.
std::set<std::string> family_names_;
CacheMethod cache_method_ = CacheMethod::kUnlimited;
std::list<std::string> lru_tracker_;
size_t cache_capacity_ = DEFAULT_CACHE_CAPACITY;
// Cache minikin font collections to prevent slow disk reads.
std::deque<sk_sp<SkFontMgr>> skia_font_managers_;
std::unordered_map<std::string, std::shared_ptr<minikin::FontCollection>>
minikin_font_collection_map_;
font_collections_cache_;
FRIEND_TEST(FontCollection, HasDefaultRegistrations);
FRIEND_TEST(FontCollection, GetMinikinFontCollections);
FRIEND_TEST(FontCollection, GetFamilyNames);
// Postprocess the family name to handle the following properties: fallback
// when not found and reverting to the default name when no fallback is found.
const std::string ProcessFamilyName(const std::string& family);
// Polls all of the SkFontMgrs to obtain a set of all available font family
// names.
void DiscoverFamilyNames();
// Add the family names of mgr to set of available font family names.
void DiscoverFamilyNames(sk_sp<SkFontMgr> mgr);
void TrimCache();
static const std::string GetDefaultFamilyName() {
return DEFAULT_FAMILY_NAME;
};
FTL_DISALLOW_COPY_AND_ASSIGN(FontCollection);
};
} // namespace txt

View File

@@ -137,25 +137,25 @@ void Paragraph::InitBreaker() {
breaker_.setText();
}
// NOTE: Minikin LineBreaker addStyleRun() has an O(N^2) (according to
// benchmarks) time complexity where N is the total number of characters.
// However, this is not significant for reasonably sized paragraphs. It is
// currently recommended to break up very long paragraphs (10k+ characters) to
// ensure speedy layout.
void Paragraph::AddRunsToLineBreaker(
bool Paragraph::AddRunsToLineBreaker(
std::unordered_map<std::string, std::shared_ptr<minikin::FontCollection>>&
collection_map) {
collection_map /* TODO: Cache the font collection here. */) {
minikin::FontStyle font;
minikin::MinikinPaint paint;
for (size_t i = 0; i < runs_.size(); ++i) {
auto run = runs_.GetRun(i);
GetFontAndMinikinPaint(run.style, &font, &paint);
breaker_.addStyleRun(&paint,
font_collection_->GetMinikinFontCollectionForFamily(
run.style.font_family),
font, run.start, run.end, false,
auto collection = font_collection_->GetMinikinFontCollectionForFamily(
run.style.font_family);
if (collection == nullptr) {
FTL_DLOG(INFO) << "Could not find font collection for family \""
<< run.style.font_family << "\".";
return false;
}
breaker_.addStyleRun(&paint, collection, font, run.start, run.end, false,
run.style.letter_spacing);
}
return true;
}
void Paragraph::FillWhitespaceSet(size_t start,
@@ -172,8 +172,9 @@ void Paragraph::FillWhitespaceSet(size_t start,
void Paragraph::Layout(double width, bool force) {
// Do not allow calling layout multiple times without changing anything.
if (!needs_layout_ && width == width_ && !force)
if (!needs_layout_ && width == width_ && !force) {
return;
}
needs_layout_ = false;
width_ = width;
@@ -182,6 +183,7 @@ void Paragraph::Layout(double width, bool force) {
collection_map;
breaker_.setLineWidths(0.0f, 0, width_);
// TODO(garyq): Get hyphenator working. Hyphenator should be created with
// a pattern binary dataset. Should be something along these lines:
//
@@ -189,8 +191,14 @@ void Paragraph::Layout(double width, bool force) {
// minikin::Hyphenator::loadBinary(<paramsgohere>);
// breaker_.setLocale(icu::Locale::getRoot(), &hyph);
//
// TODO: Maybe create a new breaker altogether.
InitBreaker();
AddRunsToLineBreaker(collection_map);
if (!AddRunsToLineBreaker(collection_map)) {
return;
}
breaker_.setJustified(paragraph_style_.text_align == TextAlign::justify);
breaker_.setStrategy(paragraph_style_.break_strategy);
size_t breaks_count = breaker_.computeBreaks();
@@ -601,8 +609,9 @@ void Paragraph::SetParagraphStyle(const ParagraphStyle& style) {
paragraph_style_ = style;
}
void Paragraph::SetFontCollection(FontCollection* font_collection) {
font_collection_ = font_collection;
void Paragraph::SetFontCollection(
std::shared_ptr<FontCollection> font_collection) {
font_collection_ = std::move(font_collection);
}
// The x,y coordinates will be the very top left corner of the rendered

View File

@@ -17,10 +17,12 @@
#ifndef LIB_TXT_SRC_PARAGRAPH_H_
#define LIB_TXT_SRC_PARAGRAPH_H_
#include <set>
#include <tuple>
#include <vector>
#include "font_collection.h"
#include "lib/ftl/compiler_specific.h"
#include "lib/ftl/macros.h"
#include "minikin/LineBreaker.h"
#include "paint_record.h"
@@ -142,32 +144,32 @@ class Paragraph {
private:
friend class ParagraphBuilder;
FRIEND_TEST(RenderTest, SimpleParagraph);
FRIEND_TEST(RenderTest, SimpleRedParagraph);
FRIEND_TEST(RenderTest, RainbowParagraph);
FRIEND_TEST(RenderTest, DefaultStyleParagraph);
FRIEND_TEST(RenderTest, BoldParagraph);
FRIEND_TEST(RenderTest, LeftAlignParagraph);
FRIEND_TEST(RenderTest, RightAlignParagraph);
FRIEND_TEST(RenderTest, CenterAlignParagraph);
FRIEND_TEST(RenderTest, JustifyAlignParagraph);
FRIEND_TEST(RenderTest, DecorationsParagraph);
FRIEND_TEST(RenderTest, ItalicsParagraph);
FRIEND_TEST(RenderTest, ChineseParagraph);
FRIEND_TEST(RenderTest, DISABLED_ArabicParagraph);
FRIEND_TEST(RenderTest, SpacingParagraph);
FRIEND_TEST(RenderTest, LongWordParagraph);
FRIEND_TEST(RenderTest, KernScaleParagraph);
FRIEND_TEST(RenderTest, NewlineParagraph);
FRIEND_TEST(RenderTest, EmojiParagraph);
FRIEND_TEST(RenderTest, HyphenBreakParagraph);
FRIEND_TEST(RenderTest, RepeatLayoutParagraph);
FRIEND_TEST(ParagraphTest, SimpleParagraph);
FRIEND_TEST(ParagraphTest, SimpleRedParagraph);
FRIEND_TEST(ParagraphTest, RainbowParagraph);
FRIEND_TEST(ParagraphTest, DefaultStyleParagraph);
FRIEND_TEST(ParagraphTest, BoldParagraph);
FRIEND_TEST(ParagraphTest, LeftAlignParagraph);
FRIEND_TEST(ParagraphTest, RightAlignParagraph);
FRIEND_TEST(ParagraphTest, CenterAlignParagraph);
FRIEND_TEST(ParagraphTest, JustifyAlignParagraph);
FRIEND_TEST(ParagraphTest, DecorationsParagraph);
FRIEND_TEST(ParagraphTest, ItalicsParagraph);
FRIEND_TEST(ParagraphTest, ChineseParagraph);
FRIEND_TEST(ParagraphTest, DISABLED_ArabicParagraph);
FRIEND_TEST(ParagraphTest, SpacingParagraph);
FRIEND_TEST(ParagraphTest, LongWordParagraph);
FRIEND_TEST(ParagraphTest, KernScaleParagraph);
FRIEND_TEST(ParagraphTest, NewlineParagraph);
FRIEND_TEST(ParagraphTest, EmojiParagraph);
FRIEND_TEST(ParagraphTest, HyphenBreakParagraph);
FRIEND_TEST(ParagraphTest, RepeatLayoutParagraph);
// Starting data to layout.
std::vector<uint16_t> text_;
StyledRuns runs_;
ParagraphStyle paragraph_style_;
FontCollection* font_collection_;
std::shared_ptr<FontCollection> font_collection_;
minikin::LineBreaker breaker_;
@@ -215,12 +217,10 @@ class Paragraph {
void SetParagraphStyle(const ParagraphStyle& style);
void SetFontCollection(FontCollection* font_collection);
void SetFontCollection(std::shared_ptr<FontCollection> font_collection);
// Pass the runs to breaker_.
// NOTE: This is O(N^2) due to minikin breaking being O(N^2) where N = sum of
// all text added using this method. This is insignificant with normal usage.
void AddRunsToLineBreaker(
FTL_WARN_UNUSED_RESULT
bool AddRunsToLineBreaker(
std::unordered_map<std::string, std::shared_ptr<minikin::FontCollection>>&
collection_map);

View File

@@ -23,17 +23,14 @@
namespace txt {
ParagraphBuilder::ParagraphBuilder(ParagraphStyle style,
FontCollection* font_collection)
: font_collection_(font_collection) {
ParagraphBuilder::ParagraphBuilder(
ParagraphStyle style,
std::shared_ptr<FontCollection> font_collection)
: font_collection_(std::move(font_collection)) {
SetParagraphStyle(style);
}
ParagraphBuilder::ParagraphBuilder(ParagraphStyle style) {
SetParagraphStyle(style);
}
ParagraphBuilder::ParagraphBuilder() {}
ParagraphBuilder::~ParagraphBuilder() = default;
void ParagraphBuilder::SetParagraphStyle(const ParagraphStyle& style) {
paragraph_style_ = style;
@@ -46,12 +43,6 @@ void ParagraphBuilder::SetParagraphStyle(const ParagraphStyle& style) {
PushStyle(text_style);
}
void ParagraphBuilder::SetFontCollection(FontCollection* font_collection) {
font_collection_ = font_collection;
}
ParagraphBuilder::~ParagraphBuilder() = default;
void ParagraphBuilder::PushStyle(const TextStyle& style) {
const size_t text_index = text_.size();
runs_.EndRunIfNeeded(text_index);
@@ -106,12 +97,6 @@ void ParagraphBuilder::SplitNewlineRuns() {
}
std::unique_ptr<Paragraph> ParagraphBuilder::Build() {
if (font_collection_ == nullptr) {
// Will be deprecated when full compatibility with Flutter Engine is
// complete.
font_collection_ = &FontCollection::GetFontCollection("");
}
runs_.EndRunIfNeeded(text_.size());
SplitNewlineRuns();

View File

@@ -31,11 +31,8 @@ namespace txt {
class ParagraphBuilder {
public:
explicit ParagraphBuilder(ParagraphStyle style);
ParagraphBuilder(ParagraphStyle style, FontCollection* font_collection);
ParagraphBuilder();
ParagraphBuilder(ParagraphStyle style,
std::shared_ptr<FontCollection> font_collection);
~ParagraphBuilder();
@@ -71,10 +68,6 @@ class ParagraphBuilder {
void SetParagraphStyle(const ParagraphStyle& style);
// It is recommended to initialize the ParagraphBuilder with a font collection
// as default font collection fallback will be deprecated.
void SetFontCollection(FontCollection* font_collection);
// Constructs a Paragraph object that can be used to layout and paint the text
// to a SkCanvas.
std::unique_ptr<Paragraph> Build();
@@ -82,9 +75,9 @@ class ParagraphBuilder {
private:
std::vector<uint16_t> text_;
std::vector<size_t> style_stack_;
std::shared_ptr<FontCollection> font_collection_;
StyledRuns runs_;
ParagraphStyle paragraph_style_;
FontCollection* font_collection_ = nullptr;
// Break any newline '\n' characters into their own runs. This allows
// Paragraph::Layout to cleanly discover and handle newlines.

View File

@@ -64,23 +64,23 @@ class StyledRuns {
void SplitNewlineRuns(std::list<size_t> newline_positions);
private:
FRIEND_TEST(RenderTest, SimpleParagraph);
FRIEND_TEST(RenderTest, SimpleRedParagraph);
FRIEND_TEST(RenderTest, RainbowParagraph);
FRIEND_TEST(RenderTest, DefaultStyleParagraph);
FRIEND_TEST(RenderTest, BoldParagraph);
FRIEND_TEST(RenderTest, LeftAlignParagraph);
FRIEND_TEST(RenderTest, RightAlignParagraph);
FRIEND_TEST(RenderTest, CenterAlignParagraph);
FRIEND_TEST(RenderTest, JustifyAlignParagraph);
FRIEND_TEST(RenderTest, DecorationsParagraph);
FRIEND_TEST(RenderTest, ItalicsParagraph);
FRIEND_TEST(RenderTest, ChineseParagraph);
FRIEND_TEST(RenderTest, DISABLED_ArabicParagraph);
FRIEND_TEST(RenderTest, LongWordParagraph);
FRIEND_TEST(RenderTest, KernParagraph);
FRIEND_TEST(RenderTest, HyphenBreakParagraph);
FRIEND_TEST(RenderTest, RepeatLayoutParagraph);
FRIEND_TEST(ParagraphTest, SimpleParagraph);
FRIEND_TEST(ParagraphTest, SimpleRedParagraph);
FRIEND_TEST(ParagraphTest, RainbowParagraph);
FRIEND_TEST(ParagraphTest, DefaultStyleParagraph);
FRIEND_TEST(ParagraphTest, BoldParagraph);
FRIEND_TEST(ParagraphTest, LeftAlignParagraph);
FRIEND_TEST(ParagraphTest, RightAlignParagraph);
FRIEND_TEST(ParagraphTest, CenterAlignParagraph);
FRIEND_TEST(ParagraphTest, JustifyAlignParagraph);
FRIEND_TEST(ParagraphTest, DecorationsParagraph);
FRIEND_TEST(ParagraphTest, ItalicsParagraph);
FRIEND_TEST(ParagraphTest, ChineseParagraph);
FRIEND_TEST(ParagraphTest, DISABLED_ArabicParagraph);
FRIEND_TEST(ParagraphTest, LongWordParagraph);
FRIEND_TEST(ParagraphTest, KernParagraph);
FRIEND_TEST(ParagraphTest, HyphenBreakParagraph);
FRIEND_TEST(ParagraphTest, RepeatLayoutParagraph);
struct IndexedRun {
size_t style_index = 0;

View File

@@ -14,13 +14,19 @@
* limitations under the License.
*/
#include "text_style.h"
#include "font_style.h"
#include "font_weight.h"
#include "text_style.h"
#include "third_party/skia/include/core/SkColor.h"
namespace txt {
std::string TextStyle::GetDefaultFontFamily() {
return "Roboto";
}
TextStyle::TextStyle() : font_family(GetDefaultFontFamily()) {}
bool TextStyle::equals(const TextStyle& other) const {
if (color != other.color)
return false;

View File

@@ -40,12 +40,16 @@ class TextStyle {
FontWeight font_weight = FontWeight::w400;
FontStyle font_style = FontStyle::normal;
TextBaseline text_baseline = TextBaseline::kAlphabetic;
std::string font_family = "";
std::string font_family;
double font_size = 14.0;
double letter_spacing = 0.0;
double word_spacing = 0.0;
double height = 1.0;
static std::string GetDefaultFontFamily();
TextStyle();
bool equals(const TextStyle& other) const;
};

View File

@@ -22,6 +22,8 @@
namespace txt {
#if 0
TEST(FontCollection, HasDefaultRegistrations) {
std::string defaultFamilyName = txt::FontCollection::GetDefaultFamilyName();
@@ -95,4 +97,6 @@ TEST(FontCollection, GetFamilyNames) {
ASSERT_EQ(names.count("Another Fake Font"), 0ull);
}
#endif // 0
} // namespace txt

View File

@@ -27,15 +27,16 @@
namespace txt {
TEST_F(RenderTest, SimpleParagraph) {
using ParagraphTest = RenderTest;
TEST_F(ParagraphTest, SimpleParagraph) {
const char* text = "Hello World Text Dialog";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorBLACK;
@@ -60,15 +61,14 @@ TEST_F(RenderTest, SimpleParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, SimpleRedParagraph) {
TEST_F(ParagraphTest, SimpleRedParagraph) {
const char* text = "I am RED";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorRED;
@@ -94,7 +94,7 @@ TEST_F(RenderTest, SimpleRedParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, RainbowParagraph) {
TEST_F(ParagraphTest, RainbowParagraph) {
const char* text1 = "Red Roboto";
auto icu_text1 = icu::UnicodeString::fromUTF8(text1);
std::u16string u16_text1(icu_text1.getBuffer(),
@@ -121,8 +121,7 @@ TEST_F(RenderTest, RainbowParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 2;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style1;
text_style1.color = SK_ColorRED;
@@ -188,15 +187,14 @@ TEST_F(RenderTest, RainbowParagraph) {
}
// Currently, this should render nothing without a supplied TextStyle.
TEST_F(RenderTest, DefaultStyleParagraph) {
TEST_F(ParagraphTest, DefaultStyleParagraph) {
const char* text = "No TextStyle! Uh Oh!";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorRED;
@@ -219,15 +217,14 @@ TEST_F(RenderTest, DefaultStyleParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, BoldParagraph) {
TEST_F(ParagraphTest, BoldParagraph) {
const char* text = "This is Red max bold text!";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Roboto";
@@ -257,7 +254,7 @@ TEST_F(RenderTest, BoldParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, LeftAlignParagraph) {
TEST_F(ParagraphTest, LeftAlignParagraph) {
const char* text =
"This is a very long sentence to test if the text will properly wrap "
"around and go to the next line. Sometimes, short sentence. Longer "
@@ -283,8 +280,7 @@ TEST_F(RenderTest, LeftAlignParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 26;
@@ -354,7 +350,7 @@ TEST_F(RenderTest, LeftAlignParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, RightAlignParagraph) {
TEST_F(ParagraphTest, RightAlignParagraph) {
const char* text =
"This is a very long sentence to test if the text will properly wrap "
"around and go to the next line. Sometimes, short sentence. Longer "
@@ -380,8 +376,7 @@ TEST_F(RenderTest, RightAlignParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::right;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 26;
@@ -458,7 +453,7 @@ TEST_F(RenderTest, RightAlignParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, CenterAlignParagraph) {
TEST_F(ParagraphTest, CenterAlignParagraph) {
const char* text =
"This is a very long sentence to test if the text will properly wrap "
"around and go to the next line. Sometimes, short sentence. Longer "
@@ -484,8 +479,7 @@ TEST_F(RenderTest, CenterAlignParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::center;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 26;
@@ -566,7 +560,7 @@ TEST_F(RenderTest, CenterAlignParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, JustifyAlignParagraph) {
TEST_F(ParagraphTest, JustifyAlignParagraph) {
const char* text =
"This is a very long sentence to test if the text will properly wrap "
"around and go to the next line. Sometimes, short sentence. Longer "
@@ -590,8 +584,7 @@ TEST_F(RenderTest, JustifyAlignParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::justify;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 26;
@@ -653,12 +646,11 @@ TEST_F(RenderTest, JustifyAlignParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, DecorationsParagraph) {
TEST_F(ParagraphTest, DecorationsParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 26;
@@ -730,10 +722,9 @@ TEST_F(RenderTest, DecorationsParagraph) {
ASSERT_EQ(paragraph->records_[5].style().decoration_color, SK_ColorRED);
}
TEST_F(RenderTest, ItalicsParagraph) {
TEST_F(ParagraphTest, ItalicsParagraph) {
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorRED;
@@ -762,7 +753,7 @@ TEST_F(RenderTest, ItalicsParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, ChineseParagraph) {
TEST_F(ParagraphTest, ChineseParagraph) {
const char* text =
"左線読設重説切後碁給能上目秘使約。満毎冠行来昼本可必図将発確年。今属場育"
"図情闘陰野高備込制詩西校客。審対江置講今固残必託地集済決維駆年策。立得庭"
@@ -776,8 +767,7 @@ TEST_F(RenderTest, ChineseParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::justify;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorBLACK;
@@ -808,7 +798,7 @@ TEST_F(RenderTest, ChineseParagraph) {
}
// TODO(garyq): Support RTL languages.
TEST_F(RenderTest, DISABLED_ArabicParagraph) {
TEST_F(ParagraphTest, DISABLED_ArabicParagraph) {
const char* text =
"من أسر وإعلان الخاصّة وهولندا،, عل قائمة الضغوط بالمطالبة تلك. الصفحة "
"بمباركة التقليدية قام عن. تصفح";
@@ -820,8 +810,7 @@ TEST_F(RenderTest, DISABLED_ArabicParagraph) {
paragraph_style.max_lines = 14;
paragraph_style.text_align = TextAlign::right;
paragraph_style.rtl = true;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorBLACK;
@@ -858,7 +847,7 @@ TEST_F(RenderTest, DISABLED_ArabicParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, GetGlyphPositionAtCoordinateParagraph) {
TEST_F(ParagraphTest, GetGlyphPositionAtCoordinateParagraph) {
const char* text =
"12345 67890 12345 67890 12345 67890 12345 67890 12345 67890 12345 "
"67890 12345";
@@ -869,8 +858,7 @@ TEST_F(RenderTest, GetGlyphPositionAtCoordinateParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 10;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 50;
@@ -920,7 +908,7 @@ TEST_F(RenderTest, GetGlyphPositionAtCoordinateParagraph) {
ASSERT_EQ(paragraph->GetGlyphPositionAtCoordinate(85, 10000), 74ull);
}
TEST_F(RenderTest, GetRectsForRangeParagraph) {
TEST_F(ParagraphTest, GetRectsForRangeParagraph) {
const char* text =
"12345, \"67890\" 12345 67890 12345 67890 12345 67890 12345 67890 12345 "
"67890 12345";
@@ -931,8 +919,7 @@ TEST_F(RenderTest, GetRectsForRangeParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 10;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 50;
@@ -1062,7 +1049,7 @@ TEST_F(RenderTest, GetRectsForRangeParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, GetWordBoundaryParagraph) {
TEST_F(ParagraphTest, GetWordBoundaryParagraph) {
const char* text =
"12345 67890 12345 67890 12345 67890 12345 67890 12345 67890 12345 "
"67890 12345";
@@ -1073,8 +1060,7 @@ TEST_F(RenderTest, GetWordBoundaryParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 10;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 52;
@@ -1161,7 +1147,7 @@ TEST_F(RenderTest, GetWordBoundaryParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, SpacingParagraph) {
TEST_F(ParagraphTest, SpacingParagraph) {
const char* text = "H";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
@@ -1170,8 +1156,7 @@ TEST_F(RenderTest, SpacingParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.max_lines = 10;
paragraph_style.text_align = TextAlign::left;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_size = 50;
@@ -1248,7 +1233,7 @@ TEST_F(RenderTest, SpacingParagraph) {
ASSERT_EQ(paragraph->records_[6].style().word_spacing, 20);
}
TEST_F(RenderTest, LongWordParagraph) {
TEST_F(ParagraphTest, LongWordParagraph) {
const char* text =
"A "
"veryverylongwordtoseewherethiswillwraporifitwillatallandifitdoesthenthat"
@@ -1259,8 +1244,7 @@ TEST_F(RenderTest, LongWordParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.break_strategy = minikin::kBreakStrategy_HighQuality;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Roboto";
@@ -1292,13 +1276,12 @@ TEST_F(RenderTest, LongWordParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, KernScaleParagraph) {
TEST_F(ParagraphTest, KernScaleParagraph) {
float scale = 3.0f;
txt::ParagraphStyle paragraph_style;
paragraph_style.break_strategy = minikin::kBreakStrategy_HighQuality;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Droid Serif";
@@ -1335,11 +1318,11 @@ TEST_F(RenderTest, KernScaleParagraph) {
EXPECT_DOUBLE_EQ(paragraph->records_[4].offset().x(), 253.36328125f);
}
TEST_F(RenderTest, NewlineParagraph) {
TEST_F(ParagraphTest, NewlineParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.break_strategy = minikin::kBreakStrategy_HighQuality;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Roboto";
@@ -1390,7 +1373,7 @@ TEST_F(RenderTest, NewlineParagraph) {
EXPECT_DOUBLE_EQ(paragraph->records_[8].offset().y(), 406);
}
TEST_F(RenderTest, EmojiParagraph) {
TEST_F(ParagraphTest, EmojiParagraph) {
const char* text =
"😀😃😄😁😆😅😂🤣☺😇🙂😍😡😟😢😻👽💩👍👎🙏👌👋👄👁👦👼👨‍🚀👨‍🚒🙋‍♂️👳👨‍👨‍👧‍👧\
💼👡👠☂🐶🐰🐻🐼🐷🐒🐵🐔🐧🐦🐋🐟🐡🕸🐌🐴🐊🐄🐪🐘🌸🌏🔥🌟🌚🌝💦💧\
@@ -1401,8 +1384,8 @@ TEST_F(RenderTest, EmojiParagraph) {
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.color = SK_ColorBLACK;
@@ -1418,9 +1401,13 @@ TEST_F(RenderTest, EmojiParagraph) {
paragraph->Layout(GetTestCanvasWidth());
paragraph->Paint(GetCanvas(), 0, 0);
ASSERT_TRUE(Snapshot());
for (size_t i = 0; i < u16_text.length(); i++) {
ASSERT_EQ(paragraph->text_[i], u16_text[i]);
}
ASSERT_EQ(paragraph->records_.size(), 8ull);
EXPECT_EQ(paragraph->records_[0].line(), 0ull);
@@ -1428,14 +1415,9 @@ TEST_F(RenderTest, EmojiParagraph) {
EXPECT_EQ(paragraph->records_[2].line(), 2ull);
EXPECT_EQ(paragraph->records_[3].line(), 3ull);
EXPECT_EQ(paragraph->records_[7].line(), 7ull);
// TODO(garyq): Add more robust tests for emojis, currently, look at the
// resulting file to check if emojis are drawn properly.
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, HyphenBreakParagraph) {
TEST_F(ParagraphTest, HyphenBreakParagraph) {
const char* text =
"A "
"very-very-long-Hyphen-word-to-see-where-this-will-wrap-or-if-it-will-at-"
@@ -1447,8 +1429,8 @@ TEST_F(RenderTest, HyphenBreakParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.break_strategy = minikin::kBreakStrategy_HighQuality;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Roboto";
@@ -1480,7 +1462,7 @@ TEST_F(RenderTest, HyphenBreakParagraph) {
ASSERT_TRUE(Snapshot());
}
TEST_F(RenderTest, RepeatLayoutParagraph) {
TEST_F(ParagraphTest, RepeatLayoutParagraph) {
const char* text =
"Sentence to layout at diff widths to get diff line counts. short words "
"short words short words short words short words short words short words "
@@ -1491,8 +1473,7 @@ TEST_F(RenderTest, RepeatLayoutParagraph) {
txt::ParagraphStyle paragraph_style;
paragraph_style.break_strategy = minikin::kBreakStrategy_HighQuality;
auto font_collection = FontCollection::GetFontCollection(txt::GetFontDir());
txt::ParagraphBuilder builder(paragraph_style, &font_collection);
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_family = "Roboto";

View File

@@ -21,10 +21,20 @@
#include "lib/ftl/logging.h"
#include "third_party/skia/include/core/SkImageEncoder.h"
#include "third_party/skia/include/core/SkStream.h"
#include "txt/asset_font_manager.h"
#include "txt/directory_asset_data_provider.h"
#include "txt/font_collection.h"
#include "utils.h"
RenderTest::RenderTest() : snapshots_(0) {}
namespace txt {
RenderTest::~RenderTest() {}
RenderTest::RenderTest()
: snapshots_(0), font_collection_(std::make_shared<FontCollection>()) {
font_collection_->PushBack(sk_make_sp<AssetFontManager>(
std::make_unique<txt::DirectoryAssetDataProvider>(GetFontDir())));
}
RenderTest::~RenderTest() = default;
SkCanvas* RenderTest::GetCanvas() {
return canvas_ == nullptr ? nullptr : canvas_.get();
@@ -82,7 +92,13 @@ void RenderTest::SetUp() {
canvas_->clear(SK_ColorWHITE);
}
std::shared_ptr<FontCollection> RenderTest::GetTestFontCollection() const {
return font_collection_;
}
void RenderTest::TearDown() {
canvas_ = nullptr;
bitmap_ = nullptr;
}
} // namespace txt

View File

@@ -16,11 +16,13 @@
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "lib/ftl/macros.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "txt/font_collection.h"
namespace txt {
class RenderTest : public ::testing::Test {
public:
@@ -36,6 +38,8 @@ class RenderTest : public ::testing::Test {
size_t GetTestCanvasHeight() const;
std::shared_ptr<txt::FontCollection> GetTestFontCollection() const;
protected:
void SetUp() override;
@@ -45,8 +49,11 @@ class RenderTest : public ::testing::Test {
size_t snapshots_;
std::unique_ptr<SkBitmap> bitmap_;
std::unique_ptr<SkCanvas> canvas_;
std::shared_ptr<txt::FontCollection> font_collection_;
std::string GetNextSnapshotName();
FTL_DISALLOW_COPY_AND_ASSIGN(RenderTest);
};
} // namespace txt

View File

@@ -24,7 +24,7 @@ namespace txt {
static std::string gFontDir;
static ftl::CommandLine gCommandLine;
const std::string GetFontDir() {
const std::string& GetFontDir() {
return gFontDir;
}

View File

@@ -20,7 +20,7 @@
namespace txt {
const std::string GetFontDir();
const std::string& GetFontDir();
void SetFontDir(const std::string& dir);