Support hot reload of asset fonts (flutter/engine#35213)

This commit is contained in:
Jonah Williams
2022-08-08 11:06:05 -07:00
committed by GitHub
parent 0589683136
commit 1245043020
6 changed files with 145 additions and 26 deletions

View File

@@ -45,6 +45,22 @@ void FontCollection::SetupDefaultFontManager(
collection_->SetupDefaultFontManager(font_initialization_data);
}
// Font manifest yaml format:
//
// flutter:
// fonts:
// - family: Raleway
// fonts:
// - asset: fonts/Raleway-Regular.ttf
// - asset: fonts/Raleway-Italic.ttf
// style: italic
// - family: RobotoMono
// fonts:
// - asset: fonts/RobotoMono-Regular.ttf
// - asset: fonts/RobotoMono-Bold.ttf
// weight: 700
//
// Structure described in https://docs.flutter.dev/cookbook/design/fonts
void FontCollection::RegisterFonts(
std::shared_ptr<AssetManager> asset_manager) {
std::unique_ptr<fml::Mapping> manifest_mapping =
@@ -65,8 +81,6 @@ void FontCollection::RegisterFonts(
return;
}
// Structure described in https://flutter.io/custom-fonts/
if (!document.IsArray()) {
return;
}

View File

@@ -40,6 +40,8 @@ const std::string_view
const std::string_view
ServiceProtocol::kRenderFrameWithRasterStatsExtensionName =
"_flutter.renderFrameWithRasterStats";
const std::string_view ServiceProtocol::kReloadAssetFonts =
"_flutter.reloadAssetFonts";
static constexpr std::string_view kViewIdPrefx = "_flutterView/";
static constexpr std::string_view kListViewsExtensionName =
@@ -60,6 +62,7 @@ ServiceProtocol::ServiceProtocol()
kGetSkSLsExtensionName,
kEstimateRasterCacheMemoryExtensionName,
kRenderFrameWithRasterStatsExtensionName,
kReloadAssetFonts,
}),
handlers_mutex_(fml::SharedMutex::Create()) {}

View File

@@ -30,6 +30,7 @@ class ServiceProtocol {
static const std::string_view kGetSkSLsExtensionName;
static const std::string_view kEstimateRasterCacheMemoryExtensionName;
static const std::string_view kRenderFrameWithRasterStatsExtensionName;
static const std::string_view kReloadAssetFonts;
class Handler {
public:

View File

@@ -454,6 +454,10 @@ Shell::Shell(DartVMRef vm,
task_runners_.GetRasterTaskRunner(),
std::bind(&Shell::OnServiceProtocolRenderFrameWithRasterStats, this,
std::placeholders::_1, std::placeholders::_2)};
service_protocol_handlers_[ServiceProtocol::kReloadAssetFonts] = {
task_runners_.GetPlatformTaskRunner(),
std::bind(&Shell::OnServiceProtocolReloadAssetFonts, this,
std::placeholders::_1, std::placeholders::_2)};
}
Shell::~Shell() {
@@ -1900,6 +1904,45 @@ bool Shell::OnServiceProtocolRenderFrameWithRasterStats(
}
}
void Shell::SendFontChangeNotification() {
// After system fonts are reloaded, we send a system channel message
// to notify flutter framework.
rapidjson::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
rapidjson::Value message_value;
message_value.SetString(kFontChange, allocator);
document.AddMember(kTypeKey, message_value, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string message = buffer.GetString();
std::unique_ptr<PlatformMessage> fontsChangeMessage =
std::make_unique<flutter::PlatformMessage>(
kSystemChannel,
fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr);
OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage));
}
bool Shell::OnServiceProtocolReloadAssetFonts(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response) {
FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());
if (!engine_) {
return false;
}
engine_->GetFontCollection().RegisterFonts(engine_->GetAssetManager());
engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
SendFontChangeNotification();
auto& allocator = response->GetAllocator();
response->SetObject();
response->AddMember("type", "Success", allocator);
return true;
}
Rasterizer::Screenshot Shell::Screenshot(
Rasterizer::ScreenshotType screenshot_type,
bool base64_encode) {
@@ -1962,23 +2005,7 @@ bool Shell::ReloadSystemFonts() {
engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache();
// After system fonts are reloaded, we send a system channel message
// to notify flutter framework.
rapidjson::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
rapidjson::Value message_value;
message_value.SetString(kFontChange, allocator);
document.AddMember(kTypeKey, message_value, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string message = buffer.GetString();
std::unique_ptr<PlatformMessage> fontsChangeMessage =
std::make_unique<flutter::PlatformMessage>(
kSystemChannel,
fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr);
OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage));
SendFontChangeNotification();
return true;
}

View File

@@ -714,6 +714,17 @@ class Shell final : public PlatformView::Delegate,
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Service protocol handler
//
// Forces the FontCollection to reload the font manifest. Used to support hot
// reload for fonts.
bool OnServiceProtocolReloadAssetFonts(
const ServiceProtocol::Handler::ServiceProtocolMap& params,
rapidjson::Document* response);
// Send a system font change notification.
void SendFontChangeNotification();
// |ResourceCacheLimitItem|
size_t GetResourceCacheLimit() override { return resource_cache_limit_; };

View File

@@ -2,7 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:litetest/litetest.dart';
import 'package:vm_service/vm_service.dart' as vms;
@@ -20,18 +24,13 @@ void main() {
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final vms.Response response = await vmService.callMethod('_flutter.listViews');
final List<Object?>? rawViews = response.json!['views'] as List<Object?>?;
final String viewId = (rawViews![0]! as Map<String, Object?>?)!['id']! as String;
final String viewId = await getViewId(vmService);
dynamic error;
try {
await vmService.callMethod(
'_flutter.setAssetBundlePath',
args: <String, Object>{
'viewId': viewId,
'assetDirectory': ''
},
args: <String, Object>{'viewId': viewId, 'assetDirectory': ''},
);
} catch (err) {
error = err;
@@ -41,4 +40,68 @@ void main() {
await vmService?.dispose();
}
});
test('Reload fonts request sends font change notification', () async {
vms.VmService? vmService;
try {
final developer.ServiceProtocolInfo info =
await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test must not be run with --disable-observatory.');
}
final Completer<PlatformResponse> completer = Completer<PlatformResponse>();
ui.window.onPlatformMessage = (String name, ByteData? data, ui.PlatformMessageResponseCallback? callback) {
final ByteBuffer buffer = data!.buffer;
final Uint8List list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
completer.complete(PlatformResponse(name: name, contents: utf8.decode(list)));
};
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
final String viewId = await getViewId(vmService);
final vms.Response fontChangeResponse = await vmService.callMethod(
'_flutter.reloadAssetFonts',
args: <String, Object>{'viewId': viewId},
);
expect(fontChangeResponse.type, 'Success');
expect(
await completer.future,
const PlatformResponse(
name: 'flutter/system',
contents: '{"type":"fontsChange"}',
),
);
} finally {
await vmService?.dispose();
}
});
}
Future<String> getViewId(vms.VmService vmService) async {
final vms.Response response = await vmService.callMethod('_flutter.listViews');
final List<Object?>? rawViews = response.json!['views'] as List<Object?>?;
return (rawViews![0]! as Map<String, Object?>?)!['id']! as String;
}
class PlatformResponse {
const PlatformResponse({
required this.name,
required this.contents,
});
final String name;
final String contents;
@override
bool operator ==(Object other) =>
other is PlatformResponse &&
other.name == name &&
other.contents == contents;
@override
int get hashCode => Object.hash(name, contents);
}