From 1245043020382e990b3bc9e619fe3d96bd69d0af Mon Sep 17 00:00:00 2001 From: Jonah Williams Date: Mon, 8 Aug 2022 11:06:05 -0700 Subject: [PATCH] Support hot reload of asset fonts (flutter/engine#35213) --- .../flutter/lib/ui/text/font_collection.cc | 18 ++++- .../src/flutter/runtime/service_protocol.cc | 3 + engine/src/flutter/runtime/service_protocol.h | 1 + engine/src/flutter/shell/common/shell.cc | 61 +++++++++++---- engine/src/flutter/shell/common/shell.h | 11 +++ .../observatory/vmservice_methods_test.dart | 77 +++++++++++++++++-- 6 files changed, 145 insertions(+), 26 deletions(-) diff --git a/engine/src/flutter/lib/ui/text/font_collection.cc b/engine/src/flutter/lib/ui/text/font_collection.cc index 3ca89d964d..3a5327b6fe 100644 --- a/engine/src/flutter/lib/ui/text/font_collection.cc +++ b/engine/src/flutter/lib/ui/text/font_collection.cc @@ -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 asset_manager) { std::unique_ptr manifest_mapping = @@ -65,8 +81,6 @@ void FontCollection::RegisterFonts( return; } - // Structure described in https://flutter.io/custom-fonts/ - if (!document.IsArray()) { return; } diff --git a/engine/src/flutter/runtime/service_protocol.cc b/engine/src/flutter/runtime/service_protocol.cc index 3a9c0d6e36..0f25565ada 100644 --- a/engine/src/flutter/runtime/service_protocol.cc +++ b/engine/src/flutter/runtime/service_protocol.cc @@ -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()) {} diff --git a/engine/src/flutter/runtime/service_protocol.h b/engine/src/flutter/runtime/service_protocol.h index e9df73d4d5..dc3a4d186e 100644 --- a/engine/src/flutter/runtime/service_protocol.h +++ b/engine/src/flutter/runtime/service_protocol.h @@ -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: diff --git a/engine/src/flutter/shell/common/shell.cc b/engine/src/flutter/shell/common/shell.cc index e0931d1728..6c80032b46 100644 --- a/engine/src/flutter/shell/common/shell.cc +++ b/engine/src/flutter/shell/common/shell.cc @@ -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 writer(buffer); + document.Accept(writer); + std::string message = buffer.GetString(); + std::unique_ptr fontsChangeMessage = + std::make_unique( + 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 writer(buffer); - document.Accept(writer); - std::string message = buffer.GetString(); - std::unique_ptr fontsChangeMessage = - std::make_unique( - kSystemChannel, - fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr); - - OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage)); + SendFontChangeNotification(); return true; } diff --git a/engine/src/flutter/shell/common/shell.h b/engine/src/flutter/shell/common/shell.h index 75761b9177..051e1a9c5d 100644 --- a/engine/src/flutter/shell/common/shell.h +++ b/engine/src/flutter/shell/common/shell.h @@ -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_; }; diff --git a/engine/src/flutter/testing/dart/observatory/vmservice_methods_test.dart b/engine/src/flutter/testing/dart/observatory/vmservice_methods_test.dart index a6491797f2..ed62cb80cc 100644 --- a/engine/src/flutter/testing/dart/observatory/vmservice_methods_test.dart +++ b/engine/src/flutter/testing/dart/observatory/vmservice_methods_test.dart @@ -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? rawViews = response.json!['views'] as List?; - final String viewId = (rawViews![0]! as Map?)!['id']! as String; + final String viewId = await getViewId(vmService); dynamic error; try { await vmService.callMethod( '_flutter.setAssetBundlePath', - args: { - 'viewId': viewId, - 'assetDirectory': '' - }, + args: {'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 completer = Completer(); + 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: {'viewId': viewId}, + ); + + expect(fontChangeResponse.type, 'Success'); + expect( + await completer.future, + const PlatformResponse( + name: 'flutter/system', + contents: '{"type":"fontsChange"}', + ), + ); + } finally { + await vmService?.dispose(); + } + }); +} + +Future getViewId(vms.VmService vmService) async { + final vms.Response response = await vmService.callMethod('_flutter.listViews'); + final List? rawViews = response.json!['views'] as List?; + return (rawViews![0]! as Map?)!['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); }