Copy the Flutter Runner from //topaz into the engine. (flutter/engine#8886)

Build rules and include paths have been updated as necessary.
No other functional change.
This commit is contained in:
Chinmay Garde
2019-05-07 17:24:18 -07:00
committed by GitHub
parent c96714ac5d
commit 8ef9d87c66
75 changed files with 13311 additions and 2 deletions

View File

@@ -715,6 +715,13 @@ FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.cc
FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.h
FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.cc
FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.h
FILE: ../../../flutter/shell/platform/fuchsia/collect_traces.dart
FILE: ../../../flutter/shell/platform/fuchsia/component.cc
FILE: ../../../flutter/shell/platform/fuchsia/component.h
FILE: ../../../flutter/shell/platform/fuchsia/compositor_context.cc
FILE: ../../../flutter/shell/platform/fuchsia/compositor_context.h
FILE: ../../../flutter/shell/platform/fuchsia/context_writer_bridge.cc
FILE: ../../../flutter/shell/platform/fuchsia/context_writer_bridge.h
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h
@@ -730,6 +737,35 @@ FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h
FILE: ../../../flutter/shell/platform/fuchsia/engine.cc
FILE: ../../../flutter/shell/platform/fuchsia/engine.h
FILE: ../../../flutter/shell/platform/fuchsia/fuchsia_font_manager.cc
FILE: ../../../flutter/shell/platform/fuchsia/fuchsia_font_manager.h
FILE: ../../../flutter/shell/platform/fuchsia/fuchsia_font_manager_unittest.cc
FILE: ../../../flutter/shell/platform/fuchsia/isolate_configurator.cc
FILE: ../../../flutter/shell/platform/fuchsia/isolate_configurator.h
FILE: ../../../flutter/shell/platform/fuchsia/kernel/extract_far.dart
FILE: ../../../flutter/shell/platform/fuchsia/kernel/framework_shim.dart
FILE: ../../../flutter/shell/platform/fuchsia/kernel/libraries.json
FILE: ../../../flutter/shell/platform/fuchsia/logging.h
FILE: ../../../flutter/shell/platform/fuchsia/loop.cc
FILE: ../../../flutter/shell/platform/fuchsia/loop.h
FILE: ../../../flutter/shell/platform/fuchsia/main.cc
FILE: ../../../flutter/shell/platform/fuchsia/meta/aot_product_runtime
FILE: ../../../flutter/shell/platform/fuchsia/meta/aot_runtime
FILE: ../../../flutter/shell/platform/fuchsia/meta/flutter_aot_product_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/meta/flutter_aot_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/meta/flutter_jit_product_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/meta/flutter_jit_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/meta/flutter_runner_tests.cmx
FILE: ../../../flutter/shell/platform/fuchsia/meta/jit_product_runtime
FILE: ../../../flutter/shell/platform/fuchsia/meta/jit_runtime
FILE: ../../../flutter/shell/platform/fuchsia/platform_view.cc
FILE: ../../../flutter/shell/platform/fuchsia/platform_view.h
FILE: ../../../flutter/shell/platform/fuchsia/runner.cc
FILE: ../../../flutter/shell/platform/fuchsia/runner.h
FILE: ../../../flutter/shell/platform/fuchsia/runner_context.cc
FILE: ../../../flutter/shell/platform/fuchsia/runner_context.h
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/files.cc
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/files.h
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc
@@ -742,6 +778,29 @@ FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.cc
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/vmo.h
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc
FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.h
FILE: ../../../flutter/shell/platform/fuchsia/service_provider_dir.cc
FILE: ../../../flutter/shell/platform/fuchsia/service_provider_dir.h
FILE: ../../../flutter/shell/platform/fuchsia/session_connection.cc
FILE: ../../../flutter/shell/platform/fuchsia/session_connection.h
FILE: ../../../flutter/shell/platform/fuchsia/surface.cc
FILE: ../../../flutter/shell/platform/fuchsia/surface.h
FILE: ../../../flutter/shell/platform/fuchsia/task_observers.cc
FILE: ../../../flutter/shell/platform/fuchsia/task_observers.h
FILE: ../../../flutter/shell/platform/fuchsia/task_runner_adapter.cc
FILE: ../../../flutter/shell/platform/fuchsia/task_runner_adapter.h
FILE: ../../../flutter/shell/platform/fuchsia/thread.cc
FILE: ../../../flutter/shell/platform/fuchsia/thread.h
FILE: ../../../flutter/shell/platform/fuchsia/unique_fdio_ns.h
FILE: ../../../flutter/shell/platform/fuchsia/vsync_recorder.cc
FILE: ../../../flutter/shell/platform/fuchsia/vsync_recorder.h
FILE: ../../../flutter/shell/platform/fuchsia/vsync_waiter.cc
FILE: ../../../flutter/shell/platform/fuchsia/vsync_waiter.h
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface.cc
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface.h
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface_pool.cc
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface_pool.h
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface_producer.cc
FILE: ../../../flutter/shell/platform/fuchsia/vulkan_surface_producer.h
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/flutter_window_controller.cc
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window.h

View File

@@ -26,7 +26,9 @@ group("platform") {
]
} else if (is_fuchsia) {
# Fuchsia has its own runner implementation.
deps = []
deps = [
"fuchsia",
]
} else {
assert(false, "Unknown/Unsupported platform.")
}

View File

@@ -0,0 +1,91 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_fuchsia)
import("//build/fuchsia/sdk.gni")
executable("fuchsia") {
output_name = "four_gate"
sources = [
"component.cc",
"component.h",
"compositor_context.cc",
"compositor_context.h",
"context_writer_bridge.cc",
"context_writer_bridge.h",
"engine.cc",
"engine.h",
"fuchsia_font_manager.cc",
"fuchsia_font_manager.h",
"isolate_configurator.cc",
"isolate_configurator.h",
"logging.h",
"loop.cc",
"loop.h",
"main.cc",
"platform_view.cc",
"platform_view.h",
"runner.cc",
"runner.h",
"runner_context.cc",
"runner_context.h",
"service_provider_dir.cc",
"service_provider_dir.h",
"session_connection.cc",
"session_connection.h",
"surface.cc",
"surface.h",
"task_observers.cc",
"task_observers.h",
"task_runner_adapter.cc",
"task_runner_adapter.h",
"thread.cc",
"thread.h",
"unique_fdio_ns.h",
"vsync_recorder.cc",
"vsync_recorder.h",
"vsync_waiter.cc",
"vsync_waiter.h",
"vulkan_surface.cc",
"vulkan_surface.h",
"vulkan_surface_pool.cc",
"vulkan_surface_pool.h",
"vulkan_surface_producer.cc",
"vulkan_surface_producer.h",
]
deps = [
"$flutter_root/common",
"$flutter_root/flow",
"$flutter_root/fml",
"$flutter_root/lib/ui",
"$flutter_root/runtime",
"$flutter_root/runtime:libdart",
"$flutter_root/shell/common",
"$flutter_root/vulkan",
"$fuchsia_sdk_root/fidl:fuchsia.fonts",
"$fuchsia_sdk_root/fidl:fuchsia.images",
"$fuchsia_sdk_root/fidl:fuchsia.io",
"$fuchsia_sdk_root/fidl:fuchsia.modular",
"$fuchsia_sdk_root/fidl:fuchsia.sys",
"$fuchsia_sdk_root/fidl:fuchsia.ui.app",
"$fuchsia_sdk_root/fidl:fuchsia.ui.scenic",
"$fuchsia_sdk_root/pkg:async-cpp",
"$fuchsia_sdk_root/pkg:async-loop",
"$fuchsia_sdk_root/pkg:async-loop-cpp",
"$fuchsia_sdk_root/pkg:fdio",
"$fuchsia_sdk_root/pkg:fidl_cpp",
"$fuchsia_sdk_root/pkg:scenic_cpp",
"$fuchsia_sdk_root/pkg:syslog",
"$fuchsia_sdk_root/pkg:zx",
"$fuchsia_sdk_root/pkg/lib/sys/cpp",
"$fuchsia_sdk_root/pkg/lib/vfs/cpp",
"dart-pkg/fuchsia",
"dart-pkg/zircon",
"runtime/dart/utils",
"//third_party/tonic",
]
}

View File

@@ -0,0 +1,4 @@
Flutter Application Runner
==========================
Implements the `fuchsia::sys::Runner` FIDL interface to launch and run mutliple Flutter applications within the same process.

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import subprocess
import os
import sys
def main():
parser = argparse.ArgumentParser(description='Package a Flutter application')
parser.add_argument('--flutter-root', type=str, required=True,
help='The root of the Flutter SDK')
parser.add_argument('--flutter-tools', type=str, required=True,
help='The executable for the Flutter tool')
parser.add_argument('--asset-dir', type=str, required=True,
help='The directory where to put intermediate files')
parser.add_argument('--app-dir', type=str, required=True,
help='The root of the app')
parser.add_argument('--packages', type=str, required=True,
help='The package map to use')
parser.add_argument('--manifest', type=str, help='The application manifest')
parser.add_argument('--component-name', type=str, help='The name of the component')
parser.add_argument('--asset-manifest-out', type=str,
help='Output path for the asset manifest used by the fuchsia packaging tool')
args = parser.parse_args()
env = os.environ.copy()
env['FLUTTER_ROOT'] = args.flutter_root
call_args = [
args.flutter_tools,
'--asset-dir=%s' % args.asset_dir,
'--packages=%s' % args.packages,
]
if 'manifest' in args:
call_args.append('--manifest=%s' % args.manifest)
if args.asset_manifest_out:
call_args.append('--asset-manifest-out=%s' % args.asset_manifest_out)
if args.component_name:
call_args.append('--component-name=%s' % args.component_name)
result = subprocess.call(call_args, env=env, cwd=args.app_dir)
return result
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,74 @@
#!/usr/bin/env python
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import re
import sys
def main():
parser = argparse.ArgumentParser(
sys.argv[0],
description="Generate main file for Fuchsia dart test")
parser.add_argument("--out",
help="Path to .dart file to generate",
required=True)
parser.add_argument("--main-dart",
help="Path to main.dart file to import",
required=True)
args = parser.parse_args()
out_dir = os.path.dirname(args.out)
assert os.path.isfile(os.path.join(os.path.dirname(args.out), args.main_dart))
outfile = open(args.out, 'w')
# Ignores relative lib imports due to a few modules that complain about
# this. It is also possible that a future may be unawaited given that main
# may not always be synchronous across all functions.
outfile.write('''// Generated by ''')
outfile.write(os.path.basename(__file__))
outfile.write('''
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'package:flutter_driver/driver_extension.dart';
''')
outfile.write("import '%s' as flutter_app_main;\n" % args.main_dart)
outfile.write('''
void main() async {
assert(await (() async {
// TODO(awdavies): Use the logger instead.
print('Overriding app main method because flutter_driver_extendable '
'is enabled in the build file');
try {
// Enables Flutter Driver VM service extension
//
// This extension is required for tests that use package:flutter_driver
// to drive applications from a separate process.
enableFlutterDriverExtension();
// TODO(awdavies): Use the logger instead.
print('flutter driver extensions enabled.');
//ignore: avoid_catches_without_on_clauses
} catch (e) {
// TODO(awdavies): Use the logger instead.
// Noop.
print('flutter driver extensions not enabled. $e');
}
// Always return true so that the assert succeeds.
return true;
}()));
// Execute the main method of the app under test
var res = (flutter_app_main.main as dynamic)();
if (res != null && res is Future) {
await res;
}
}
''')
outfile.close()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,66 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'dart:convert';
bool includeFunction(String function) {
return function.startsWith("dart:") ||
function.startsWith("package:flutter/") ||
function.startsWith("package:vector_math/");
}
main(List<String> args) async {
if (args.length != 1) {
print("Usage:\n"
" fx syslog | dart topaz/runtime/flutter_runner/collect_traces.dart output.txt");
exitCode = 1;
return;
}
var functionCounts = Map<String, int>();
ProcessSignal.sigint.watch().listen((_) {
var functions = List<String>();
// TODO(flutter): Investigate consensus functions to avoid bloat.
var minimumCount = 1;
functionCounts.forEach((String function, int count) {
if (count >= minimumCount) {
functions.add(function);
}
});
functions.sort();
var sb = StringBuffer();
for (var function in functions) {
sb.writeln(function);
}
File(args[0]).writeAsString(sb.toString(), flush: true).then((_) { exit(0); });
});
final stdinAsLines = LineSplitter().bind(Utf8Decoder().bind(stdin));
await for (final line in stdinAsLines) {
final marker = "compilation-trace: ";
final markerPosition = line.indexOf(marker);
if (markerPosition == -1) {
continue;
}
final function = line.substring(markerPosition + marker.length);
if (!includeFunction(function)) {
continue;
}
print(function);
var count = functionCounts[function];
if (count == null) {
count = 1;
} else {
count++;
}
functionCounts[function] = count;
}
}

View File

@@ -0,0 +1,10 @@
The compilation trace lists functions that will be compiled in the core
snapshot. It is derived by unioning the output of Dart_SaveCompilationTrace
after startup from a few apps.
To update this trace.
- In //topaz/runtime/flutter_runner/engine.cc, change kCompilationTraceDelayInSeconds to a non-zero value.
- Re-build.
- Run `fx syslog | dart topaz/runtime/flutter_runner/collect_traces.dart topaz/runtime/flutter_runner/compilation_trace.txt`
- Boot and run a few apps, making sure to exercise the interesting paths before the timer set above expires.
- Send SIGINT (Ctrl-C) to collect_traces.dart.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,526 @@
// Copyright 2013 The Flutter 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 "component.h"
#include <dlfcn.h>
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/namespace.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <lib/vfs/cpp/remote_dir.h>
#include <lib/vfs/cpp/service.h>
#include <sys/stat.h>
#include <zircon/dlfcn.h>
#include <zircon/status.h>
#include <regex>
#include <sstream>
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/shell/common/switches.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/tempfs.h"
#include "runtime/dart/utils/vmo.h"
#include "service_provider_dir.h"
#include "task_observers.h"
#include "thread.h"
namespace flutter_runner {
constexpr char kDataKey[] = "data";
constexpr char kTmpPath[] = "/tmp";
constexpr char kServiceRootPath[] = "/svc";
std::pair<std::unique_ptr<Thread>, std::unique_ptr<Application>>
Application::Create(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller) {
std::unique_ptr<Thread> thread = std::make_unique<Thread>();
std::unique_ptr<Application> application;
fml::AutoResetWaitableEvent latch;
async::PostTask(thread->dispatcher(), [&]() mutable {
application.reset(
new Application(std::move(termination_callback), std::move(package),
std::move(startup_info), runner_incoming_services,
std::move(controller)));
latch.Signal();
});
latch.Wait();
return {std::move(thread), std::move(application)};
}
static std::string DebugLabelForURL(const std::string& url) {
auto found = url.rfind("/");
if (found == std::string::npos) {
return url;
} else {
return {url, found + 1};
}
}
Application::Application(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
application_controller_request)
: termination_callback_(std::move(termination_callback)),
debug_label_(DebugLabelForURL(startup_info.launch_info.url)),
application_controller_(this),
outgoing_dir_(new vfs::PseudoDir()),
runner_incoming_services_(runner_incoming_services) {
application_controller_.set_error_handler(
[this](zx_status_t status) { Kill(); });
FML_DCHECK(fdio_ns_.is_valid());
// LaunchInfo::url non-optional.
auto& launch_info = startup_info.launch_info;
// LaunchInfo::arguments optional.
if (auto& arguments = launch_info.arguments) {
settings_ = flutter::SettingsFromCommandLine(
fml::CommandLineFromIterators(arguments->begin(), arguments->end()));
}
// Determine /pkg/data directory from StartupInfo.
std::string data_path;
for (size_t i = 0; i < startup_info.program_metadata->size(); ++i) {
auto pg = startup_info.program_metadata->at(i);
if (pg.key.compare(kDataKey) == 0) {
data_path = "pkg/" + pg.value;
}
}
if (data_path.empty()) {
FML_DLOG(ERROR) << "Could not find a /pkg/data directory for "
<< package.resolved_url;
return;
}
// Setup /tmp to be mapped to the process-local memfs.
dart_utils::SetupComponentTemp(fdio_ns_.get());
// LaunchInfo::flat_namespace optional.
for (size_t i = 0; i < startup_info.flat_namespace.paths.size(); ++i) {
const auto& path = startup_info.flat_namespace.paths.at(i);
if (path == kTmpPath) {
continue;
}
zx::channel dir;
if (path == kServiceRootPath) {
svc_ = std::make_unique<sys::ServiceDirectory>(
std::move(startup_info.flat_namespace.directories.at(i)));
dir = svc_->CloneChannel().TakeChannel();
} else {
dir = std::move(startup_info.flat_namespace.directories.at(i));
}
zx_handle_t dir_handle = dir.release();
if (fdio_ns_bind(fdio_ns_.get(), path.data(), dir_handle) != ZX_OK) {
FML_DLOG(ERROR) << "Could not bind path to namespace: " << path;
zx_handle_close(dir_handle);
}
}
application_directory_.reset(fdio_ns_opendir(fdio_ns_.get()));
FML_DCHECK(application_directory_.is_valid());
application_assets_directory_.reset(openat(
application_directory_.get(), data_path.c_str(), O_RDONLY | O_DIRECTORY));
// TODO: LaunchInfo::out.
// TODO: LaunchInfo::err.
// LaunchInfo::service_request optional.
if (launch_info.directory_request) {
outgoing_dir_->Serve(fuchsia::io::OPEN_RIGHT_READABLE |
fuchsia::io::OPEN_RIGHT_WRITABLE |
fuchsia::io::OPEN_FLAG_DIRECTORY,
std::move(launch_info.directory_request));
}
directory_request_ = directory_ptr_.NewRequest();
fidl::InterfaceHandle<fuchsia::io::Directory> flutter_public_dir;
// TODO(anmittal): when fixing enumeration using new c++ vfs, make sure that
// flutter_public_dir is only accessed once we receive OnOpen Event.
// That will prevent FL-175 for public directory
auto request = flutter_public_dir.NewRequest().TakeChannel();
fdio_service_connect_at(directory_ptr_.channel().get(), "public",
request.release());
auto service_provider_dir = std::make_unique<ServiceProviderDir>();
service_provider_dir->set_fallback(std::move(flutter_public_dir));
// Clone and check if client is servicing the directory.
directory_ptr_->Clone(fuchsia::io::OPEN_FLAG_DESCRIBE |
fuchsia::io::OPEN_RIGHT_READABLE |
fuchsia::io::OPEN_RIGHT_WRITABLE,
cloned_directory_ptr_.NewRequest());
cloned_directory_ptr_.events().OnOpen =
[this](zx_status_t status, std::unique_ptr<fuchsia::io::NodeInfo> info) {
cloned_directory_ptr_.Unbind();
if (status != ZX_OK) {
FML_LOG(ERROR) << "could not bind out directory for flutter app("
<< debug_label_
<< "): " << zx_status_get_string(status);
return;
}
const char* other_dirs[] = {"debug", "ctrl"};
// add other directories as RemoteDirs.
for (auto& dir_str : other_dirs) {
fidl::InterfaceHandle<fuchsia::io::Directory> dir;
auto request = dir.NewRequest().TakeChannel();
fdio_service_connect_at(directory_ptr_.channel().get(), dir_str,
request.release());
outgoing_dir_->AddEntry(
dir_str, std::make_unique<vfs::RemoteDir>(dir.TakeChannel()));
}
};
cloned_directory_ptr_.set_error_handler(
[this](zx_status_t status) { cloned_directory_ptr_.Unbind(); });
// TODO: LaunchInfo::additional_services optional.
// All launch arguments have been read. Perform service binding and
// final settings configuration. The next call will be to create a view
// for this application.
service_provider_dir->AddService(
fuchsia::ui::app::ViewProvider::Name_,
std::make_unique<vfs::Service>(
[this](zx::channel channel, async_dispatcher_t* dispatcher) {
shells_bindings_.AddBinding(
this, fidl::InterfaceRequest<fuchsia::ui::app::ViewProvider>(
std::move(channel)));
}));
outgoing_dir_->AddEntry("public", std::move(service_provider_dir));
// Setup the application controller binding.
if (application_controller_request) {
application_controller_.Bind(std::move(application_controller_request));
}
// Compare flutter_jit_runner in BUILD.gn.
settings_.vm_snapshot_data_path = "pkg/data/vm_snapshot_data.bin";
settings_.vm_snapshot_instr_path = "pkg/data/vm_snapshot_instructions.bin";
settings_.isolate_snapshot_data_path =
"pkg/data/isolate_core_snapshot_data.bin";
settings_.isolate_snapshot_instr_path =
"pkg/data/isolate_core_snapshot_instructions.bin";
{
// Check if we can use the snapshot with the framework already loaded.
std::string runner_framework;
std::string app_framework;
if (dart_utils::ReadFileToString("pkg/data/runner.frameworkversion",
&runner_framework) &&
dart_utils::ReadFileToStringAt(application_assets_directory_.get(),
"app.frameworkversion",
&app_framework) &&
(runner_framework.compare(app_framework) == 0)) {
settings_.vm_snapshot_data_path =
"pkg/data/framework_vm_snapshot_data.bin";
settings_.vm_snapshot_instr_path =
"pkg/data/framework_vm_snapshot_instructions.bin";
settings_.isolate_snapshot_data_path =
"pkg/data/framework_isolate_core_snapshot_data.bin";
settings_.isolate_snapshot_instr_path =
"pkg/data/framework_isolate_core_snapshot_instructions.bin";
FML_LOG(INFO) << "Using snapshot with framework for "
<< package.resolved_url;
} else {
FML_LOG(INFO) << "Using snapshot without framework for "
<< package.resolved_url;
}
}
#if defined(DART_PRODUCT)
settings_.enable_observatory = false;
#else
settings_.enable_observatory = true;
#endif
settings_.icu_data_path = "";
settings_.assets_dir = application_assets_directory_.get();
// Compare flutter_jit_app in flutter_app.gni.
settings_.application_kernel_list_asset = "app.dilplist";
settings_.log_tag = debug_label_ + std::string{"(flutter)"};
// No asserts in debug or release product.
// No asserts in release with flutter_profile=true (non-product)
// Yes asserts in non-product debug.
#if !defined(DART_PRODUCT) && (!defined(FLUTTER_PROFILE) || !defined(NDEBUG))
// Debug mode
settings_.disable_dart_asserts = false;
#else
// Release mode
settings_.disable_dart_asserts = true;
#endif
settings_.task_observer_add =
std::bind(&CurrentMessageLoopAddAfterTaskObserver, std::placeholders::_1,
std::placeholders::_2);
settings_.task_observer_remove = std::bind(
&CurrentMessageLoopRemoveAfterTaskObserver, std::placeholders::_1);
// TODO(FL-117): Re-enable causal async stack traces when this issue is
// addressed.
settings_.dart_flags = {"--no_causal_async_stacks"};
// Disable code collection as it interferes with JIT code warmup
// by decreasing usage counters and flushing code which is still useful.
settings_.dart_flags.push_back("--no-collect_code");
if (!flutter::DartVM::IsRunningPrecompiledCode()) {
// The interpreter is enabled unconditionally in JIT mode. If an app is
// built for debugging (that is, with no bytecode), the VM will fall back on
// ASTs.
settings_.dart_flags.push_back("--enable_interpreter");
}
// Don't collect CPU samples from Dart VM C++ code.
settings_.dart_flags.push_back("--no_profile_vm");
// Scale back CPU profiler sampling period on ARM64 to avoid overloading
// the tracing engine.
#if defined(__aarch64__)
settings_.dart_flags.push_back("--profile_period=10000");
#endif // defined(__aarch64__)
auto dispatcher = async_get_default_dispatcher();
FML_CHECK(dispatcher);
const std::string component_url = package.resolved_url;
settings_.unhandled_exception_callback =
[dispatcher, runner_incoming_services, component_url](
const std::string& error, const std::string& stack_trace) {
async::PostTask(dispatcher, [runner_incoming_services, component_url,
error, stack_trace]() {
dart_utils::HandleException(runner_incoming_services, component_url,
error, stack_trace);
});
// Ideally we would return whether HandleException returned ZX_OK, but
// short of knowing if the exception was correctly handled, we return
// false to have the error and stack trace printed in the logs.
return false;
};
AttemptVMLaunchWithCurrentSettings(settings_);
}
Application::~Application() = default;
const std::string& Application::GetDebugLabel() const {
return debug_label_;
}
class FileInNamespaceBuffer final : public fml::Mapping {
public:
FileInNamespaceBuffer(int namespace_fd, const char* path, bool executable)
: address_(nullptr), size_(0) {
fuchsia::mem::Buffer buffer;
if (!dart_utils::VmoFromFilenameAt(namespace_fd, path, &buffer)) {
return;
}
if (buffer.size == 0) {
return;
}
uint32_t flags = ZX_VM_PERM_READ;
if (executable) {
flags |= ZX_VM_PERM_EXECUTE;
// VmoFromFilenameAt will return VMOs without ZX_RIGHT_EXECUTE,
// so we need replace_as_executable to be able to map them as
// ZX_VM_PERM_EXECUTE.
// TODO(mdempsky): Update comment once SEC-42 is fixed.
zx_status_t status =
buffer.vmo.replace_as_executable(zx::handle(), &buffer.vmo);
if (status != ZX_OK) {
FML_LOG(FATAL) << "Failed to make VMO executable: "
<< zx_status_get_string(status);
}
}
uintptr_t addr;
zx_status_t status =
zx::vmar::root_self()->map(0, buffer.vmo, 0, buffer.size, flags, &addr);
if (status != ZX_OK) {
FML_LOG(FATAL) << "Failed to map " << path << ": "
<< zx_status_get_string(status);
}
address_ = reinterpret_cast<void*>(addr);
size_ = buffer.size;
}
~FileInNamespaceBuffer() {
if (address_ != nullptr) {
zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(address_),
size_);
address_ = nullptr;
size_ = 0;
}
}
// |fml::Mapping|
const uint8_t* GetMapping() const override {
return reinterpret_cast<const uint8_t*>(address_);
}
// |fml::Mapping|
size_t GetSize() const override { return size_; }
private:
void* address_;
size_t size_;
FML_DISALLOW_COPY_AND_ASSIGN(FileInNamespaceBuffer);
};
std::unique_ptr<fml::Mapping> CreateWithContentsOfFile(int namespace_fd,
const char* file_path,
bool executable) {
FML_TRACE_EVENT("flutter", "LoadFile", "path", file_path);
auto source = std::make_unique<FileInNamespaceBuffer>(namespace_fd, file_path,
executable);
return source->GetMapping() == nullptr ? nullptr : std::move(source);
}
void Application::AttemptVMLaunchWithCurrentSettings(
const flutter::Settings& settings) {
if (!flutter::DartVM::IsRunningPrecompiledCode()) {
// We will be initializing the VM lazily in this case.
return;
}
// Compare flutter_aot_app in flutter_app.gni.
fml::RefPtr<flutter::DartSnapshot> vm_snapshot =
fml::MakeRefCounted<flutter::DartSnapshot>(
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"vm_snapshot_data.bin", false),
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"vm_snapshot_instructions.bin", true));
isolate_snapshot_ = fml::MakeRefCounted<flutter::DartSnapshot>(
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"isolate_snapshot_data.bin", false),
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"isolate_snapshot_instructions.bin", true));
shared_snapshot_ = fml::MakeRefCounted<flutter::DartSnapshot>(
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"shared_snapshot_data.bin", false),
CreateWithContentsOfFile(
application_assets_directory_.get() /* /pkg/data */,
"shared_snapshot_instructions.bin", true));
auto vm = flutter::DartVMRef::Create(settings_, //
std::move(vm_snapshot), //
isolate_snapshot_, //
shared_snapshot_ //
);
FML_CHECK(vm) << "Mut be able to initialize the VM.";
}
// |fuchsia::sys::ComponentController|
void Application::Kill() {
application_controller_.events().OnTerminated(
last_return_code_.second, fuchsia::sys::TerminationReason::EXITED);
termination_callback_(this);
// WARNING: Don't do anything past this point as this instance may have been
// collected.
}
// |fuchsia::sys::ComponentController|
void Application::Detach() {
application_controller_.set_error_handler(nullptr);
}
// |flutter::Engine::Delegate|
void Application::OnEngineTerminate(const Engine* shell_holder) {
auto found = std::find_if(shell_holders_.begin(), shell_holders_.end(),
[shell_holder](const auto& holder) {
return holder.get() == shell_holder;
});
if (found == shell_holders_.end()) {
return;
}
// We may launch multiple shell in this application. However, we will
// terminate when the last shell goes away. The error code return to the
// application controller will be the last isolate that had an error.
auto return_code = shell_holder->GetEngineReturnCode();
if (return_code.first) {
last_return_code_ = return_code;
}
shell_holders_.erase(found);
if (shell_holders_.size() == 0) {
Kill();
// WARNING: Don't do anything past this point because the delegate may have
// collected this instance via the termination callback.
}
}
// |fuchsia::ui::app::ViewProvider|
void Application::CreateView(
zx::eventpair view_token,
fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> incoming_services,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider> outgoing_services) {
if (!svc_) {
FML_DLOG(ERROR)
<< "Component incoming services was invalid when attempting to "
"create a shell for a view provider request.";
return;
}
shell_holders_.emplace(std::make_unique<Engine>(
*this, // delegate
debug_label_, // thread label
svc_, // Component incoming services
settings_, // settings
std::move(isolate_snapshot_), // isolate snapshot
std::move(shared_snapshot_), // shared snapshot
scenic::ToViewToken(std::move(view_token)), // view token
std::move(fdio_ns_), // FDIO namespace
std::move(directory_request_) // outgoing request
));
}
#if !defined(DART_PRODUCT)
void Application::WriteProfileToTrace() const {
for (const auto& engine : shell_holders_) {
engine->WriteProfileToTrace();
}
}
#endif // !defined(DART_PRODUCT)
} // namespace flutter_runner

View File

@@ -0,0 +1,113 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_COMPONENT_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_COMPONENT_H_
#include <array>
#include <memory>
#include <set>
#include <fuchsia/io/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <fuchsia/ui/app/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/default.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/fidl/cpp/interface_request.h>
#include <lib/fit/function.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <lib/zx/eventpair.h>
#include "engine.h"
#include "flutter/common/settings.h"
#include "flutter/fml/macros.h"
#include "thread.h"
#include "unique_fdio_ns.h"
namespace flutter_runner {
// Represents an instance of a Flutter application that contains one of more
// Flutter engine instances.
class Application final : public Engine::Delegate,
public fuchsia::sys::ComponentController,
public fuchsia::ui::app::ViewProvider {
public:
using TerminationCallback = fit::function<void(const Application*)>;
// Creates a dedicated thread to run the application and constructions the
// application on it. The application can be accessed only on this thread.
// This is a synchronous operation.
static std::pair<std::unique_ptr<Thread>, std::unique_ptr<Application>>
Create(TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller);
// Must be called on the same thread returned from the create call. The thread
// may be collected after.
~Application();
const std::string& GetDebugLabel() const;
#if !defined(DART_PRODUCT)
void WriteProfileToTrace() const;
#endif // !defined(DART_PRODUCT)
private:
flutter::Settings settings_;
TerminationCallback termination_callback_;
const std::string debug_label_;
UniqueFDIONS fdio_ns_ = UniqueFDIONSCreate();
fml::UniqueFD application_directory_;
fml::UniqueFD application_assets_directory_;
fidl::Binding<fuchsia::sys::ComponentController> application_controller_;
fuchsia::io::DirectoryPtr directory_ptr_;
fuchsia::io::NodePtr cloned_directory_ptr_;
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request_;
std::unique_ptr<vfs::PseudoDir> outgoing_dir_;
std::shared_ptr<sys::ServiceDirectory> svc_;
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_;
fidl::BindingSet<fuchsia::ui::app::ViewProvider> shells_bindings_;
fml::RefPtr<flutter::DartSnapshot> isolate_snapshot_;
fml::RefPtr<flutter::DartSnapshot> shared_snapshot_;
std::set<std::unique_ptr<Engine>> shell_holders_;
std::pair<bool, uint32_t> last_return_code_;
Application(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller);
// |fuchsia::sys::ComponentController|
void Kill() override;
// |fuchsia::sys::ComponentController|
void Detach() override;
// |fuchsia::ui::app::ViewProvider|
void CreateView(
zx::eventpair view_token,
fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> incoming_services,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider> outgoing_services)
override;
// |flutter::Engine::Delegate|
void OnEngineTerminate(const Engine* holder) override;
void AttemptVMLaunchWithCurrentSettings(const flutter::Settings& settings);
FML_DISALLOW_COPY_AND_ASSIGN(Application);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_COMPONENT_H_

View File

@@ -0,0 +1,104 @@
// Copyright 2013 The Flutter 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 "compositor_context.h"
#include "flutter/flow/layers/layer_tree.h"
namespace flutter_runner {
class ScopedFrame final : public flutter::CompositorContext::ScopedFrame {
public:
ScopedFrame(flutter::CompositorContext& context,
const SkMatrix& root_surface_transformation,
bool instrumentation_enabled,
SessionConnection& session_connection)
: flutter::CompositorContext::ScopedFrame(context,
nullptr,
nullptr,
nullptr,
root_surface_transformation,
instrumentation_enabled),
session_connection_(session_connection) {}
private:
SessionConnection& session_connection_;
bool Raster(flutter::LayerTree& layer_tree,
bool ignore_raster_cache) override {
if (!session_connection_.has_metrics()) {
return true;
}
{
// Preroll the Flutter layer tree. This allows Flutter to perform
// pre-paint optimizations.
TRACE_EVENT0("flutter", "Preroll");
layer_tree.Preroll(*this, true /* ignore raster cache */);
}
{
// Traverse the Flutter layer tree so that the necessary session ops to
// represent the frame are enqueued in the underlying session.
TRACE_EVENT0("flutter", "UpdateScene");
layer_tree.UpdateScene(session_connection_.scene_update_context(),
session_connection_.root_node());
}
{
// Flush all pending session ops.
TRACE_EVENT0("flutter", "SessionPresent");
session_connection_.Present(*this);
}
return true;
}
FML_DISALLOW_COPY_AND_ASSIGN(ScopedFrame);
};
CompositorContext::CompositorContext(
std::string debug_label,
fuchsia::ui::views::ViewToken view_token,
fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session,
fit::closure session_error_callback,
zx_handle_t vsync_event_handle)
: debug_label_(std::move(debug_label)),
session_connection_(debug_label_,
std::move(view_token),
std::move(session),
std::move(session_error_callback),
vsync_event_handle) {}
void CompositorContext::OnSessionMetricsDidChange(
const fuchsia::ui::gfx::Metrics& metrics) {
session_connection_.set_metrics(metrics);
}
void CompositorContext::OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor) {
session_connection_.OnSessionSizeChangeHint(width_change_factor,
height_change_factor);
}
CompositorContext::~CompositorContext() = default;
std::unique_ptr<flutter::CompositorContext::ScopedFrame>
CompositorContext::AcquireFrame(GrContext* gr_context,
SkCanvas* canvas,
flutter::ExternalViewEmbedder* view_embedder,
const SkMatrix& root_surface_transformation,
bool instrumentation_enabled) {
// TODO: The AcquireFrame interface is too broad and must be refactored to get
// rid of the context and canvas arguments as those seem to be only used for
// colorspace correctness purposes on the mobile shells.
return std::make_unique<flutter_runner::ScopedFrame>(
*this, //
root_surface_transformation, //
instrumentation_enabled, //
session_connection_ //
);
}
} // namespace flutter_runner

View File

@@ -0,0 +1,52 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_COMPOSITOR_CONTEXT_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_COMPOSITOR_CONTEXT_H_
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fit/function.h>
#include "flutter/flow/compositor_context.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/macros.h"
#include "session_connection.h"
namespace flutter_runner {
// Holds composition specific state and bindings specific to composition on
// Fuchsia.
class CompositorContext final : public flutter::CompositorContext {
public:
CompositorContext(std::string debug_label,
fuchsia::ui::views::ViewToken view_token,
fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session,
fit::closure session_error_callback,
zx_handle_t vsync_event_handle);
~CompositorContext() override;
void OnSessionMetricsDidChange(const fuchsia::ui::gfx::Metrics& metrics);
void OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor);
private:
const std::string debug_label_;
SessionConnection session_connection_;
// |flutter::CompositorContext|
std::unique_ptr<ScopedFrame> AcquireFrame(
GrContext* gr_context,
SkCanvas* canvas,
flutter::ExternalViewEmbedder* view_embedder,
const SkMatrix& root_surface_transformation,
bool instrumentation_enabled) override;
FML_DISALLOW_COPY_AND_ASSIGN(CompositorContext);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_COMPOSITOR_CONTEXT_H_

View File

@@ -0,0 +1,80 @@
// Copyright 2013 The Flutter 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 "context_writer_bridge.h"
#include <unordered_set>
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
namespace flutter_runner {
ContextWriterBridge::ContextWriterBridge(
fidl::InterfaceHandle<fuchsia::modular::ContextWriter> writer)
: writer_(writer.Bind()) {}
ContextWriterBridge::~ContextWriterBridge() = default;
void ContextWriterBridge::UpdateSemantics(
const flutter::SemanticsNodeUpdates& update) {
for (const auto& update : update) {
const auto& node = update.second;
semantics_nodes_[node.id] = node;
}
std::vector<int> visited_nodes;
UpdateVisitedForNodeAndChildren(0, &visited_nodes);
EraseUnvisitedNodes(visited_nodes);
// The data sent to the Context Service is a JSON formatted list of labels
// for all on screen widgets.
rapidjson::Document nodes_json(rapidjson::kArrayType);
for (const int node_index : visited_nodes) {
const auto& node = semantics_nodes_[node_index];
if (!node.label.empty()) {
rapidjson::Value value;
value.SetString(node.label.data(), node.label.size());
nodes_json.PushBack(value, nodes_json.GetAllocator());
}
}
if (nodes_json.Size() > 0) {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
nodes_json.Accept(writer);
writer_->WriteEntityTopic("/inferred/accessibility_text",
buffer.GetString());
}
}
void ContextWriterBridge::UpdateVisitedForNodeAndChildren(
const int id,
std::vector<int>* visited_nodes) {
std::map<int, flutter::SemanticsNode>::const_iterator it =
semantics_nodes_.find(id);
if (it == semantics_nodes_.end()) {
return;
}
visited_nodes->push_back(id);
for (const int child : it->second.childrenInTraversalOrder) {
UpdateVisitedForNodeAndChildren(child, visited_nodes);
}
}
void ContextWriterBridge::EraseUnvisitedNodes(
const std::vector<int>& visited_nodes) {
const std::unordered_set<int> visited_nodes_lookup(visited_nodes.begin(),
visited_nodes.end());
for (auto it = semantics_nodes_.begin(); it != semantics_nodes_.end();) {
if (visited_nodes_lookup.find((*it).first) == visited_nodes_lookup.end()) {
it = semantics_nodes_.erase(it);
} else {
++it;
}
}
}
} // namespace flutter_runner

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <map>
#include <fuchsia/modular/cpp/fidl.h>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
namespace flutter_runner {
// Maintain an up-to-date list of SemanticsNodes on screen, and communicate
// with the Context Service.
class ContextWriterBridge final {
public:
ContextWriterBridge(
fidl::InterfaceHandle<fuchsia::modular::ContextWriter> writer);
~ContextWriterBridge();
// Update the internal representation of the semantics nodes, and write the
// semantics to Context Service.
void UpdateSemantics(const flutter::SemanticsNodeUpdates& update);
private:
fuchsia::modular::ContextWriterPtr writer_;
std::map<int, flutter::SemanticsNode> semantics_nodes_;
// Walk the semantics node tree starting at |id|, and store the id of each
// visited child in |visited_nodes|.
void UpdateVisitedForNodeAndChildren(const int id,
std::vector<int>* visited_nodes);
// Remove any node from |semantics_nodes_| that doesn't have an id in
// |visited_nodes|.
void EraseUnvisitedNodes(const std::vector<int>& visited_nodes);
FML_DISALLOW_COPY_AND_ASSIGN(ContextWriterBridge);
};
} // namespace flutter_runner

View File

@@ -0,0 +1,454 @@
// Copyright 2013 The Flutter 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 "engine.h"
#include <lib/async/cpp/task.h>
#include <sstream>
#include "flutter/common/task_runners.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/task_runner.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/run_configuration.h"
#include "runtime/dart/utils/files.h"
#include "fuchsia_font_manager.h"
#include "platform_view.h"
#include "task_runner_adapter.h"
#include "thread.h"
namespace flutter_runner {
static void UpdateNativeThreadLabelNames(const std::string& label,
const flutter::TaskRunners& runners) {
auto set_thread_name = [](fml::RefPtr<fml::TaskRunner> runner,
std::string prefix, std::string suffix) {
if (!runner) {
return;
}
fml::TaskRunner::RunNowOrPostTask(runner, [name = prefix + suffix]() {
zx::thread::self()->set_property(ZX_PROP_NAME, name.c_str(), name.size());
});
};
set_thread_name(runners.GetPlatformTaskRunner(), label, ".platform");
set_thread_name(runners.GetUITaskRunner(), label, ".ui");
set_thread_name(runners.GetGPUTaskRunner(), label, ".gpu");
set_thread_name(runners.GetIOTaskRunner(), label, ".io");
}
Engine::Engine(Delegate& delegate,
std::string thread_label,
std::shared_ptr<sys::ServiceDirectory> svc,
flutter::Settings settings,
fml::RefPtr<const flutter::DartSnapshot> isolate_snapshot,
fml::RefPtr<const flutter::DartSnapshot> shared_snapshot,
fuchsia::ui::views::ViewToken view_token,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request)
: delegate_(delegate),
thread_label_(std::move(thread_label)),
settings_(std::move(settings)),
weak_factory_(this) {
if (zx::event::create(0, &vsync_event_) != ZX_OK) {
FML_DLOG(ERROR) << "Could not create the vsync event.";
return;
}
// Launch the threads that will be used to run the shell. These threads will
// be joined in the destructor.
for (auto& thread : threads_) {
thread.reset(new Thread());
}
// Set up the session connection.
auto scenic = svc->Connect<fuchsia::ui::scenic::Scenic>();
fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session;
fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> session_listener;
auto session_listener_request = session_listener.NewRequest();
scenic->CreateSession(session.NewRequest(), session_listener.Bind());
// Grab the parent environment services. The platform view may want to access
// some of these services.
fuchsia::sys::EnvironmentPtr environment;
svc->Connect(environment.NewRequest());
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider>
parent_environment_service_provider;
environment->GetServices(parent_environment_service_provider.NewRequest());
environment.Unbind();
// Grab the accessibilty context writer that can understand the semantics tree
// on the platform view.
fidl::InterfaceHandle<fuchsia::modular::ContextWriter>
accessibility_context_writer;
svc->Connect(accessibility_context_writer.NewRequest());
// We need to manually schedule a frame when the session metrics change.
OnMetricsUpdate on_session_metrics_change_callback = std::bind(
&Engine::OnSessionMetricsDidChange, this, std::placeholders::_1);
OnSizeChangeHint on_session_size_change_hint_callback =
std::bind(&Engine::OnSessionSizeChangeHint, this, std::placeholders::_1,
std::placeholders::_2);
// SessionListener has a OnScenicError method; invoke this callback on the
// platform thread when that happens. The Session itself should also be
// disconnected when this happens, and it will also attempt to terminate.
fit::closure on_session_listener_error_callback =
[dispatcher = async_get_default_dispatcher(),
weak = weak_factory_.GetWeakPtr()]() {
async::PostTask(dispatcher, [weak]() {
if (weak) {
weak->Terminate();
}
});
};
// Setup the callback that will instantiate the platform view.
flutter::Shell::CreateCallback<flutter::PlatformView>
on_create_platform_view = fml::MakeCopyable(
[debug_label = thread_label_,
parent_environment_service_provider =
std::move(parent_environment_service_provider),
session_listener_request = std::move(session_listener_request),
on_session_listener_error_callback =
std::move(on_session_listener_error_callback),
on_session_metrics_change_callback =
std::move(on_session_metrics_change_callback),
on_session_size_change_hint_callback =
std::move(on_session_size_change_hint_callback),
accessibility_context_writer =
std::move(accessibility_context_writer),
vsync_handle = vsync_event_.get()](flutter::Shell& shell) mutable {
return std::make_unique<flutter_runner::PlatformView>(
shell, // delegate
debug_label, // debug label
shell.GetTaskRunners(), // task runners
std::move(parent_environment_service_provider), // services
std::move(session_listener_request), // session listener
std::move(on_session_listener_error_callback),
std::move(on_session_metrics_change_callback),
std::move(on_session_size_change_hint_callback),
std::move(accessibility_context_writer), // accessibility
// context writer
vsync_handle // vsync handle
);
});
// Session can be terminated on the GPU thread, but we must terminate
// ourselves on the platform thread.
//
// This handles the fidl error callback when the Session connection is
// broken. The SessionListener interface also has an OnError method, which is
// invoked on the platform thread (in PlatformView).
fit::closure on_session_error_callback =
[dispatcher = async_get_default_dispatcher(),
weak = weak_factory_.GetWeakPtr()]() {
async::PostTask(dispatcher, [weak]() {
if (weak) {
weak->Terminate();
}
});
};
// Create the compositor context from the scenic pointer to create the
// rasterizer.
std::unique_ptr<flutter::CompositorContext> compositor_context;
{
TRACE_EVENT0("flutter", "CreateCompositorContext");
compositor_context = std::make_unique<flutter_runner::CompositorContext>(
thread_label_, // debug label
std::move(view_token), // scenic view we attach our tree to
std::move(session), // scenic session
std::move(on_session_error_callback), // session did encounter error
vsync_event_.get() // vsync event handle
);
}
// Setup the callback that will instantiate the rasterizer.
flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
fml::MakeCopyable([compositor_context = std::move(compositor_context)](
flutter::Shell& shell) mutable {
return std::make_unique<flutter::Rasterizer>(
shell.GetTaskRunners(), // task runners
std::move(compositor_context) // compositor context
);
});
// Get the task runners from the managed threads. The current thread will be
// used as the "platform" thread.
const flutter::TaskRunners task_runners(
thread_label_, // Dart thread labels
CreateFMLTaskRunner(async_get_default_dispatcher()), // platform
CreateFMLTaskRunner(threads_[0]->dispatcher()), // gpu
CreateFMLTaskRunner(threads_[1]->dispatcher()), // ui
CreateFMLTaskRunner(threads_[2]->dispatcher()) // io
);
UpdateNativeThreadLabelNames(thread_label_, task_runners);
settings_.verbose_logging = true;
settings_.advisory_script_uri = thread_label_;
settings_.advisory_script_entrypoint = thread_label_;
settings_.root_isolate_create_callback =
std::bind(&Engine::OnMainIsolateStart, this);
settings_.root_isolate_shutdown_callback =
std::bind([weak = weak_factory_.GetWeakPtr(),
runner = task_runners.GetPlatformTaskRunner()]() {
runner->PostTask([weak = std::move(weak)] {
if (weak) {
weak->OnMainIsolateShutdown();
}
});
});
auto vm = flutter::DartVMRef::Create(settings_);
if (!isolate_snapshot) {
isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot();
}
if (!shared_snapshot) {
shared_snapshot = flutter::DartSnapshot::Empty();
}
{
TRACE_EVENT0("flutter", "CreateShell");
shell_ = flutter::Shell::Create(
task_runners, // host task runners
settings_, // shell launch settings
std::move(isolate_snapshot), // isolate snapshot
std::move(shared_snapshot), // shared snapshot
on_create_platform_view, // platform view create callback
on_create_rasterizer, // rasterizer create callback
std::move(vm) // vm reference
);
}
if (!shell_) {
FML_LOG(ERROR) << "Could not launch the shell.";
return;
}
// Shell has been created. Before we run the engine, setup the isolate
// configurator.
{
fuchsia::sys::EnvironmentPtr environment;
svc->Connect(environment.NewRequest());
isolate_configurator_ = std::make_unique<IsolateConfigurator>(
std::move(fdio_ns), //
std::move(environment), //
directory_request.TakeChannel() //
);
}
// This platform does not get a separate surface platform view creation
// notification. Fire one eagerly.
shell_->GetPlatformView()->NotifyCreated();
// Launch the engine in the appropriate configuration.
auto run_configuration = flutter::RunConfiguration::InferFromSettings(
settings_, task_runners.GetIOTaskRunner());
auto on_run_failure = [weak = weak_factory_.GetWeakPtr()]() {
// The engine could have been killed by the caller right after the
// constructor was called but before it could run on the UI thread.
if (weak) {
weak->Terminate();
}
};
// Connect to the system font provider.
fuchsia::fonts::ProviderSyncPtr sync_font_provider;
svc->Connect(sync_font_provider.NewRequest());
shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
fml::MakeCopyable([engine = shell_->GetEngine(), //
run_configuration = std::move(run_configuration), //
sync_font_provider = std::move(sync_font_provider), //
on_run_failure //
]() mutable {
if (!engine) {
return;
}
// Set default font manager.
engine->GetFontCollection().GetFontCollection()->SetDefaultFontManager(
sk_make_sp<txt::FuchsiaFontManager>(std::move(sync_font_provider)));
if (engine->Run(std::move(run_configuration)) ==
flutter::Engine::RunStatus::Failure) {
on_run_failure();
}
}));
}
Engine::~Engine() {
shell_.reset();
for (const auto& thread : threads_) {
thread->Quit();
}
for (const auto& thread : threads_) {
thread->Join();
}
}
std::pair<bool, uint32_t> Engine::GetEngineReturnCode() const {
std::pair<bool, uint32_t> code(false, 0);
if (!shell_) {
return code;
}
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell_->GetTaskRunners().GetUITaskRunner(),
[&latch, &code, engine = shell_->GetEngine()]() {
if (engine) {
code = engine->GetUIIsolateReturnCode();
}
latch.Signal();
});
latch.Wait();
return code;
}
static void CreateCompilationTrace(Dart_Isolate isolate) {
Dart_EnterIsolate(isolate);
{
Dart_EnterScope();
uint8_t* trace = nullptr;
intptr_t trace_length = 0;
Dart_Handle result = Dart_SaveCompilationTrace(&trace, &trace_length);
tonic::LogIfError(result);
for (intptr_t start = 0; start < trace_length;) {
intptr_t end = start;
while ((end < trace_length) && trace[end] != '\n')
end++;
std::string line(reinterpret_cast<char*>(&trace[start]), end - start);
FML_LOG(INFO) << "compilation-trace: " << line;
start = end + 1;
}
Dart_ExitScope();
}
// Re-enter Dart scope to release the compilation trace's memory.
{
Dart_EnterScope();
uint8_t* feedback = nullptr;
intptr_t feedback_length = 0;
Dart_Handle result = Dart_SaveTypeFeedback(&feedback, &feedback_length);
tonic::LogIfError(result);
const std::string kTypeFeedbackFile = "/data/dart_type_feedback.bin";
if (dart_utils::WriteFile(kTypeFeedbackFile,
reinterpret_cast<const char*>(feedback),
feedback_length)) {
FML_LOG(INFO) << "Dart type feedback written to " << kTypeFeedbackFile;
} else {
FML_LOG(ERROR) << "Could not write Dart type feedback to "
<< kTypeFeedbackFile;
}
Dart_ExitScope();
}
Dart_ExitIsolate();
}
void Engine::OnMainIsolateStart() {
if (!isolate_configurator_ ||
!isolate_configurator_->ConfigureCurrentIsolate()) {
FML_LOG(ERROR) << "Could not configure some native embedder bindings for a "
"new root isolate.";
}
FML_DLOG(INFO) << "Main isolate for engine '" << thread_label_
<< "' was started.";
const intptr_t kCompilationTraceDelayInSeconds = 0;
if (kCompilationTraceDelayInSeconds != 0) {
Dart_Isolate isolate = Dart_CurrentIsolate();
FML_CHECK(isolate);
shell_->GetTaskRunners().GetUITaskRunner()->PostDelayedTask(
[engine = shell_->GetEngine(), isolate]() {
if (!engine) {
return;
}
CreateCompilationTrace(isolate);
},
fml::TimeDelta::FromSeconds(kCompilationTraceDelayInSeconds));
}
}
void Engine::OnMainIsolateShutdown() {
FML_DLOG(INFO) << "Main isolate for engine '" << thread_label_
<< "' shutting down.";
Terminate();
}
void Engine::Terminate() {
delegate_.OnEngineTerminate(this);
// Warning. Do not do anything after this point as the delegate may have
// collected this object.
}
void Engine::OnSessionMetricsDidChange(
const fuchsia::ui::gfx::Metrics& metrics) {
if (!shell_) {
return;
}
shell_->GetTaskRunners().GetGPUTaskRunner()->PostTask(
[rasterizer = shell_->GetRasterizer(), metrics]() {
if (rasterizer) {
auto compositor_context =
reinterpret_cast<flutter_runner::CompositorContext*>(
rasterizer->compositor_context());
compositor_context->OnSessionMetricsDidChange(metrics);
}
});
}
void Engine::OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor) {
if (!shell_) {
return;
}
shell_->GetTaskRunners().GetGPUTaskRunner()->PostTask(
[rasterizer = shell_->GetRasterizer(), width_change_factor,
height_change_factor]() {
if (rasterizer) {
auto compositor_context = reinterpret_cast<CompositorContext*>(
rasterizer->compositor_context());
compositor_context->OnSessionSizeChangeHint(width_change_factor,
height_change_factor);
}
});
}
#if !defined(DART_PRODUCT)
void Engine::WriteProfileToTrace() const {
Dart_Port main_port = shell_->GetEngine()->GetUIIsolateMainPort();
char* error = NULL;
bool success = Dart_WriteProfileToTimeline(main_port, &error);
if (!success) {
FML_LOG(ERROR) << "Failed to write Dart profile to trace: " << error;
free(error);
}
}
#endif // !defined(DART_PRODUCT)
} // namespace flutter_runner

View File

@@ -0,0 +1,75 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_ENGINE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_ENGINE_H_
#include <fuchsia/io/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/zx/event.h>
#include "flutter/fml/macros.h"
#include "flutter/shell/common/shell.h"
#include "isolate_configurator.h"
#include "thread.h"
namespace flutter_runner {
// Represents an instance of running Flutter engine along with the threads
// that host the same.
class Engine final {
public:
class Delegate {
public:
virtual void OnEngineTerminate(const Engine* holder) = 0;
};
Engine(Delegate& delegate,
std::string thread_label,
std::shared_ptr<sys::ServiceDirectory> svc,
flutter::Settings settings,
fml::RefPtr<const flutter::DartSnapshot> isolate_snapshot,
fml::RefPtr<const flutter::DartSnapshot> shared_snapshot,
fuchsia::ui::views::ViewToken view_token,
UniqueFDIONS fdio_ns,
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request);
~Engine();
// Returns the Dart return code for the root isolate if one is present. This
// call is thread safe and synchronous. This call must be made infrequently.
std::pair<bool, uint32_t> GetEngineReturnCode() const;
#if !defined(DART_PRODUCT)
void WriteProfileToTrace() const;
#endif // !defined(DART_PRODUCT)
private:
Delegate& delegate_;
const std::string thread_label_;
flutter::Settings settings_;
std::array<std::unique_ptr<Thread>, 3> threads_;
std::unique_ptr<IsolateConfigurator> isolate_configurator_;
std::unique_ptr<flutter::Shell> shell_;
zx::event vsync_event_;
fml::WeakPtrFactory<Engine> weak_factory_;
void OnMainIsolateStart();
void OnMainIsolateShutdown();
void Terminate();
void OnSessionMetricsDidChange(const fuchsia::ui::gfx::Metrics& metrics);
void OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor);
FML_DISALLOW_COPY_AND_ASSIGN(Engine);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_ENGINE_H_

View File

@@ -0,0 +1,316 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_fuchsia || is_fuchsia_host)
import("//build/package.gni")
import("//build/tools/json_merge/json_merge.gni")
import("//third_party/dart/build/dart/dart_action.gni")
import("//topaz/runtime/dart/config.gni")
import("//topaz/runtime/dart/dart_component.gni")
import("//topaz/runtime/dart/dart_kernel.gni")
# Defines JIT runtime components to be further distributed in one package.
#
# Takes a set of flutter components and puts them into one fuchsia package with
# the flutter_jit_runner as its runtime. Also supports legacy calls where the
# components parameter isn't specified, in which we will create one default
# component for the package.
#
# Parameters
#
# components (required)
# [list of scopes] Defines the components in the package. Either main_dart
# or components must be defined, but not both.
#
# Entries in a scope in the resources list:
#
# component_name (required)
# Name of the component.
#
# main_dart (required)
# File containing the main function of the component.
#
# dart_package_name (optional)
# Name of the dart package for the component. If not provided, it will
# be inferred from the component name.
#
# package_root (optional)
# Path to the dart package for the component. If not provided, it will
# be assumed as ".".
#
# sources (optional)
# Relative path of source files to be included in the dart package for
# the component at $package_root/lib.
#
# main_dart (required)
# File containing the main function of the application. Either main_dart or
# components must be defined, but not both.
#
# package_name (optional)
# Name of the Dart package. This is used as an identifier in code that
# depends on the dart library that the *one and only* component generates.
# Only compatible when components is not specified (use
# components.dart_package_name).
#
template("_flutter_jit_component") {
pkg_name = target_name
legacy_component = false
if (!defined(invoker.components)) {
# If components is not specified, we are fitting main_dart into a component
# scope, and using that for the package.
#
# TODO(CP-140): Remove support for legacy_component once all existing calls
# to flutter_app() have a components parameter.
legacy_component = true
if (defined(invoker.fuchsia_package_name)) {
legacy_component_name = invoker.fuchsia_package_name
} else {
legacy_component_name = target_name
}
pkg_name = legacy_component_name
pkg_sources = []
if (defined(invoker.sources)) {
pkg_sources = invoker.sources
}
components = [
{
main_dart = invoker.main_dart
component_name = legacy_component_name
component_type = "flutter"
package_root = "."
deps = invoker.deps
sources = pkg_sources
},
]
}
flutter_dart_jit_component(target_name) {
forward_variables_from(invoker, "*")
}
}
# Defines AOT runtime components to be further distributed in one package.
#
# Takes a set of flutter components and puts them into one fuchsia package with
# the flutter_aot_runner as its runtime. Also supports legacy calls where the
# components parameter isn't specified, in which we will create one default
# component for the package.
#
# Parameters
#
# components (required)
# [list of scopes] Defines the components in the package. Either main_dart
# or components must be defined, but not both.
#
# Entries in a scope in the resources list:
#
# component_name (required)
# Name of the component.
#
# main_dart (required)
# File containing the main function of the component.
#
# dart_package_name (optional)
# Name of the dart package for the component. If not provided, it will
# be inferred from the component name.
#
# package_root (optional)
# Path to the dart package for the component. If not provided, it will
# be assumed as ".".
#
# sources (optional)
# Relative path of source files to be included in the dart package for
# the component at $package_root/lib.
#
# main_dart (required)
# File containing the main function of the application. Either main_dart or
# components must be defined, but not both.
#
# package_name (optional)
# Name of the Dart package. This is used as an identifier in code that
# depends on the dart library that the *one and only* component generates.
# Only compatible when components is not specified (use
# components.dart_package_name).
#
template("_flutter_aot_component") {
# This variable isn't needed in AOT builds.
if (defined(invoker.flutter_driver_extendable)) {
not_needed(invoker, [ "flutter_driver_extendable" ])
}
pkg_name = target_name
legacy_component = false
if (!defined(invoker.components)) {
# If components is not specified, we are fitting main_dart into a component
# scope, and using that for the package.
#
# TODO(CP-140): Remove support for legacy_component once all existing calls
# to flutter_app() have a components parameter.
legacy_component = true
if (defined(invoker.fuchsia_package_name)) {
legacy_component_name = invoker.fuchsia_package_name
} else {
legacy_component_name = target_name
}
pkg_name = legacy_component_name
pkg_sources = []
if (defined(invoker.sources)) {
pkg_sources = invoker.sources
}
components = [
{
main_dart = invoker.main_dart
component_name = legacy_component_name
component_type = "flutter"
package_root = "."
deps = invoker.deps
sources = pkg_sources
},
]
}
flutter_dart_aot_component(target_name) {
forward_variables_from(invoker, "*")
}
}
template("flutter_jit_app") {
template_name = "_flutter_jit_component"
if (dart_force_product) {
template_name = flutter_product_app
}
target(template_name, target_name) {
forward_variables_from(invoker, "*")
}
}
template("flutter_aot_app") {
template_name = "_flutter_aot_component"
if (dart_force_product) {
template_name = flutter_product_app
}
target(template_name, target_name) {
forward_variables_from(invoker, "*", [ "space_dart" ])
}
}
# Defines a Flutter application
#
# Parameters
#
# main_dart (required)
# Name of the Dart file containing the main function. Either main_dart or
# components must be defined, but not both.
#
# package_name (optional)
# Name of the Dart package.
#
# fuchsia_package_name (optional)
# Name of the Fuchsia package.
#
# deps (optional)
# List of Dart packages the application depends on.
#
# manifest (optional)
# Path to the manifest file
#
# disable_analysis (optional)
# Prevents analysis from being run on this target.
#
# product (optional)
# A boolean. Whether to build/run the app in a stripped-down Dart VM.
# Defaults to !is_debug.
#
# flutter_driver_extendable (optional)
# A boolean. Determines if, in a debug build, this package will be built
# with a wrapper that auto-enables flutter driver extensions when running
# the application in a an environment that includes TestRunner. Does not
# affect AOT or release builds.
#
# components (required)
# [list of scopes] Defines the components in the package. Either main_dart
# or components must be defined, but not both.
#
# Entries in a scope in the resources list:
#
# component_name (required)
# Name of the component.
#
# main_dart (required)
# File containing the main function of the component.
#
# package_root (optional)
# Path to the dart package for the component. If not provided, it will
# be assumed as ".".
#
# sources (optional)
# Relative path of source files to be included in the dart package for
# the component at $package_root/lib.
#
template("flutter_app") {
assert((defined(invoker.components) && !defined(invoker.main_dart)) ||
(!defined(invoker.components) && defined(invoker.main_dart)),
"Only one of components or main_dart should be defined")
target(flutter_default_app, target_name) {
forward_variables_from(invoker, "*", [ "aot" ])
}
}
# Defines multiple Flutter/Dart applications in one fuchsia package
#
# Parameters
#
# components (required)
# [list of scopes] Defines the components in the package. Either main_dart
# or components must be defined, but not both.
#
# Entries in a scope in the resources list:
#
# component_name (required)
# Name of the component.
#
# main_dart (required)
# File containing the main function of the component.
#
# dart_package_name (optional)
# Name of the dart package for the component. If not provided, it will
# be inferred from the component name.
#
# package_root (optional)
# Path to the dart package for the component. If not provided, it will
# be assumed as ".".
#
# sources (optional)
# Relative path of source files to be included in the dart package for
# the component at $package_root/lib.
#
template("flutter_dart_apps") {
assert(defined(invoker.components) && !defined(invoker.main_dart),
"components must be defined. Use main_dart under components instead.")
pkg_name = target_name
legacy_component = false
if (flutter_default_app == "flutter_jit_app") {
template_name = "flutter_dart_jit_component"
if (dart_force_product) {
template_name = flutter_product_app
}
target(template_name, target_name) {
forward_variables_from(invoker, "*", [ "aot" ])
}
} else {
template_name = "flutter_dart_aot_component"
if (dart_force_product) {
template_name = flutter_product_app
}
target(template_name, target_name) {
forward_variables_from(invoker,
"*",
[
"aot",
"space_dart",
])
}
}
}

View File

@@ -0,0 +1,454 @@
// Copyright 2013 The Flutter 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 "fuchsia_font_manager.h"
#include <lib/fit/function.h>
#include <lib/zx/vmar.h>
#include <unordered_map>
#include "flutter/fml/trace_event.h"
#include "logging.h"
#include "runtime/dart/utils/inlines.h"
#include "runtime/dart/utils/vmo.h"
#include "third_party/icu/source/common/unicode/uchar.h"
namespace txt {
namespace {
constexpr char kDefaultFontFamily[] = "Roboto";
void UnmapMemory(const void* buffer, uint64_t size) {
static_assert(sizeof(void*) == sizeof(uint64_t), "pointers aren't 64-bit");
zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(buffer), size);
}
struct ReleaseSkDataContext {
uint64_t buffer_size;
int buffer_id;
fit::function<void()> release_proc;
ReleaseSkDataContext(uint64_t buffer_size,
int buffer_id,
fit::function<void()> release_proc)
: buffer_size(buffer_size),
buffer_id(buffer_id),
release_proc(std::move(release_proc)) {}
};
void ReleaseSkData(const void* buffer, void* context) {
auto skdata_context = reinterpret_cast<ReleaseSkDataContext*>(context);
DEBUG_CHECK(skdata_context != nullptr, LOG_TAG, "");
UnmapMemory(buffer, skdata_context->buffer_size);
skdata_context->release_proc();
delete skdata_context;
}
sk_sp<SkData> MakeSkDataFromBuffer(const fuchsia::mem::Buffer& data,
int buffer_id,
fit::function<void()> release_proc) {
bool is_valid;
zx_status_t status = dart_utils::IsSizeValid(data, &is_valid);
if (!is_valid || data.size > std::numeric_limits<size_t>::max()) {
return nullptr;
}
uint64_t size = data.size;
uintptr_t buffer = 0;
status = zx::vmar::root_self()->map(0, data.vmo, 0, size, ZX_VM_PERM_READ,
&buffer);
if (status != ZX_OK)
return nullptr;
auto context =
new ReleaseSkDataContext(size, buffer_id, std::move(release_proc));
return SkData::MakeWithProc(reinterpret_cast<void*>(buffer), size,
ReleaseSkData, context);
}
fuchsia::fonts::Slant SkToFuchsiaSlant(SkFontStyle::Slant slant) {
switch (slant) {
case SkFontStyle::kOblique_Slant:
return fuchsia::fonts::Slant::OBLIQUE;
case SkFontStyle::kItalic_Slant:
return fuchsia::fonts::Slant::ITALIC;
case SkFontStyle::kUpright_Slant:
default:
return fuchsia::fonts::Slant::UPRIGHT;
}
}
SkFontStyle::Slant FuchsiaToSkSlant(fuchsia::fonts::Slant slant) {
switch (slant) {
case fuchsia::fonts::Slant::OBLIQUE:
return SkFontStyle::kOblique_Slant;
case fuchsia::fonts::Slant::ITALIC:
return SkFontStyle::kItalic_Slant;
case fuchsia::fonts::Slant::UPRIGHT:
default:
return SkFontStyle::kUpright_Slant;
}
}
fidl::VectorPtr<std::string> BuildLanguageList(const char* bcp47[],
int bcp47_count) {
DEBUG_CHECK(bcp47 != nullptr || bcp47_count == 0, LOG_TAG, "");
auto languages = fidl::VectorPtr<std::string>::New(0);
for (int i = 0; i < bcp47_count; i++) {
languages.push_back(bcp47[i]);
}
return languages;
}
sk_sp<SkTypeface> CreateTypefaceFromSkData(sk_sp<SkData> data, int font_index) {
return SkFontMgr::RefDefault()->makeFromData(std::move(data), font_index);
}
} // anonymous namespace
class FuchsiaFontManager::TypefaceCache {
public:
TypefaceCache() {}
~TypefaceCache();
// Get an SkTypeface with the given buffer id, font index, and buffer
// data. Creates a new SkTypeface if one does not already exist.
sk_sp<SkTypeface> GetOrCreateTypeface(
int buffer_id,
int font_index,
const fuchsia::mem::Buffer& buffer) const;
// Callback called when an SkData with the given buffer id is deleted.
void OnSkDataDeleted(int buffer_id) const;
private:
// Used to identify an SkTypeface in the cache.
struct TypefaceId {
int buffer_id;
int font_index;
// Needed by std::unordered_map.
bool operator==(const TypefaceId& other) const {
return (buffer_id == other.buffer_id && font_index == other.font_index);
}
// Used for debugging.
friend std::ostream& operator<<(std::ostream& os, const TypefaceId& id) {
return os << "TypfaceId: [buffer_id: " << id.buffer_id
<< ", font_index: " << id.font_index << "]";
}
};
// Needed by std::unordered_map.
struct TypefaceIdHash {
std::size_t operator()(const TypefaceId& id) const {
return std::hash<int>()(id.buffer_id) ^
(std::hash<int>()(id.font_index) << 1);
}
};
// Try to get an SkData with the given buffer id from the cache. If an
// SkData is not found, create it and add it to the cache.
sk_sp<SkData> GetOrCreateSkData(int buffer_id,
const fuchsia::mem::Buffer& buffer) const;
// Create a new SkTypeface for the given TypefaceId and SkData and add it to
// the cache.
sk_sp<SkTypeface> CreateSkTypeface(TypefaceId id, sk_sp<SkData> buffer) const;
mutable std::unordered_map<TypefaceId, SkTypeface*, TypefaceIdHash>
typeface_cache_;
mutable std::unordered_map<int, std::shared_ptr<BufferHolder>> buffer_cache_;
// Disallow copy and assignment.
TypefaceCache(const TypefaceCache&) = delete;
TypefaceCache& operator=(const TypefaceCache&) = delete;
};
class FuchsiaFontManager::BufferHolder {
public:
BufferHolder(const TypefaceCache* cache, int buffer_id)
: cache_(cache), buffer_id_(buffer_id) {}
~BufferHolder() {}
void SetData(SkData* data) { data_ = data; }
SkData* GetData() const { return data_; }
void OnDataDeleted() { cache_->OnSkDataDeleted(buffer_id_); }
private:
const TypefaceCache* cache_;
int buffer_id_;
SkData* data_;
// Disallow copy and assignment.
BufferHolder(const BufferHolder&) = delete;
BufferHolder& operator=(const BufferHolder&) = delete;
};
FuchsiaFontManager::TypefaceCache::~TypefaceCache() {
for (const auto& entry : typeface_cache_) {
entry.second->weak_unref();
}
}
void FuchsiaFontManager::TypefaceCache::OnSkDataDeleted(int buffer_id) const {
bool was_found = buffer_cache_.erase(buffer_id) != 0;
DEBUG_CHECK(was_found, LOG_TAG, "");
}
sk_sp<SkData> FuchsiaFontManager::TypefaceCache::GetOrCreateSkData(
int buffer_id,
const fuchsia::mem::Buffer& buffer) const {
auto iter = buffer_cache_.find(buffer_id);
if (iter != buffer_cache_.end()) {
return sk_ref_sp(iter->second->GetData());
}
auto holder = std::make_shared<BufferHolder>(this, buffer_id);
std::weak_ptr<BufferHolder> weak_holder = holder;
auto data = MakeSkDataFromBuffer(buffer, buffer_id, [weak_holder]() {
if (auto holder = weak_holder.lock()) {
holder->OnDataDeleted();
}
});
if (!data) {
return nullptr;
}
holder->SetData(data.get());
buffer_cache_[buffer_id] = std::move(holder);
return data;
}
sk_sp<SkTypeface> FuchsiaFontManager::TypefaceCache::CreateSkTypeface(
TypefaceId id,
sk_sp<SkData> buffer) const {
auto result = CreateTypefaceFromSkData(std::move(buffer), id.font_index);
result->weak_ref();
typeface_cache_[id] = result.get();
return result;
}
sk_sp<SkTypeface> FuchsiaFontManager::TypefaceCache::GetOrCreateTypeface(
int buffer_id,
int font_index,
const fuchsia::mem::Buffer& buffer) const {
auto id = TypefaceId{buffer_id, font_index};
auto iter = typeface_cache_.find(id);
if (iter != typeface_cache_.end()) {
if (iter->second->try_ref()) {
return sk_ref_sp(iter->second);
} else {
iter->second->weak_unref();
typeface_cache_.erase(iter);
}
}
sk_sp<SkData> data = GetOrCreateSkData(buffer_id, buffer);
if (!data) {
return nullptr;
}
return CreateSkTypeface(id, std::move(data));
}
class FuchsiaFontManager::FontStyleSet : public SkFontStyleSet {
public:
FontStyleSet(sk_sp<FuchsiaFontManager> font_manager,
std::string family_name,
std::vector<SkFontStyle> styles)
: font_manager_(font_manager),
family_name_(family_name),
styles_(styles) {}
~FontStyleSet() override = default;
int count() override { return styles_.size(); }
void getStyle(int index, SkFontStyle* style, SkString* style_name) override {
DEBUG_CHECK(index >= 0 && index < static_cast<int>(styles_.size()), LOG_TAG,
"");
if (style)
*style = styles_[index];
// We don't have style names. Return an empty name.
if (style_name)
style_name->reset();
}
SkTypeface* createTypeface(int index) override {
DEBUG_CHECK(index >= 0 && index < static_cast<int>(styles_.size()), LOG_TAG,
"");
if (typefaces_.empty())
typefaces_.resize(styles_.size());
if (!typefaces_[index]) {
typefaces_[index] = font_manager_->FetchTypeface(
family_name_.c_str(), styles_[index], /*bcp47=*/nullptr,
/*bcp47_count=*/0, /*character=*/0,
fuchsia::fonts::REQUEST_FLAG_NO_FALLBACK |
fuchsia::fonts::REQUEST_FLAG_EXACT_MATCH);
}
return SkSafeRef(typefaces_[index].get());
}
SkTypeface* matchStyle(const SkFontStyle& pattern) override {
return matchStyleCSS3(pattern);
}
private:
sk_sp<FuchsiaFontManager> font_manager_;
std::string family_name_;
std::vector<SkFontStyle> styles_;
std::vector<sk_sp<SkTypeface>> typefaces_;
// Disallow copy and assignment.
FontStyleSet(const FontStyleSet&) = delete;
FontStyleSet& operator=(const FontStyleSet&) = delete;
};
FuchsiaFontManager::FuchsiaFontManager(fuchsia::fonts::ProviderSyncPtr provider)
: font_provider_(std::move(provider)),
typeface_cache_(new FuchsiaFontManager::TypefaceCache()) {}
FuchsiaFontManager::~FuchsiaFontManager() = default;
int FuchsiaFontManager::onCountFamilies() const {
DEBUG_CHECK(false, LOG_TAG, "");
return 0;
}
void FuchsiaFontManager::onGetFamilyName(int index,
SkString* familyName) const {
DEBUG_CHECK(false, LOG_TAG, "");
}
SkFontStyleSet* FuchsiaFontManager::onCreateStyleSet(int index) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
SkFontStyleSet* FuchsiaFontManager::onMatchFamily(
const char family_name[]) const {
fuchsia::fonts::FamilyInfoPtr family_info;
int err = font_provider_->GetFamilyInfo(family_name, &family_info);
if (err != ZX_OK) {
#ifndef NDEBUG
FX_LOGF(ERROR, LOG_TAG,
"Error fetching family from provider [err=%d]. Did "
"you run Flutter in an environment that has a font manager?",
err);
#endif
return nullptr;
}
if (!family_info)
return nullptr;
std::vector<SkFontStyle> styles;
for (auto& style : family_info->styles) {
styles.push_back(
SkFontStyle(style.weight, style.width, FuchsiaToSkSlant(style.slant)));
}
return new FontStyleSet(sk_ref_sp(this), family_info->name,
std::move(styles));
}
SkTypeface* FuchsiaFontManager::onMatchFamilyStyle(
const char familyName[],
const SkFontStyle& style) const {
sk_sp<SkTypeface> typeface = FetchTypeface(familyName, style, nullptr, 0, 0);
return typeface.release();
}
SkTypeface* FuchsiaFontManager::onMatchFamilyStyleCharacter(
const char familyName[],
const SkFontStyle& style,
const char* bcp47[],
int bcp47_count,
SkUnichar character) const {
sk_sp<SkTypeface> typeface =
FetchTypeface(kDefaultFontFamily, style, bcp47, bcp47_count, character);
return typeface.release();
}
SkTypeface* FuchsiaFontManager::onMatchFaceStyle(const SkTypeface*,
const SkFontStyle&) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::onMakeFromData(sk_sp<SkData>,
int ttcIndex) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::onMakeFromStreamIndex(
std::unique_ptr<SkStreamAsset>,
int ttcIndex) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::onMakeFromStreamArgs(
std::unique_ptr<SkStreamAsset>,
const SkFontArguments&) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::onMakeFromFile(const char path[],
int ttcIndex) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::onLegacyMakeTypeface(
const char familyName[],
SkFontStyle) const {
DEBUG_CHECK(false, LOG_TAG, "");
return nullptr;
}
sk_sp<SkTypeface> FuchsiaFontManager::FetchTypeface(const char family_name[],
const SkFontStyle& style,
const char* bcp47[],
int bcp47_count,
SkUnichar character,
uint32_t flags) const {
TRACE_EVENT0("flutter", "FuchsiaFontManager::FetchTypeface");
fuchsia::fonts::Request request;
request.family = family_name;
request.weight = style.weight();
request.width = style.width();
request.slant = SkToFuchsiaSlant(style.slant());
request.language = BuildLanguageList(bcp47, bcp47_count);
request.character = character;
request.flags = flags;
fuchsia::fonts::ResponsePtr response;
int err = font_provider_->GetFont(std::move(request), &response);
if (err != ZX_OK) {
#ifndef NDEBUG
FX_LOGF(ERROR, LOG_TAG,
"Error fetching font from provider [err=%d]. Did "
"you run Flutter in an environment that has a font manager?",
err);
#endif
return nullptr;
}
// The service may return null response if there is no font matching the
// request.
if (!response) {
return nullptr;
}
return typeface_cache_->GetOrCreateTypeface(
response->buffer_id, response->font_index, response->buffer);
}
} // namespace txt

View File

@@ -0,0 +1,92 @@
// Copyright 2013 The Flutter 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_FUCHSIA_FONT_MANAGER_H_
#define TXT_FUCHSIA_FONT_MANAGER_H_
#include <fuchsia/fonts/cpp/fidl.h>
#include <memory>
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace txt {
class FuchsiaFontManager final : public SkFontMgr {
public:
FuchsiaFontManager(fuchsia::fonts::ProviderSyncPtr provider);
~FuchsiaFontManager() override;
protected:
// |SkFontMgr|
int onCountFamilies() const override;
// |SkFontMgr|
void onGetFamilyName(int index, SkString* familyName) const override;
// |SkFontMgr|
SkFontStyleSet* onMatchFamily(const char familyName[]) const override;
// |SkFontMgr|
SkFontStyleSet* onCreateStyleSet(int index) 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|
sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData>, int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset>,
int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset>,
const SkFontArguments&) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onMakeFromFile(const char path[],
int ttcIndex) const override;
// |SkFontMgr|
sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[],
SkFontStyle) const override;
private:
class BufferHolder;
class TypefaceCache;
class FontStyleSet;
friend class FontStyleSet;
sk_sp<SkTypeface> FetchTypeface(const char family_name[],
const SkFontStyle& style,
const char* bcp47[],
int bcp47_count,
SkUnichar character,
uint32_t flags = 0) const;
mutable fuchsia::fonts::ProviderSyncPtr font_provider_;
std::unique_ptr<TypefaceCache> typeface_cache_;
// Disallow copy and assignment.
FuchsiaFontManager(const FuchsiaFontManager&) = delete;
FuchsiaFontManager& operator=(const FuchsiaFontManager&) = delete;
};
} // namespace txt
#endif // TXT_FUCHSIA_FONT_MANAGER_H_

View File

@@ -0,0 +1,202 @@
// Copyright 2013 The Flutter 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 "topaz/runtime/flutter_runner/fuchsia_font_manager.h"
#include <fcntl.h>
#include <fuchsia/fonts/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/fdio/fd.h>
#include <lib/gtest/real_loop_fixture.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/zx/channel.h>
#include <lib/zx/handle.h>
#include <memory>
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace {
zx::channel CloneChannelFromFileDescriptor(int fd) {
zx::handle handle;
zx_status_t status = fdio_fd_clone(fd, handle.reset_and_get_address());
if (status != ZX_OK)
return zx::channel();
zx_info_handle_basic_t info = {};
status =
handle.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info), NULL, NULL);
if (status != ZX_OK || info.type != ZX_OBJ_TYPE_CHANNEL)
return zx::channel();
return zx::channel(handle.release());
}
} // namespace
namespace txt {
namespace {
// A codepoint guaranteed to be unknown in any font/family.
constexpr SkUnichar kUnknownUnicodeCharacter = 0xFFF0;
// Font family to use for tests.
constexpr char kTestFontFamily[] = "Roboto";
// URL for the fonts service.
constexpr char kFontsServiceUrl[] =
"fuchsia-pkg://fuchsia.com/fonts#meta/fonts.cmx";
class FuchsiaFontManagerTest : public gtest::RealLoopFixture {
public:
FuchsiaFontManagerTest() {
auto services = sys::ServiceDirectory::CreateFromNamespace();
// Grab launcher and launch font provider.
fuchsia::sys::LauncherPtr launcher;
services->Connect(launcher.NewRequest());
zx::channel out_services_request;
auto font_services =
sys::ServiceDirectory::CreateWithRequest(&out_services_request);
auto launch_info_font_service = GetLaunchInfoForFontService();
launch_info_font_service.directory_request =
std::move(out_services_request);
launcher->CreateComponent(std::move(launch_info_font_service),
font_service_controller_.NewRequest());
// Connect to the font provider service and then wrap it inside the font
// manager we will be testing.
fuchsia::fonts::ProviderSyncPtr provider_ptr;
font_services->Connect(provider_ptr.NewRequest());
font_manager_ = sk_make_sp<FuchsiaFontManager>(std::move(provider_ptr));
}
fuchsia::sys::LaunchInfo GetLaunchInfoForFontService() {
fuchsia::sys::LaunchInfo launch_info;
launch_info.url = kFontsServiceUrl;
launch_info.arguments.reset(
{"--no-default-fonts", "--font-manifest=/test_fonts/manifest.json"});
auto tmp_dir_fd =
open("/pkg/data/testdata/test_fonts", O_DIRECTORY | O_RDONLY);
launch_info.flat_namespace = fuchsia::sys::FlatNamespace::New();
launch_info.flat_namespace->paths.push_back("/test_fonts");
launch_info.flat_namespace->directories.push_back(
CloneChannelFromFileDescriptor(tmp_dir_fd));
close(tmp_dir_fd);
return launch_info;
}
protected:
fuchsia::sys::ComponentControllerPtr font_service_controller_;
sk_sp<SkFontMgr> font_manager_;
};
// Verify that a typeface is returned for a found character.
TEST_F(FuchsiaFontManagerTest, ValidResponseWhenCharacterFound) {
sk_sp<SkTypeface> typeface(font_manager_->matchFamilyStyleCharacter(
"", SkFontStyle(), nullptr, 0, '&'));
EXPECT_TRUE(typeface.get() != nullptr);
}
// Verify that a codepoint that doesn't map to a character correctly returns
// an empty typeface.
TEST_F(FuchsiaFontManagerTest, EmptyResponseWhenCharacterNotFound) {
sk_sp<SkTypeface> typeface(font_manager_->matchFamilyStyleCharacter(
"", SkFontStyle(), nullptr, 0, kUnknownUnicodeCharacter));
EXPECT_TRUE(typeface.get() == nullptr);
}
// Verify that SkTypeface objects are cached.
TEST_F(FuchsiaFontManagerTest, Caching) {
sk_sp<SkTypeface> typeface(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
sk_sp<SkTypeface> typeface2(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
// Expect that the same SkTypeface is returned for both requests.
EXPECT_EQ(typeface.get(), typeface2.get());
// Request a different typeface and verify that a different SkTypeface is
// returned.
sk_sp<SkTypeface> typeface3(
font_manager_->matchFamilyStyle("Roboto Slab", SkFontStyle()));
EXPECT_NE(typeface.get(), typeface3.get());
}
// Verify that SkTypeface can outlive the manager.
TEST_F(FuchsiaFontManagerTest, TypefaceOutlivesManager) {
sk_sp<SkTypeface> typeface(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
font_manager_.reset();
EXPECT_TRUE(typeface.get() != nullptr);
}
// Verify that we can query a font after releasing a previous instance.
TEST_F(FuchsiaFontManagerTest, ReleaseThenCreateAgain) {
sk_sp<SkTypeface> typeface(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
EXPECT_TRUE(typeface != nullptr);
typeface.reset();
sk_sp<SkTypeface> typeface2(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
EXPECT_TRUE(typeface2 != nullptr);
}
// Verify that we get a new typeface instance after releasing a previous
// instance of the same typeface (i.e. the cache purges the released typeface).
TEST_F(FuchsiaFontManagerTest, ReleasedTypefaceIsPurged) {
sk_sp<SkTypeface> typeface(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
EXPECT_TRUE(typeface != nullptr);
typeface.reset();
sk_sp<SkTypeface> typeface2(
font_manager_->matchFamilyStyle(kTestFontFamily, SkFontStyle()));
EXPECT_TRUE(typeface2 != nullptr);
EXPECT_NE(typeface.get(), typeface2.get());
}
// Verify that unknown font families are handled correctly.
TEST_F(FuchsiaFontManagerTest, MatchUnknownFamily) {
SkFontStyleSet* style_set = font_manager_->matchFamily("unknown");
EXPECT_TRUE(style_set == nullptr || style_set->count() == 0);
}
// Verify that a style set is returned for a known family.
TEST_F(FuchsiaFontManagerTest, MatchKnownFamily) {
SkFontStyleSet* style_set = font_manager_->matchFamily(kTestFontFamily);
EXPECT_GT(style_set->count(), 0);
}
// Verify getting an SkFontStyle from a matched family.
TEST_F(FuchsiaFontManagerTest, FontFamilyGetStyle) {
SkFontStyleSet* style_set = font_manager_->matchFamily(kTestFontFamily);
SkFontStyle style;
style_set->getStyle(0, &style, nullptr);
EXPECT_EQ(style.weight(), 400);
EXPECT_EQ(style.width(), 5);
EXPECT_EQ(style.slant(), SkFontStyle::kUpright_Slant);
}
// Verify creating a typeface from a matched family.
TEST_F(FuchsiaFontManagerTest, FontFamilyCreateTypeface) {
SkFontStyleSet* style_set = font_manager_->matchFamily(kTestFontFamily);
SkTypeface* typeface = style_set->createTypeface(0);
EXPECT_TRUE(typeface != nullptr);
SkFontStyle style = typeface->fontStyle();
EXPECT_EQ(style.weight(), 400);
EXPECT_EQ(style.width(), 5);
EXPECT_EQ(style.slant(), SkFontStyle::kUpright_Slant);
}
} // namespace
} // namespace txt

View File

@@ -0,0 +1,91 @@
// Copyright 2013 The Flutter 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 "isolate_configurator.h"
#include "dart-pkg/fuchsia/sdk_ext/fuchsia.h"
#include "dart-pkg/zircon/sdk_ext/handle.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_error.h"
namespace flutter_runner {
IsolateConfigurator::IsolateConfigurator(
UniqueFDIONS fdio_ns,
fidl::InterfaceHandle<fuchsia::sys::Environment> environment,
zx::channel directory_request)
: fdio_ns_(std::move(fdio_ns)),
environment_(std::move(environment)),
directory_request_(std::move(directory_request)) {}
IsolateConfigurator::~IsolateConfigurator() = default;
bool IsolateConfigurator::ConfigureCurrentIsolate() {
if (used_) {
return false;
}
used_ = true;
BindFuchsia();
BindZircon();
BindDartIO();
// This is now owned by the Dart bindings. So relinquish our ownership of the
// handle.
(void)fdio_ns_.release();
return true;
}
void IsolateConfigurator::BindFuchsia() {
fuchsia::dart::Initialize(std::move(environment_),
std::move(directory_request_));
}
void IsolateConfigurator::BindZircon() {
// Tell dart:zircon about the FDIO namespace configured for this instance.
Dart_Handle zircon_lib = Dart_LookupLibrary(tonic::ToDart("dart:zircon"));
FML_CHECK(!tonic::LogIfError(zircon_lib));
Dart_Handle namespace_type =
Dart_GetType(zircon_lib, tonic::ToDart("_Namespace"), 0, nullptr);
FML_CHECK(!tonic::LogIfError(namespace_type));
Dart_Handle result =
Dart_SetField(namespace_type, //
tonic::ToDart("_namespace"), //
tonic::ToDart(reinterpret_cast<intptr_t>(fdio_ns_.get())));
FML_CHECK(!tonic::LogIfError(result));
}
void IsolateConfigurator::BindDartIO() {
// Grab the dart:io lib.
Dart_Handle io_lib = Dart_LookupLibrary(tonic::ToDart("dart:io"));
FML_CHECK(!tonic::LogIfError(io_lib));
// Disable dart:io exit()
Dart_Handle embedder_config_type =
Dart_GetType(io_lib, tonic::ToDart("_EmbedderConfig"), 0, nullptr);
FML_CHECK(!tonic::LogIfError(embedder_config_type));
Dart_Handle result = Dart_SetField(embedder_config_type,
tonic::ToDart("_mayExit"), Dart_False());
FML_CHECK(!tonic::LogIfError(result));
// Tell dart:io about the FDIO namespace configured for this instance.
Dart_Handle namespace_type =
Dart_GetType(io_lib, tonic::ToDart("_Namespace"), 0, nullptr);
FML_CHECK(!tonic::LogIfError(namespace_type));
Dart_Handle namespace_args[] = {
Dart_NewInteger(reinterpret_cast<intptr_t>(fdio_ns_.get())), //
};
result = Dart_Invoke(namespace_type, tonic::ToDart("_setupNamespace"), 1,
namespace_args);
FML_CHECK(!tonic::LogIfError(result));
}
} // namespace flutter_runner

View File

@@ -0,0 +1,49 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_ISOLATE_CONFIGURATOR_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_ISOLATE_CONFIGURATOR_H_
#include <fuchsia/sys/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include "flutter/fml/macros.h"
#include "unique_fdio_ns.h"
namespace flutter_runner {
// Contains all the information necessary to configure a new root isolate. This
// is a single use item. The lifetime of this object must extend past that of
// the root isolate.
class IsolateConfigurator final {
public:
IsolateConfigurator(
UniqueFDIONS fdio_ns,
fidl::InterfaceHandle<fuchsia::sys::Environment> environment,
zx::channel directory_request);
~IsolateConfigurator();
// Can be used only once and only on the UI thread with the newly created
// isolate already current.
bool ConfigureCurrentIsolate();
private:
bool used_ = false;
UniqueFDIONS fdio_ns_;
fidl::InterfaceHandle<fuchsia::sys::Environment> environment_;
zx::channel directory_request_;
void BindFuchsia();
void BindZircon();
void BindDartIO();
FML_DISALLOW_COPY_AND_ASSIGN(IsolateConfigurator);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_ISOLATE_CONFIGURATOR_H_

View File

@@ -0,0 +1,209 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/dart/dart_tool.gni")
import("//build/host.gni")
import("//third_party/dart/utils/compile_platform.gni")
import("//topaz/runtime/dart/dart_component.gni")
import("//topaz/runtime/dart/dart_kernel.gni")
import("//topaz/runtime/flutter_runner/prebuilt_framework.gni")
compile_platform("kernel_platform_files") {
single_root_scheme = "org-dartlang-sdk"
single_root_base = rebase_path("../../../../")
libraries_specification_uri =
"org-dartlang-sdk:///topaz/runtime/flutter_runner/kernel/libraries.json"
outputs = [
"$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill",
"$root_out_dir/flutter_runner_patched_sdk/vm_outline_strong.dill",
]
args = [
# TODO(dartbug.com/36342): enable bytecode for core libraries when performance of bytecode
# pipeline is on par with default pipeline and continuously tracked.
# "--bytecode",
"--target=flutter_runner",
"dart:core",
]
}
dart_kernel("framework_shim") {
platform_name = "flutter_runner"
platform_deps =
[ "//topaz/runtime/flutter_runner/kernel:kernel_platform_files" ]
platform_path = "$root_out_dir/flutter_runner_patched_sdk"
disable_analysis = true
gen_bytecode = true
args = []
main_dart = "framework_shim.dart"
deps = [
"//third_party/dart-pkg/git/flutter/packages/flutter",
]
manifest = "$target_gen_dir/framework_shim.dilpmanifest"
}
template("core_snapshot") {
assert(defined(invoker.product),
"core_snapshot requires 'product' to be defined")
assert(defined(invoker.framework),
"core_snapshot requires 'framework' to be defined")
suffix = ""
if (invoker.product) {
suffix = "${suffix}_product"
}
if (invoker.framework) {
suffix = "${suffix}_framework"
}
action(target_name) {
deps = gen_snapshot_deps + [ ":kernel_platform_files" ]
platform_dill =
"$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill"
compilation_trace = "//topaz/runtime/flutter_runner/compilation_trace.txt"
inputs = [
platform_dill,
compilation_trace,
]
vm_snapshot_data = "$target_gen_dir/vm_isolate_snapshot${suffix}.bin"
vm_snapshot_instructions =
"$target_gen_dir/vm_snapshot_instructions${suffix}.bin"
isolate_snapshot_data = "$target_gen_dir/isolate_snapshot${suffix}.bin"
isolate_snapshot_instructions =
"$target_gen_dir/isolate_snapshot_instructions${suffix}.bin"
snapshot_profile = "$target_gen_dir/snapshot_profile${suffix}.json"
outputs = [
vm_snapshot_data,
vm_snapshot_instructions,
isolate_snapshot_data,
isolate_snapshot_instructions,
snapshot_profile,
]
if (invoker.product) {
script = gen_snapshot_product
} else {
script = gen_snapshot
}
args = [
# TODO(FL-117): Re-enable causal async stack traces when this issue is
# addressed.
"--no_causal_async_stacks",
"--use_bytecode_compiler",
"--enable_mirrors=false",
"--deterministic",
"--snapshot_kind=core-jit",
"--load_compilation_trace=" +
rebase_path(compilation_trace, root_build_dir),
"--vm_snapshot_data=" + rebase_path(vm_snapshot_data, root_build_dir),
"--vm_snapshot_instructions=" +
rebase_path(vm_snapshot_instructions, root_build_dir),
"--isolate_snapshot_data=" +
rebase_path(isolate_snapshot_data, root_build_dir),
"--isolate_snapshot_instructions=" +
rebase_path(isolate_snapshot_instructions, root_build_dir),
"--write_v8_snapshot_profile_to=" +
rebase_path(snapshot_profile, root_build_dir),
]
# No asserts in debug or release product.
# No asserts in release with flutter_profile=true (non-product)
# Yes asserts in non-product debug.
if (!invoker.product && (!flutter_profile || is_debug)) {
args += [ "--enable_asserts" ]
}
args += [ rebase_path(platform_dill) ]
if (invoker.framework) {
if (prebuilt_framework_path == "") {
deps += [ ":framework_shim_kernel" ]
inputs += [ "$target_gen_dir/framework_shim_kernel.dil" ]
args += [ rebase_path("$target_gen_dir/framework_shim_kernel.dil") ]
} else {
deps += [ ":extract_prebuilt_framework" ]
foreach(package, framework_packages) {
args += [ rebase_path(
"$target_gen_dir/data/$prebuilt_framework_name/$package.dilp") ]
inputs +=
[ "$target_gen_dir/data/$prebuilt_framework_name/$package.dilp" ]
}
}
}
}
}
core_snapshot("kernel_core_snapshot") {
product = false
framework = false
}
core_snapshot("kernel_core_snapshot_framework") {
product = false
framework = true
}
core_snapshot("kernel_core_snapshot_product") {
product = true
framework = false
}
core_snapshot("kernel_core_snapshot_product_framework") {
product = true
framework = true
}
dart_tool("extract_far") {
main_dart = "extract_far.dart"
force_prebuilt_dart = true
disable_analysis = true
source_dir = "."
sources = [
"extract_far.dart",
]
deps = [
"//third_party/dart-pkg/pub/args",
]
}
if (prebuilt_framework_path != "") {
action("extract_prebuilt_framework") {
deps = [
":extract_far",
"//garnet/bin/far:host",
]
inputs = [
prebuilt_framework_path,
]
script = get_label_info(":extract_far", "root_out_dir") +
"/dart-tools/extract_far"
args = [
"--far-tool",
rebase_path("$host_tools_dir/far"),
"--archive",
rebase_path(prebuilt_framework_path),
"--out-dir",
rebase_path(target_gen_dir),
]
outputs = []
foreach(package, framework_packages) {
args += [ "data/$prebuilt_framework_name/$package.dilp" ]
outputs +=
[ "$target_gen_dir/data/$prebuilt_framework_name/$package.dilp" ]
}
args += [ "data/$prebuilt_framework_name/app.frameworkversion" ]
outputs +=
[ "$target_gen_dir/data/$prebuilt_framework_name/app.frameworkversion" ]
}
}

View File

@@ -0,0 +1,12 @@
# Copyright 2013 The Flutter 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: ../../../tools/analysis_options.yaml
analyzer:
errors:
avoid_catches_without_on_clauses: ignore
cascade_invocations: ignore
only_throw_errors: ignore # adds noise to error messages
prefer_foreach: ignore # for-in is preferable to closurization
prefer_single_quotes: ignore

View File

@@ -0,0 +1,83 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:io";
import "package:args/args.dart";
Future<void> main(List<String> args) async {
final parser = new ArgParser();
parser.addOption("far-tool", help: "Path to `far` tool");
parser.addOption("archive", help: "Path to the far archive to extract from");
parser.addOption("out-dir", help: "Path to output directory");
final usage = """
Usage: extract_far.dart [options] {paths}
Options:
${parser.usage};
""";
ArgResults options;
try {
options = parser.parse(args);
if (options["far-tool"] == null) {
throw "Must specify --far-tool";
}
if (options["archive"] == null) {
throw "Must specify --archive";
}
if (options["out-dir"] == null) {
throw "Must specify --out-dir";
}
} catch (e) {
print("ERROR: $e\n");
print(usage);
exitCode = 1;
return;
}
await run(options);
}
Future<void> run(ArgResults options) async {
final far = options["far-tool"];
Future<void> extract(String archive, String file, String output) async {
await new File(output).parent.create(recursive: true);
final args = ["extract-file", "--archive=$archive", "--file=$file", "--output=$output"];
final result = await Process.run(far, args);
if (result.exitCode != 0) {
print(result.stdout);
print(result.stderr);
throw "Command failed: $far $args";
}
}
final outerArchive = options["archive"];
final outDir = options["out-dir"];
final innerArchive = "$outDir/meta.far";
await extract(outerArchive, "meta.far", innerArchive);
final manifest = "$outDir/meta/contents";
await extract(innerArchive, "meta/contents", manifest);
final blobNames = <String, String>{};
for (final line in await new File(manifest).readAsLines()) {
final pivot = line.lastIndexOf("=");
blobNames[line.substring(0, pivot)] = line.substring(pivot + 1, line.length);
}
for (final path in options.rest) {
final blobName = blobNames[path];
if (blobName == null) {
print("Archive contents: ");
for (final key in blobNames.keys) {
print(key);
}
throw "$outerArchive does not contain $path";
}
await extract(outerArchive, blobName, "$outDir/$path");
}
}

View File

@@ -0,0 +1,7 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
main() {}

View File

@@ -0,0 +1,164 @@
{
"comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.",
"comment:1": "Instead modify 'topaz/runtime/flutter_runner/kernel/libraries.yaml' and follow the instructions therein.",
"flutter_runner": {
"libraries": {
"_builtin": {
"uri": "../../../../third_party/dart/runtime/bin/builtin.dart"
},
"core": {
"patches": [
"../../../../third_party/dart/runtime/lib/core_patch.dart",
"../../../../third_party/dart/runtime/lib/array.dart",
"../../../../third_party/dart/runtime/lib/array_patch.dart",
"../../../../third_party/dart/runtime/lib/bigint_patch.dart",
"../../../../third_party/dart/runtime/lib/bool_patch.dart",
"../../../../third_party/dart/runtime/lib/date_patch.dart",
"../../../../third_party/dart/runtime/lib/double.dart",
"../../../../third_party/dart/runtime/lib/double_patch.dart",
"../../../../third_party/dart/runtime/lib/errors_patch.dart",
"../../../../third_party/dart/runtime/lib/expando_patch.dart",
"../../../../third_party/dart/runtime/lib/function.dart",
"../../../../third_party/dart/runtime/lib/function_patch.dart",
"../../../../third_party/dart/runtime/lib/growable_array.dart",
"../../../../third_party/dart/runtime/lib/identical_patch.dart",
"../../../../third_party/dart/runtime/lib/immutable_map.dart",
"../../../../third_party/dart/runtime/lib/integers.dart",
"../../../../third_party/dart/runtime/lib/integers_patch.dart",
"../../../../third_party/dart/runtime/lib/invocation_mirror_patch.dart",
"../../../../third_party/dart/runtime/lib/lib_prefix.dart",
"../../../../third_party/dart/runtime/lib/map_patch.dart",
"../../../../third_party/dart/runtime/lib/null_patch.dart",
"../../../../third_party/dart/runtime/lib/object_patch.dart",
"../../../../third_party/dart/runtime/lib/regexp_patch.dart",
"../../../../third_party/dart/runtime/lib/stacktrace.dart",
"../../../../third_party/dart/runtime/lib/stopwatch_patch.dart",
"../../../../third_party/dart/runtime/lib/string_buffer_patch.dart",
"../../../../third_party/dart/runtime/lib/string_patch.dart",
"../../../../third_party/dart/runtime/lib/type_patch.dart",
"../../../../third_party/dart/runtime/lib/uri_patch.dart",
"../../../../third_party/dart/runtime/lib/weak_property.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/core/core.dart"
},
"zircon": {
"uri": "../../../../topaz/public/dart-pkg/zircon/lib/zircon.dart"
},
"async": {
"patches": [
"../../../../third_party/dart/runtime/lib/async_patch.dart",
"../../../../third_party/dart/runtime/lib/deferred_load_patch.dart",
"../../../../third_party/dart/runtime/lib/schedule_microtask_patch.dart",
"../../../../third_party/dart/runtime/lib/timer_patch.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/async/async.dart"
},
"mozart.internal": {
"uri": "../../../../topaz/public/lib/ui/flutter/sdk_ext/mozart.dart"
},
"collection": {
"patches": [
"../../../../third_party/dart/runtime/lib/collection_patch.dart",
"../../../../third_party/dart/runtime/lib/compact_hash.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/collection/collection.dart"
},
"ffi": {
"patches": [
"../../../../third_party/dart/runtime/lib/ffi_dynamic_library_patch.dart",
"../../../../third_party/dart/runtime/lib/ffi_native_type_patch.dart",
"../../../../third_party/dart/runtime/lib/ffi_patch.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/ffi/ffi.dart"
},
"typed_data": {
"patches": "../../../../third_party/dart/runtime/lib/typed_data_patch.dart",
"uri": "../../../../third_party/dart/sdk/lib/typed_data/typed_data.dart"
},
"nativewrappers": {
"uri": "../../../../third_party/dart/sdk/lib/html/dartium/nativewrappers.dart"
},
"developer": {
"patches": [
"../../../../third_party/dart/runtime/lib/developer.dart",
"../../../../third_party/dart/runtime/lib/profiler.dart",
"../../../../third_party/dart/runtime/lib/timeline.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/developer/developer.dart"
},
"isolate": {
"patches": [
"../../../../third_party/dart/runtime/lib/isolate_patch.dart",
"../../../../third_party/dart/runtime/lib/timer_impl.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/isolate/isolate.dart"
},
"mirrors": {
"patches": [
"../../../../third_party/dart/runtime/lib/mirrors_patch.dart",
"../../../../third_party/dart/runtime/lib/mirrors_impl.dart",
"../../../../third_party/dart/runtime/lib/mirror_reference.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/mirrors/mirrors.dart"
},
"_vmservice": {
"uri": "../../../../third_party/dart/sdk/lib/vmservice/vmservice.dart"
},
"io": {
"patches": [
"../../../../third_party/dart/runtime/bin/common_patch.dart",
"../../../../third_party/dart/runtime/bin/directory_patch.dart",
"../../../../third_party/dart/runtime/bin/eventhandler_patch.dart",
"../../../../third_party/dart/runtime/bin/file_patch.dart",
"../../../../third_party/dart/runtime/bin/file_system_entity_patch.dart",
"../../../../third_party/dart/runtime/bin/filter_patch.dart",
"../../../../third_party/dart/runtime/bin/io_service_patch.dart",
"../../../../third_party/dart/runtime/bin/namespace_patch.dart",
"../../../../third_party/dart/runtime/bin/platform_patch.dart",
"../../../../third_party/dart/runtime/bin/process_patch.dart",
"../../../../third_party/dart/runtime/bin/socket_patch.dart",
"../../../../third_party/dart/runtime/bin/stdio_patch.dart",
"../../../../third_party/dart/runtime/bin/secure_socket_patch.dart",
"../../../../third_party/dart/runtime/bin/sync_socket_patch.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/io/io.dart"
},
"_internal": {
"patches": [
"../../../../third_party/dart/runtime/lib/internal_patch.dart",
"../../../../third_party/dart/runtime/lib/class_id_fasta.dart",
"../../../../third_party/dart/runtime/lib/print_patch.dart",
"../../../../third_party/dart/runtime/lib/symbol_patch.dart",
"../../../../third_party/dart/sdk/lib/internal/patch.dart"
],
"uri": "../../../../third_party/dart/sdk/lib/internal/internal.dart"
},
"convert": {
"patches": "../../../../third_party/dart/runtime/lib/convert_patch.dart",
"uri": "../../../../third_party/dart/sdk/lib/convert/convert.dart"
},
"profiler": {
"uri": "../../../../third_party/dart/sdk/lib/profiler/profiler.dart"
},
"math": {
"patches": "../../../../third_party/dart/runtime/lib/math_patch.dart",
"uri": "../../../../third_party/dart/sdk/lib/math/math.dart"
},
"_http": {
"uri": "../../../../third_party/dart/sdk/lib/_http/http.dart"
},
"fuchsia": {
"uri": "../../../../topaz/public/dart-pkg/fuchsia/lib/fuchsia.dart"
},
"fuchsia.builtin": {
"uri": "../../../../topaz/runtime/dart_runner/embedder/builtin.dart"
},
"ui": {
"uri": "../../../../third_party/flutter/lib/ui/ui.dart"
},
"vmservice_io": {
"uri": "../../../../third_party/dart/runtime/bin/vmservice/vmservice_io.dart"
}
}
}
}

View File

@@ -0,0 +1,163 @@
# Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# Note: if you edit this file, you must also edit libraries.json in this
# directory:
#
# python third_party/dart/tools/yaml2json.py \
# topaz/runtime/flutter_runner/kernel/libraries.yaml \
# topaz/runtime/flutter_runner/kernel/libraries.json
#
# We currently have several different files that needs to be updated when
# changing libraries, sources, and patch files. See
# https://github.com/dart-lang/sdk/issues/28836.
flutter_runner:
libraries:
_builtin:
uri: "../../../../third_party/dart/runtime/bin/builtin.dart"
_internal:
uri: "../../../../third_party/dart/sdk/lib/internal/internal.dart"
patches:
- "../../../../third_party/dart/runtime/lib/internal_patch.dart"
- "../../../../third_party/dart/runtime/lib/class_id_fasta.dart"
- "../../../../third_party/dart/runtime/lib/print_patch.dart"
- "../../../../third_party/dart/runtime/lib/symbol_patch.dart"
- "../../../../third_party/dart/sdk/lib/internal/patch.dart"
async:
uri: "../../../../third_party/dart/sdk/lib/async/async.dart"
patches:
- "../../../../third_party/dart/runtime/lib/async_patch.dart"
- "../../../../third_party/dart/runtime/lib/deferred_load_patch.dart"
- "../../../../third_party/dart/runtime/lib/schedule_microtask_patch.dart"
- "../../../../third_party/dart/runtime/lib/timer_patch.dart"
collection:
uri: "../../../../third_party/dart/sdk/lib/collection/collection.dart"
patches:
- "../../../../third_party/dart/runtime/lib/collection_patch.dart"
- "../../../../third_party/dart/runtime/lib/compact_hash.dart"
convert:
uri: "../../../../third_party/dart/sdk/lib/convert/convert.dart"
patches: "../../../../third_party/dart/runtime/lib/convert_patch.dart"
core:
uri: "../../../../third_party/dart/sdk/lib/core/core.dart"
patches:
- "../../../../third_party/dart/runtime/lib/core_patch.dart"
- "../../../../third_party/dart/runtime/lib/array.dart"
- "../../../../third_party/dart/runtime/lib/array_patch.dart"
- "../../../../third_party/dart/runtime/lib/bigint_patch.dart"
- "../../../../third_party/dart/runtime/lib/bool_patch.dart"
- "../../../../third_party/dart/runtime/lib/date_patch.dart"
- "../../../../third_party/dart/runtime/lib/double.dart"
- "../../../../third_party/dart/runtime/lib/double_patch.dart"
- "../../../../third_party/dart/runtime/lib/errors_patch.dart"
- "../../../../third_party/dart/runtime/lib/expando_patch.dart"
- "../../../../third_party/dart/runtime/lib/function.dart"
- "../../../../third_party/dart/runtime/lib/function_patch.dart"
- "../../../../third_party/dart/runtime/lib/growable_array.dart"
- "../../../../third_party/dart/runtime/lib/identical_patch.dart"
- "../../../../third_party/dart/runtime/lib/immutable_map.dart"
- "../../../../third_party/dart/runtime/lib/integers.dart"
- "../../../../third_party/dart/runtime/lib/integers_patch.dart"
- "../../../../third_party/dart/runtime/lib/invocation_mirror_patch.dart"
- "../../../../third_party/dart/runtime/lib/lib_prefix.dart"
- "../../../../third_party/dart/runtime/lib/map_patch.dart"
- "../../../../third_party/dart/runtime/lib/null_patch.dart"
- "../../../../third_party/dart/runtime/lib/object_patch.dart"
- "../../../../third_party/dart/runtime/lib/regexp_patch.dart"
- "../../../../third_party/dart/runtime/lib/stacktrace.dart"
- "../../../../third_party/dart/runtime/lib/stopwatch_patch.dart"
- "../../../../third_party/dart/runtime/lib/string_buffer_patch.dart"
- "../../../../third_party/dart/runtime/lib/string_patch.dart"
- "../../../../third_party/dart/runtime/lib/type_patch.dart"
- "../../../../third_party/dart/runtime/lib/uri_patch.dart"
- "../../../../third_party/dart/runtime/lib/weak_property.dart"
developer:
uri: "../../../../third_party/dart/sdk/lib/developer/developer.dart"
patches:
- "../../../../third_party/dart/runtime/lib/developer.dart"
- "../../../../third_party/dart/runtime/lib/profiler.dart"
- "../../../../third_party/dart/runtime/lib/timeline.dart"
ffi:
uri: "../../../../third_party/dart/sdk/lib/ffi/ffi.dart"
patches:
- "../../../../third_party/dart/runtime/lib/ffi_dynamic_library_patch.dart"
- "../../../../third_party/dart/runtime/lib/ffi_native_type_patch.dart"
- "../../../../third_party/dart/runtime/lib/ffi_patch.dart"
_http:
uri: "../../../../third_party/dart/sdk/lib/_http/http.dart"
io:
uri: "../../../../third_party/dart/sdk/lib/io/io.dart"
patches:
- "../../../../third_party/dart/runtime/bin/common_patch.dart"
- "../../../../third_party/dart/runtime/bin/directory_patch.dart"
- "../../../../third_party/dart/runtime/bin/eventhandler_patch.dart"
- "../../../../third_party/dart/runtime/bin/file_patch.dart"
- "../../../../third_party/dart/runtime/bin/file_system_entity_patch.dart"
- "../../../../third_party/dart/runtime/bin/filter_patch.dart"
- "../../../../third_party/dart/runtime/bin/io_service_patch.dart"
- "../../../../third_party/dart/runtime/bin/namespace_patch.dart"
- "../../../../third_party/dart/runtime/bin/platform_patch.dart"
- "../../../../third_party/dart/runtime/bin/process_patch.dart"
- "../../../../third_party/dart/runtime/bin/socket_patch.dart"
- "../../../../third_party/dart/runtime/bin/stdio_patch.dart"
- "../../../../third_party/dart/runtime/bin/secure_socket_patch.dart"
- "../../../../third_party/dart/runtime/bin/sync_socket_patch.dart"
isolate:
uri: "../../../../third_party/dart/sdk/lib/isolate/isolate.dart"
patches:
- "../../../../third_party/dart/runtime/lib/isolate_patch.dart"
- "../../../../third_party/dart/runtime/lib/timer_impl.dart"
math:
uri: "../../../../third_party/dart/sdk/lib/math/math.dart"
patches: "../../../../third_party/dart/runtime/lib/math_patch.dart"
mirrors:
uri: "../../../../third_party/dart/sdk/lib/mirrors/mirrors.dart"
patches:
- "../../../../third_party/dart/runtime/lib/mirrors_patch.dart"
- "../../../../third_party/dart/runtime/lib/mirrors_impl.dart"
- "../../../../third_party/dart/runtime/lib/mirror_reference.dart"
nativewrappers:
uri: "../../../../third_party/dart/sdk/lib/html/dartium/nativewrappers.dart"
profiler:
uri: "../../../../third_party/dart/sdk/lib/profiler/profiler.dart"
typed_data:
uri: "../../../../third_party/dart/sdk/lib/typed_data/typed_data.dart"
patches: "../../../../third_party/dart/runtime/lib/typed_data_patch.dart"
fuchsia.builtin:
uri: "../../../../topaz/runtime/dart_runner/embedder/builtin.dart"
zircon:
uri: "../../../../topaz/public/dart-pkg/zircon/lib/zircon.dart"
fuchsia:
uri: "../../../../topaz/public/dart-pkg/fuchsia/lib/fuchsia.dart"
ui:
uri: "../../../../third_party/flutter/lib/ui/ui.dart"
mozart.internal:
uri: "../../../../topaz/public/lib/ui/flutter/sdk_ext/mozart.dart"
_vmservice:
uri: "../../../../third_party/dart/sdk/lib/vmservice/vmservice.dart"
vmservice_io:
uri: "../../../../third_party/dart/runtime/bin/vmservice/vmservice_io.dart"

View File

@@ -0,0 +1,15 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_LOGGING_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_LOGGING_H_
namespace flutter_runner {
// Use to mark logs published via the syslog API.
#define LOG_TAG "flutter-runner"
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_LOGGING_H_

View File

@@ -0,0 +1,36 @@
// Copyright 2013 The Flutter 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 "loop.h"
#include <lib/async-loop/loop.h>
#include "task_observers.h"
namespace flutter_runner {
namespace {
static void LoopEpilogue(async_loop_t*, void*) {
ExecuteAfterTaskObservers();
}
constexpr async_loop_config_t kAttachedLoopConfig = {
.make_default_for_current_thread = true,
.epilogue = &LoopEpilogue,
};
constexpr async_loop_config_t kDetachedLoopConfig = {
.make_default_for_current_thread = false,
.epilogue = &LoopEpilogue,
};
} // namespace
async::Loop* MakeObservableLoop(bool attachToThread) {
return new async::Loop(
&(attachToThread ? kAttachedLoopConfig : kDetachedLoopConfig));
}
} // namespace flutter_runner

View File

@@ -0,0 +1,17 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_LOOP_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_LOOP_H_
#include <lib/async-loop/cpp/loop.h>
namespace flutter_runner {
// Creates a loop which allows task observers to be attached to it.
async::Loop* MakeObservableLoop(bool attachToThread);
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_LOOP_H_

View File

@@ -0,0 +1,44 @@
// Copyright 2013 The Flutter 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 <lib/async-loop/cpp/loop.h>
#if !defined(FUCHSIA_SDK)
#include <trace-provider/provider.h>
#include <trace/event.h>
#endif
#include <cstdlib>
#include "loop.h"
#include "runner.h"
#include "runtime/dart/utils/tempfs.h"
int main(int argc, char const* argv[]) {
std::unique_ptr<async::Loop> loop(flutter_runner::MakeObservableLoop(true));
#if !defined(FUCHSIA_SDK)
fbl::unique_ptr<trace::TraceProvider> provider;
{
TRACE_DURATION("flutter", "CreateTraceProvider");
bool already_started;
// Use CreateSynchronously to prevent loss of early events.
trace::TraceProvider::CreateSynchronously(
loop->dispatcher(), "flutter_runner", &provider, &already_started);
}
#endif
// Set up the process-wide /tmp memfs.
dart_utils::SetupRunnerTemp();
FML_DLOG(INFO) << "Flutter application services initialized.";
flutter_runner::Runner runner(loop.get());
loop->Run();
FML_DLOG(INFO) << "Flutter application services terminated.";
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,3 @@
{
"runner": "fuchsia-pkg://fuchsia.com/flutter_aot_product_runner#meta/flutter_aot_product_runner.cmx"
}

View File

@@ -0,0 +1,3 @@
{
"runner": "fuchsia-pkg://fuchsia.com/flutter_aot_runner#meta/flutter_aot_runner.cmx"
}

View File

@@ -0,0 +1,21 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"root-ssl-certificates",
"vulkan"
],
"services": [
"fuchsia.crash.Analyzer",
"fuchsia.device.manager.Administrator",
"fuchsia.fonts.Provider",
"fuchsia.net.SocketProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.timezone.Timezone",
"fuchsia.tracelink.Registry",
"fuchsia.vulkan.loader.Loader"
]
}
}

View File

@@ -0,0 +1,21 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"root-ssl-certificates",
"vulkan"
],
"services": [
"fuchsia.crash.Analyzer",
"fuchsia.device.manager.Administrator",
"fuchsia.fonts.Provider",
"fuchsia.net.SocketProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.timezone.Timezone",
"fuchsia.tracelink.Registry",
"fuchsia.vulkan.loader.Loader"
]
}
}

View File

@@ -0,0 +1,21 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"root-ssl-certificates",
"vulkan"
],
"services": [
"fuchsia.device.manager.Administrator",
"fuchsia.crash.Analyzer",
"fuchsia.fonts.Provider",
"fuchsia.net.SocketProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.timezone.Timezone",
"fuchsia.tracelink.Registry",
"fuchsia.vulkan.loader.Loader"
]
}
}

View File

@@ -0,0 +1,21 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"root-ssl-certificates",
"vulkan"
],
"services": [
"fuchsia.crash.Analyzer",
"fuchsia.device.manager.Administrator",
"fuchsia.fonts.Provider",
"fuchsia.net.SocketProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.timezone.Timezone",
"fuchsia.tracelink.Registry",
"fuchsia.vulkan.loader.Loader"
]
}
}

View File

@@ -0,0 +1,10 @@
{
"program": {
"binary": "test/flutter_runner_tests"
},
"sandbox": {
"services": [
"fuchsia.sys.Launcher"
]
}
}

View File

@@ -0,0 +1,3 @@
{
"runner": "fuchsia-pkg://fuchsia.com/flutter_jit_product_runner#meta/flutter_jit_product_runner.cmx"
}

View File

@@ -0,0 +1,3 @@
{
"runner": "fuchsia-pkg://fuchsia.com/flutter_jit_runner#meta/flutter_jit_runner.cmx"
}

View File

@@ -0,0 +1,743 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define RAPIDJSON_HAS_STDSTRING 1
#include "platform_view.h"
#include <sstream>
#include "flutter/fml/logging.h"
#include "flutter/lib/ui/compositing/scene_host.h"
#include "flutter/lib/ui/window/pointer_data.h"
#include "logging.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "runtime/dart/utils/inlines.h"
#include "vsync_waiter.h"
namespace flutter_runner {
namespace {
inline fuchsia::ui::gfx::vec3 Add(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z};
}
inline fuchsia::ui::gfx::vec3 Subtract(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = a.x - b.x, .y = a.y - b.y, .z = a.z - b.z};
}
inline fuchsia::ui::gfx::BoundingBox InsetBy(
const fuchsia::ui::gfx::BoundingBox& box,
const fuchsia::ui::gfx::vec3& inset_from_min,
const fuchsia::ui::gfx::vec3& inset_from_max) {
return {.min = Add(box.min, inset_from_min),
.max = Subtract(box.max, inset_from_max)};
}
inline fuchsia::ui::gfx::BoundingBox ViewPropertiesLayoutBox(
const fuchsia::ui::gfx::ViewProperties& view_properties) {
return InsetBy(view_properties.bounding_box, view_properties.inset_from_min,
view_properties.inset_from_max);
}
inline fuchsia::ui::gfx::vec3 Max(const fuchsia::ui::gfx::vec3& v,
float min_val) {
return {.x = std::max(v.x, min_val),
.y = std::max(v.y, min_val),
.z = std::max(v.z, min_val)};
}
} // end namespace
static constexpr char kFlutterPlatformChannel[] = "flutter/platform";
static constexpr char kTextInputChannel[] = "flutter/textinput";
static constexpr char kKeyEventChannel[] = "flutter/keyevent";
static constexpr char kAccessibilityChannel[] = "flutter/accessibility";
// FL(77): Terminate engine if Fuchsia system FIDL connections have error.
template <class T>
void SetInterfaceErrorHandler(fidl::InterfacePtr<T>& interface,
std::string name) {
interface.set_error_handler([name](zx_status_t status) {
FML_LOG(ERROR) << "Interface error on: " << name;
});
}
template <class T>
void SetInterfaceErrorHandler(fidl::Binding<T>& binding, std::string name) {
binding.set_error_handler([name](zx_status_t status) {
FML_LOG(ERROR) << "Interface error on: " << name;
});
}
PlatformView::PlatformView(
PlatformView::Delegate& delegate,
std::string debug_label,
flutter::TaskRunners task_runners,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider>
parent_environment_service_provider_handle,
fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>
session_listener_request,
fit::closure session_listener_error_callback,
OnMetricsUpdate session_metrics_did_change_callback,
OnSizeChangeHint session_size_change_hint_callback,
fidl::InterfaceHandle<fuchsia::modular::ContextWriter>
accessibility_context_writer,
zx_handle_t vsync_event_handle)
: flutter::PlatformView(delegate, std::move(task_runners)),
debug_label_(std::move(debug_label)),
session_listener_binding_(this, std::move(session_listener_request)),
session_listener_error_callback_(
std::move(session_listener_error_callback)),
metrics_changed_callback_(std::move(session_metrics_did_change_callback)),
size_change_hint_callback_(std::move(session_size_change_hint_callback)),
ime_client_(this),
context_writer_bridge_(std::move(accessibility_context_writer)),
surface_(std::make_unique<Surface>(debug_label_)),
vsync_event_handle_(vsync_event_handle) {
// Register all error handlers.
SetInterfaceErrorHandler(session_listener_binding_, "SessionListener");
SetInterfaceErrorHandler(ime_, "Input Method Editor");
SetInterfaceErrorHandler(text_sync_service_, "Text Sync Service");
SetInterfaceErrorHandler(clipboard_, "Clipboard");
SetInterfaceErrorHandler(parent_environment_service_provider_,
"Parent Environment Service Provider");
// Access the clipboard.
parent_environment_service_provider_ =
parent_environment_service_provider_handle.Bind();
parent_environment_service_provider_.get()->ConnectToService(
fuchsia::modular::Clipboard::Name_,
clipboard_.NewRequest().TakeChannel());
parent_environment_service_provider_.get()->ConnectToService(
fuchsia::ui::input::ImeService::Name_,
text_sync_service_.NewRequest().TakeChannel());
// Finally! Register the native platform message handlers.
RegisterPlatformMessageHandlers();
// TODO(SCN-975): Re-enable. Likely that Engine should clone the ViewToken
// and pass the clone in here.
// view_->GetToken(std::bind(&PlatformView::ConnectSemanticsProvider, this,
// std::placeholders::_1));
}
PlatformView::~PlatformView() = default;
void PlatformView::RegisterPlatformMessageHandlers() {
platform_message_handlers_[kFlutterPlatformChannel] =
std::bind(&PlatformView::HandleFlutterPlatformChannelPlatformMessage,
this, std::placeholders::_1);
platform_message_handlers_[kTextInputChannel] =
std::bind(&PlatformView::HandleFlutterTextInputChannelPlatformMessage,
this, std::placeholders::_1);
platform_message_handlers_[kAccessibilityChannel] =
std::bind(&PlatformView::HandleAccessibilityChannelPlatformMessage, this,
std::placeholders::_1);
}
void PlatformView::OnPropertiesChanged(
const fuchsia::ui::gfx::ViewProperties& view_properties) {
fuchsia::ui::gfx::BoundingBox layout_box =
ViewPropertiesLayoutBox(view_properties);
fuchsia::ui::gfx::vec3 logical_size =
Max(Subtract(layout_box.max, layout_box.min), 0.f);
metrics_.size.width = logical_size.x;
metrics_.size.height = logical_size.y;
metrics_.size.depth = logical_size.z;
metrics_.padding.left = view_properties.inset_from_min.x;
metrics_.padding.top = view_properties.inset_from_min.y;
metrics_.padding.front = view_properties.inset_from_min.z;
metrics_.padding.right = view_properties.inset_from_max.x;
metrics_.padding.bottom = view_properties.inset_from_max.y;
metrics_.padding.back = view_properties.inset_from_max.z;
FlushViewportMetrics();
}
// TODO(SCN-975): Re-enable.
// void PlatformView::ConnectSemanticsProvider(
// fuchsia::ui::viewsv1token::ViewToken token) {
// semantics_bridge_.SetupEnvironment(
// token.value, parent_environment_service_provider_.get());
// }
void PlatformView::UpdateViewportMetrics(
const fuchsia::ui::gfx::Metrics& metrics) {
metrics_.scale = metrics.scale_x;
metrics_.scale_z = metrics.scale_z;
FlushViewportMetrics();
}
void PlatformView::FlushViewportMetrics() {
const auto scale = metrics_.scale;
const auto scale_z = metrics_.scale_z;
SetViewportMetrics({
scale, // device_pixel_ratio
metrics_.size.width * scale, // physical_width
metrics_.size.height * scale, // physical_height
metrics_.size.depth * scale_z, // physical_depth
metrics_.padding.top * scale, // physical_padding_top
metrics_.padding.right * scale, // physical_padding_right
metrics_.padding.bottom * scale, // physical_padding_bottom
metrics_.padding.left * scale, // physical_padding_left
metrics_.view_inset.front * scale_z, // physical_view_inset_front
metrics_.view_inset.back * scale_z, // physical_view_inset_back
metrics_.view_inset.top * scale, // physical_view_inset_top
metrics_.view_inset.right * scale, // physical_view_inset_right
metrics_.view_inset.bottom * scale, // physical_view_inset_bottom
metrics_.view_inset.left * scale // physical_view_inset_left
});
}
// |fuchsia::ui::input::InputMethodEditorClient|
void PlatformView::DidUpdateState(
fuchsia::ui::input::TextInputState state,
std::unique_ptr<fuchsia::ui::input::InputEvent> input_event) {
rapidjson::Document document;
auto& allocator = document.GetAllocator();
rapidjson::Value encoded_state(rapidjson::kObjectType);
encoded_state.AddMember("text", state.text, allocator);
encoded_state.AddMember("selectionBase", state.selection.base, allocator);
encoded_state.AddMember("selectionExtent", state.selection.extent, allocator);
switch (state.selection.affinity) {
case fuchsia::ui::input::TextAffinity::UPSTREAM:
encoded_state.AddMember("selectionAffinity",
rapidjson::Value("TextAffinity.upstream"),
allocator);
break;
case fuchsia::ui::input::TextAffinity::DOWNSTREAM:
encoded_state.AddMember("selectionAffinity",
rapidjson::Value("TextAffinity.downstream"),
allocator);
break;
}
encoded_state.AddMember("selectionIsDirectional", true, allocator);
encoded_state.AddMember("composingBase", state.composing.start, allocator);
encoded_state.AddMember("composingExtent", state.composing.end, allocator);
rapidjson::Value args(rapidjson::kArrayType);
args.PushBack(current_text_input_client_, allocator);
args.PushBack(encoded_state, allocator);
document.SetObject();
document.AddMember("method",
rapidjson::Value("TextInputClient.updateEditingState"),
allocator);
document.AddMember("args", args, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString());
DispatchPlatformMessage(fml::MakeRefCounted<flutter::PlatformMessage>(
kTextInputChannel, // channel
std::vector<uint8_t>(data, data + buffer.GetSize()), // message
nullptr) // response
);
last_text_state_ =
std::make_unique<fuchsia::ui::input::TextInputState>(state);
// Handle keyboard input events for HID keys only.
// TODO(SCN-1189): Are we done here?
if (input_event && input_event->keyboard().hid_usage != 0) {
OnHandleKeyboardEvent(input_event->keyboard());
}
}
// |fuchsia::ui::input::InputMethodEditorClient|
void PlatformView::OnAction(fuchsia::ui::input::InputMethodAction action) {
rapidjson::Document document;
auto& allocator = document.GetAllocator();
rapidjson::Value args(rapidjson::kArrayType);
args.PushBack(current_text_input_client_, allocator);
// Done is currently the only text input action defined by Flutter.
args.PushBack("TextInputAction.done", allocator);
document.SetObject();
document.AddMember(
"method", rapidjson::Value("TextInputClient.performAction"), allocator);
document.AddMember("args", args, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString());
DispatchPlatformMessage(fml::MakeRefCounted<flutter::PlatformMessage>(
kTextInputChannel, // channel
std::vector<uint8_t>(data, data + buffer.GetSize()), // message
nullptr) // response
);
}
void PlatformView::OnScenicError(std::string error) {
FML_LOG(ERROR) << "Session error: " << error;
session_listener_error_callback_();
}
void PlatformView::OnScenicEvent(
std::vector<fuchsia::ui::scenic::Event> events) {
TRACE_EVENT0("flutter", "PlatformView::OnScenicEvent");
for (const auto& event : events) {
switch (event.Which()) {
case fuchsia::ui::scenic::Event::Tag::kGfx:
switch (event.gfx().Which()) {
case fuchsia::ui::gfx::Event::Tag::kMetrics: {
if (event.gfx().metrics().metrics != scenic_metrics_) {
scenic_metrics_ = std::move(event.gfx().metrics().metrics);
metrics_changed_callback_(scenic_metrics_);
UpdateViewportMetrics(scenic_metrics_);
}
break;
}
case fuchsia::ui::gfx::Event::Tag::kSizeChangeHint: {
size_change_hint_callback_(
event.gfx().size_change_hint().width_change_factor,
event.gfx().size_change_hint().height_change_factor);
break;
}
case fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged: {
OnPropertiesChanged(
std::move(event.gfx().view_properties_changed().properties));
break;
}
case fuchsia::ui::gfx::Event::Tag::kViewConnected:
OnChildViewConnected(event.gfx().view_connected().view_holder_id);
break;
case fuchsia::ui::gfx::Event::Tag::kViewDisconnected:
OnChildViewDisconnected(
event.gfx().view_disconnected().view_holder_id);
break;
case fuchsia::ui::gfx::Event::Tag::kViewStateChanged:
OnChildViewStateChanged(
event.gfx().view_state_changed().view_holder_id,
event.gfx().view_state_changed().state.is_rendering);
break;
case fuchsia::ui::gfx::Event::Tag::Invalid:
FML_DCHECK(false) << "Flutter PlatformView::OnScenicEvent: Got "
"an invalid GFX event.";
break;
default:
// We don't care about some event types, so not handling them is OK.
break;
}
break;
case fuchsia::ui::scenic::Event::Tag::kInput:
switch (event.input().Which()) {
case fuchsia::ui::input::InputEvent::Tag::kFocus: {
OnHandleFocusEvent(event.input().focus());
break;
}
case fuchsia::ui::input::InputEvent::Tag::kPointer: {
OnHandlePointerEvent(event.input().pointer());
break;
}
case fuchsia::ui::input::InputEvent::Tag::kKeyboard: {
OnHandleKeyboardEvent(event.input().keyboard());
break;
}
case fuchsia::ui::input::InputEvent::Tag::Invalid: {
FML_DCHECK(false)
<< "Flutter PlatformView::OnScenicEvent: Got an invalid INPUT "
"event.";
}
}
break;
default: {
break;
}
}
}
}
void PlatformView::OnChildViewConnected(scenic::ResourceId view_holder_id) {
task_runners_.GetUITaskRunner()->PostTask([view_holder_id]() {
flutter::SceneHost::OnViewConnected(view_holder_id);
});
}
void PlatformView::OnChildViewDisconnected(scenic::ResourceId view_holder_id) {
task_runners_.GetUITaskRunner()->PostTask([view_holder_id]() {
flutter::SceneHost::OnViewDisconnected(view_holder_id);
});
}
void PlatformView::OnChildViewStateChanged(scenic::ResourceId view_holder_id,
bool state) {
task_runners_.GetUITaskRunner()->PostTask([view_holder_id, state]() {
flutter::SceneHost::OnViewStateChanged(view_holder_id, state);
});
}
static flutter::PointerData::Change GetChangeFromPointerEventPhase(
fuchsia::ui::input::PointerEventPhase phase) {
switch (phase) {
case fuchsia::ui::input::PointerEventPhase::ADD:
return flutter::PointerData::Change::kAdd;
case fuchsia::ui::input::PointerEventPhase::HOVER:
return flutter::PointerData::Change::kHover;
case fuchsia::ui::input::PointerEventPhase::DOWN:
return flutter::PointerData::Change::kDown;
case fuchsia::ui::input::PointerEventPhase::MOVE:
return flutter::PointerData::Change::kMove;
case fuchsia::ui::input::PointerEventPhase::UP:
return flutter::PointerData::Change::kUp;
case fuchsia::ui::input::PointerEventPhase::REMOVE:
return flutter::PointerData::Change::kRemove;
case fuchsia::ui::input::PointerEventPhase::CANCEL:
return flutter::PointerData::Change::kCancel;
default:
return flutter::PointerData::Change::kCancel;
}
}
static flutter::PointerData::DeviceKind GetKindFromPointerType(
fuchsia::ui::input::PointerEventType type) {
switch (type) {
case fuchsia::ui::input::PointerEventType::TOUCH:
return flutter::PointerData::DeviceKind::kTouch;
case fuchsia::ui::input::PointerEventType::MOUSE:
return flutter::PointerData::DeviceKind::kMouse;
default:
return flutter::PointerData::DeviceKind::kTouch;
}
}
#if !defined(FUCHSIA_SDK)
// TODO(SCN-1278): Remove this.
// Turns two floats (high bits, low bits) into a 64-bit uint.
static trace_flow_id_t PointerTraceHACK(float fa, float fb) {
uint32_t ia, ib;
memcpy(&ia, &fa, sizeof(uint32_t));
memcpy(&ib, &fb, sizeof(uint32_t));
return (((uint64_t)ia) << 32) | ib;
}
#endif // !defined(FUCHSIA_SDK)
bool PlatformView::OnHandlePointerEvent(
const fuchsia::ui::input::PointerEvent& pointer) {
TRACE_EVENT0("flutter", "PlatformView::OnHandlePointerEvent");
#if !defined(FUCHSIA_SDK)
// TODO(SCN-1278): Use proper trace_id for tracing flow.
trace_flow_id_t trace_id =
PointerTraceHACK(pointer.radius_major, pointer.radius_minor);
TRACE_FLOW_END("input", "dispatch_event_to_client", trace_id);
#endif // !defined(FUCHSIA_SDK)
flutter::PointerData pointer_data;
pointer_data.Clear();
pointer_data.time_stamp = pointer.event_time / 1000;
pointer_data.change = GetChangeFromPointerEventPhase(pointer.phase);
pointer_data.kind = GetKindFromPointerType(pointer.type);
pointer_data.device = pointer.pointer_id;
pointer_data.physical_x = pointer.x * metrics_.scale;
pointer_data.physical_y = pointer.y * metrics_.scale;
// Buttons are single bit values starting with kMousePrimaryButton = 1.
pointer_data.buttons = static_cast<uint64_t>(pointer.buttons);
switch (pointer_data.change) {
case flutter::PointerData::Change::kDown:
down_pointers_.insert(pointer_data.device);
break;
case flutter::PointerData::Change::kCancel:
case flutter::PointerData::Change::kUp:
down_pointers_.erase(pointer_data.device);
break;
case flutter::PointerData::Change::kMove:
if (down_pointers_.count(pointer_data.device) == 0) {
pointer_data.change = flutter::PointerData::Change::kHover;
}
break;
case flutter::PointerData::Change::kAdd:
if (down_pointers_.count(pointer_data.device) != 0) {
FML_DLOG(ERROR) << "Received add event for down pointer.";
}
break;
case flutter::PointerData::Change::kRemove:
if (down_pointers_.count(pointer_data.device) != 0) {
FML_DLOG(ERROR) << "Received remove event for down pointer.";
}
break;
case flutter::PointerData::Change::kHover:
if (down_pointers_.count(pointer_data.device) != 0) {
FML_DLOG(ERROR) << "Received hover event for down pointer.";
}
break;
}
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(0, pointer_data);
DispatchPointerDataPacket(std::move(packet));
return true;
}
bool PlatformView::OnHandleKeyboardEvent(
const fuchsia::ui::input::KeyboardEvent& keyboard) {
const char* type = nullptr;
if (keyboard.phase == fuchsia::ui::input::KeyboardEventPhase::PRESSED) {
type = "keydown";
} else if (keyboard.phase == fuchsia::ui::input::KeyboardEventPhase::REPEAT) {
type = "keydown"; // TODO change this to keyrepeat
} else if (keyboard.phase ==
fuchsia::ui::input::KeyboardEventPhase::RELEASED) {
type = "keyup";
}
if (type == nullptr) {
FML_DLOG(ERROR) << "Unknown key event phase.";
return false;
}
rapidjson::Document document;
auto& allocator = document.GetAllocator();
document.SetObject();
document.AddMember("type", rapidjson::Value(type, strlen(type)), allocator);
document.AddMember("keymap", rapidjson::Value("fuchsia"), allocator);
document.AddMember("hidUsage", keyboard.hid_usage, allocator);
document.AddMember("codePoint", keyboard.code_point, allocator);
document.AddMember("modifiers", keyboard.modifiers, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString());
DispatchPlatformMessage(fml::MakeRefCounted<flutter::PlatformMessage>(
kKeyEventChannel, // channel
std::vector<uint8_t>(data, data + buffer.GetSize()), // data
nullptr) // response
);
return true;
}
bool PlatformView::OnHandleFocusEvent(
const fuchsia::ui::input::FocusEvent& focus) {
// Ensure last_text_state_ is set to make sure Flutter actually wants an IME.
if (focus.focused && last_text_state_ != nullptr) {
ActivateIme();
return true;
} else if (!focus.focused) {
DeactivateIme();
return true;
}
return false;
}
void PlatformView::ActivateIme() {
DEBUG_CHECK(last_text_state_ != nullptr, LOG_TAG, "");
text_sync_service_->GetInputMethodEditor(
fuchsia::ui::input::KeyboardType::TEXT, // keyboard type
fuchsia::ui::input::InputMethodAction::DONE, // input method action
*last_text_state_, // initial state
ime_client_.NewBinding(), // client
ime_.NewRequest() // editor
);
}
void PlatformView::DeactivateIme() {
if (ime_) {
text_sync_service_->HideKeyboard();
ime_ = nullptr;
}
if (ime_client_.is_bound()) {
ime_client_.Unbind();
}
}
// |flutter::PlatformView|
std::unique_ptr<flutter::VsyncWaiter> PlatformView::CreateVSyncWaiter() {
return std::make_unique<flutter_runner::VsyncWaiter>(
debug_label_, vsync_event_handle_, task_runners_);
}
// |flutter::PlatformView|
std::unique_ptr<flutter::Surface> PlatformView::CreateRenderingSurface() {
// This platform does not repeatly lose and gain a surface connection. So the
// surface is setup once during platform view setup and and returned to the
// shell on the initial (and only) |NotifyCreated| call.
return std::move(surface_);
}
// |flutter::PlatformView|
void PlatformView::HandlePlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message) {
if (!message) {
return;
}
auto found = platform_message_handlers_.find(message->channel());
if (found == platform_message_handlers_.end()) {
FML_LOG(ERROR)
<< "Platform view received message on channel '" << message->channel()
<< "' with no registed handler. And empty response will be generated. "
"Please implement the native message handler.";
flutter::PlatformView::HandlePlatformMessage(std::move(message));
return;
}
found->second(std::move(message));
}
// |flutter::PlatformView|
void PlatformView::UpdateSemantics(
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) {
// TODO(MI4-1262): Figure out if the context_writer_bridge should be removed
// as it is unused.
// context_writer_bridge_.UpdateSemantics(update);
// TODO(MIT-1539): Uncomment/Reimplement following code, to add A11y support.
// semantics_bridge_.UpdateSemantics(update);
}
// Channel handler for kAccessibilityChannel
void PlatformView::HandleAccessibilityChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message) {
FML_DCHECK(message->channel() == kAccessibilityChannel);
}
// Channel handler for kFlutterPlatformChannel
void PlatformView::HandleFlutterPlatformChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message) {
FML_DCHECK(message->channel() == kFlutterPlatformChannel);
const auto& data = message->data();
rapidjson::Document document;
document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
if (document.HasParseError() || !document.IsObject()) {
return;
}
auto root = document.GetObject();
auto method = root.FindMember("method");
if (method == root.MemberEnd() || !method->value.IsString()) {
return;
}
fml::RefPtr<flutter::PlatformMessageResponse> response = message->response();
if (method->value == "Clipboard.setData") {
auto text = root["args"]["text"].GetString();
clipboard_->Push(text);
response->CompleteEmpty();
} else if (method->value == "Clipboard.getData") {
clipboard_->Peek([response](fidl::StringPtr text) {
rapidjson::StringBuffer json_buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(json_buffer);
writer.StartArray();
writer.StartObject();
writer.Key("text");
writer.String(text.get());
writer.EndObject();
writer.EndArray();
std::string result = json_buffer.GetString();
response->Complete(std::make_unique<fml::DataMapping>(
std::vector<uint8_t>{result.begin(), result.end()}));
});
} else {
response->CompleteEmpty();
}
}
// Channel handler for kTextInputChannel
void PlatformView::HandleFlutterTextInputChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message) {
FML_DCHECK(message->channel() == kTextInputChannel);
const auto& data = message->data();
rapidjson::Document document;
document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
if (document.HasParseError() || !document.IsObject()) {
return;
}
auto root = document.GetObject();
auto method = root.FindMember("method");
if (method == root.MemberEnd() || !method->value.IsString()) {
return;
}
if (method->value == "TextInput.show") {
if (ime_) {
text_sync_service_->ShowKeyboard();
}
} else if (method->value == "TextInput.hide") {
if (ime_) {
text_sync_service_->HideKeyboard();
}
} else if (method->value == "TextInput.setClient") {
current_text_input_client_ = 0;
DeactivateIme();
auto args = root.FindMember("args");
if (args == root.MemberEnd() || !args->value.IsArray() ||
args->value.Size() != 2)
return;
const auto& configuration = args->value[1];
if (!configuration.IsObject()) {
return;
}
// TODO(abarth): Read the keyboard type from the configuration.
current_text_input_client_ = args->value[0].GetInt();
auto initial_text_input_state = fuchsia::ui::input::TextInputState{};
initial_text_input_state.text = "";
last_text_state_ = std::make_unique<fuchsia::ui::input::TextInputState>(
initial_text_input_state);
ActivateIme();
} else if (method->value == "TextInput.setEditingState") {
if (ime_) {
auto args_it = root.FindMember("args");
if (args_it == root.MemberEnd() || !args_it->value.IsObject()) {
return;
}
const auto& args = args_it->value;
fuchsia::ui::input::TextInputState state;
state.text = "";
// TODO(abarth): Deserialize state.
auto text = args.FindMember("text");
if (text != args.MemberEnd() && text->value.IsString())
state.text = text->value.GetString();
auto selection_base = args.FindMember("selectionBase");
if (selection_base != args.MemberEnd() && selection_base->value.IsInt())
state.selection.base = selection_base->value.GetInt();
auto selection_extent = args.FindMember("selectionExtent");
if (selection_extent != args.MemberEnd() &&
selection_extent->value.IsInt())
state.selection.extent = selection_extent->value.GetInt();
auto selection_affinity = args.FindMember("selectionAffinity");
if (selection_affinity != args.MemberEnd() &&
selection_affinity->value.IsString() &&
selection_affinity->value == "TextAffinity.upstream")
state.selection.affinity = fuchsia::ui::input::TextAffinity::UPSTREAM;
else
state.selection.affinity = fuchsia::ui::input::TextAffinity::DOWNSTREAM;
// We ignore selectionIsDirectional because that concept doesn't exist on
// Fuchsia.
auto composing_base = args.FindMember("composingBase");
if (composing_base != args.MemberEnd() && composing_base->value.IsInt())
state.composing.start = composing_base->value.GetInt();
auto composing_extent = args.FindMember("composingExtent");
if (composing_extent != args.MemberEnd() &&
composing_extent->value.IsInt())
state.composing.end = composing_extent->value.GetInt();
ime_->SetState(std::move(state));
}
} else if (method->value == "TextInput.clearClient") {
current_text_input_client_ = 0;
last_text_state_ = nullptr;
DeactivateIme();
} else {
FML_DLOG(ERROR) << "Unknown " << message->channel() << " method "
<< method->value.GetString();
}
}
} // namespace flutter_runner

View File

@@ -0,0 +1,174 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_PLATFORM_VIEW_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_PLATFORM_VIEW_H_
#include <map>
#include <set>
#include <fuchsia/modular/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <lib/fit/function.h>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/shell/common/platform_view.h"
#include "lib/fidl/cpp/binding.h"
#include "lib/ui/scenic/cpp/id.h"
#include "context_writer_bridge.h"
#include "surface.h"
namespace flutter_runner {
using OnMetricsUpdate = fit::function<void(const fuchsia::ui::gfx::Metrics&)>;
using OnSizeChangeHint =
fit::function<void(float width_change_factor, float height_change_factor)>;
// The per engine component residing on the platform thread is responsible for
// all platform specific integrations.
//
// The PlatformView implements SessionListener and gets Session events but it
// does *not* actually own the Session itself; that is owned by the Compositor
// thread.
class PlatformView final : public flutter::PlatformView,
private fuchsia::ui::scenic::SessionListener,
public fuchsia::ui::input::InputMethodEditorClient {
public:
PlatformView(PlatformView::Delegate& delegate,
std::string debug_label,
flutter::TaskRunners task_runners,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider>
parent_environment_service_provider,
fidl::InterfaceRequest<fuchsia::ui::scenic::SessionListener>
session_listener_request,
fit::closure on_session_listener_error_callback,
OnMetricsUpdate session_metrics_did_change_callback,
OnSizeChangeHint session_size_change_hint_callback,
fidl::InterfaceHandle<fuchsia::modular::ContextWriter>
accessibility_context_writer,
zx_handle_t vsync_event_handle);
PlatformView(PlatformView::Delegate& delegate,
std::string debug_label,
flutter::TaskRunners task_runners,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider>
parent_environment_service_provider,
fidl::InterfaceHandle<fuchsia::modular::ContextWriter>
accessibility_context_writer,
zx_handle_t vsync_event_handle);
~PlatformView();
void UpdateViewportMetrics(const fuchsia::ui::gfx::Metrics& metrics);
private:
const std::string debug_label_;
fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_binding_;
fit::closure session_listener_error_callback_;
OnMetricsUpdate metrics_changed_callback_;
OnSizeChangeHint size_change_hint_callback_;
int current_text_input_client_ = 0;
fidl::Binding<fuchsia::ui::input::InputMethodEditorClient> ime_client_;
fuchsia::ui::input::InputMethodEditorPtr ime_;
fuchsia::ui::input::ImeServicePtr text_sync_service_;
fuchsia::sys::ServiceProviderPtr parent_environment_service_provider_;
fuchsia::modular::ClipboardPtr clipboard_;
ContextWriterBridge context_writer_bridge_;
std::unique_ptr<Surface> surface_;
flutter::LogicalMetrics metrics_;
fuchsia::ui::gfx::Metrics scenic_metrics_;
// last_text_state_ is the last state of the text input as reported by the IME
// or initialized by Flutter. We set it to null if Flutter doesn't want any
// input, since then there is no text input state at all.
std::unique_ptr<fuchsia::ui::input::TextInputState> last_text_state_;
std::set<int> down_pointers_;
std::map<
std::string /* channel */,
fit::function<void(
fml::RefPtr<flutter::PlatformMessage> /* message */)> /* handler */>
platform_message_handlers_;
zx_handle_t vsync_event_handle_ = 0;
void RegisterPlatformMessageHandlers();
void FlushViewportMetrics();
// Called when the view's properties have changed.
void OnPropertiesChanged(
const fuchsia::ui::gfx::ViewProperties& view_properties);
// |fuchsia::ui::input::InputMethodEditorClient|
void DidUpdateState(
fuchsia::ui::input::TextInputState state,
std::unique_ptr<fuchsia::ui::input::InputEvent> event) override;
// |fuchsia::ui::input::InputMethodEditorClient|
void OnAction(fuchsia::ui::input::InputMethodAction action) override;
// |fuchsia::ui::scenic::SessionListener|
void OnScenicError(std::string error) override;
void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override;
void OnChildViewConnected(scenic::ResourceId view_holder_id);
void OnChildViewDisconnected(scenic::ResourceId view_holder_id);
void OnChildViewStateChanged(scenic::ResourceId view_holder_id, bool state);
bool OnHandlePointerEvent(const fuchsia::ui::input::PointerEvent& pointer);
bool OnHandleKeyboardEvent(const fuchsia::ui::input::KeyboardEvent& keyboard);
bool OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus);
// Gets a new input method editor from the input connection. Run when both
// Scenic has focus and Flutter has requested input with setClient.
void ActivateIme();
// Detaches the input method editor connection, ending the edit session and
// closing the onscreen keyboard. Call when input is no longer desired, either
// because Scenic says we lost focus or when Flutter no longer has a text
// field focused.
void DeactivateIme();
// |flutter::PlatformView|
std::unique_ptr<flutter::VsyncWaiter> CreateVSyncWaiter() override;
// |flutter::PlatformView|
std::unique_ptr<flutter::Surface> CreateRenderingSurface() override;
// |flutter::PlatformView|
void HandlePlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message) override;
// |flutter::PlatformView|
void UpdateSemantics(
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// Channel handler for kAccessibilityChannel. This is currently not
// being used, but it is necessary to handle accessibility messages
// that are sent by Flutter when semantics is enabled.
void HandleAccessibilityChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message);
// Channel handler for kFlutterPlatformChannel
void HandleFlutterPlatformChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message);
// Channel handler for kTextInputChannel
void HandleFlutterTextInputChannelPlatformMessage(
fml::RefPtr<flutter::PlatformMessage> message);
FML_DISALLOW_COPY_AND_ASSIGN(PlatformView);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_PLATFORM_VIEW_H_

View File

@@ -0,0 +1,15 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
declare_args() {
prebuilt_framework_path = ""
prebuilt_framework_name = ""
framework_packages = [
"collection",
"flutter",
"meta",
"typed_data",
"vector_math",
]
}

View File

@@ -0,0 +1,236 @@
// Copyright 2013 The Flutter 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 "runner.h"
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/async/cpp/task.h>
#include <zircon/status.h>
#include <zircon/types.h>
#if !defined(FUCHSIA_SDK)
#include <trace-engine/instrumentation.h>
#endif // !defined(FUCHSIA_SDK)
#include <sstream>
#include <utility>
#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/text/font_collection.h"
#include "flutter/runtime/dart_vm.h"
#include "fuchsia_font_manager.h"
#include "runtime/dart/utils/vmo.h"
#include "runtime/dart/utils/vmservice_object.h"
#include "third_party/icu/source/common/unicode/udata.h"
#include "third_party/skia/include/core/SkGraphics.h"
namespace flutter_runner {
namespace {
static constexpr char kIcuDataPath[] = "/pkg/data/icudtl.dat";
// Map the memory into the process and return a pointer to the memory.
uintptr_t GetICUData(const fuchsia::mem::Buffer& icu_data) {
uint64_t data_size = icu_data.size;
if (data_size > std::numeric_limits<size_t>::max())
return 0u;
uintptr_t data = 0u;
zx_status_t status = zx::vmar::root_self()->map(
0, icu_data.vmo, 0, static_cast<size_t>(data_size), ZX_VM_PERM_READ,
&data);
if (status == ZX_OK) {
return data;
}
return 0u;
}
// Return value indicates if initialization was successful.
bool InitializeICU() {
const char* data_path = kIcuDataPath;
fuchsia::mem::Buffer icu_data;
if (!dart_utils::VmoFromFilename(data_path, &icu_data)) {
return false;
}
uintptr_t data = GetICUData(icu_data);
if (!data) {
return false;
}
// Pass the data to ICU.
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<const char*>(data), &err);
return err == U_ZERO_ERROR;
}
} // namespace
static void SetProcessName() {
std::stringstream stream;
#if defined(DART_PRODUCT)
stream << "io.flutter.product_runner.";
#else
stream << "io.flutter.runner.";
#endif
if (flutter::DartVM::IsRunningPrecompiledCode()) {
stream << "aot";
} else {
stream << "jit";
}
const auto name = stream.str();
zx::process::self()->set_property(ZX_PROP_NAME, name.c_str(), name.size());
}
static void SetThreadName(const std::string& thread_name) {
zx::thread::self()->set_property(ZX_PROP_NAME, thread_name.c_str(),
thread_name.size());
}
Runner::Runner(async::Loop* loop)
: loop_(loop), runner_context_(RunnerContext::CreateFromStartupInfo()) {
#if !defined(DART_PRODUCT)
// The VM service isolate uses the process-wide namespace. It writes the
// vm service protocol port under /tmp. The VMServiceObject exposes that
// port number to The Hub.
runner_context_->debug_dir()->AddEntry(
dart_utils::VMServiceObject::kPortDirName,
std::make_unique<dart_utils::VMServiceObject>());
#if !defined(FUCHSIA_SDK)
SetupTraceObserver();
#endif // !defined(FUCHSIA_SDK)
#endif // !defined(DART_PRODUCT)
SkGraphics::Init();
SetupICU();
SetProcessName();
SetThreadName("io.flutter.runner.main");
runner_context_->AddPublicService<fuchsia::sys::Runner>(
std::bind(&Runner::RegisterApplication, this, std::placeholders::_1));
}
Runner::~Runner() {
runner_context_->RemovePublicService<fuchsia::sys::Runner>();
#if !defined(DART_PRODUCT)
#if !defined(FUCHSIA_SDK)
trace_observer_->Stop();
#endif // !defined(FUCHSIA_SDK)
#endif // !defined(DART_PRODUCT)
}
void Runner::RegisterApplication(
fidl::InterfaceRequest<fuchsia::sys::Runner> request) {
active_applications_bindings_.AddBinding(this, std::move(request));
}
void Runner::StartComponent(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller) {
TRACE_EVENT0("flutter", "StartComponent");
// Notes on application termination: Application typically terminate on the
// thread on which they were created. This usually means the thread was
// specifically created to host the application. But we want to ensure that
// access to the active applications collection is made on the same thread. So
// we capture the runner in the termination callback. There is no risk of
// there being multiple application runner instance in the process at the same
// time. So it is safe to use the raw pointer.
Application::TerminationCallback termination_callback =
[task_runner = loop_->dispatcher(), //
application_runner = this //
](const Application* application) {
async::PostTask(task_runner, [application_runner, application]() {
application_runner->OnApplicationTerminate(application);
});
};
auto thread_application_pair = Application::Create(
std::move(termination_callback), // termination callback
std::move(package), // application pacakge
std::move(startup_info), // startup info
runner_context_->svc(), // runner incoming services
std::move(controller) // controller request
);
auto key = thread_application_pair.second.get();
active_applications_[key] = std::move(thread_application_pair);
}
void Runner::OnApplicationTerminate(const Application* application) {
auto app = active_applications_.find(application);
if (app == active_applications_.end()) {
FML_LOG(INFO)
<< "The remote end of the application runner tried to terminate an "
"application that has already been terminated, possibly because we "
"initiated the termination";
return;
}
auto& active_application = app->second;
// Grab the items out of the entry because we will have to rethread the
// destruction.
auto application_to_destroy = std::move(active_application.application);
auto application_thread = std::move(active_application.thread);
// Delegate the entry.
active_applications_.erase(application);
// Post the task to destroy the application and quit its message loop.
async::PostTask(
application_thread->dispatcher(),
fml::MakeCopyable([instance = std::move(application_to_destroy),
thread = application_thread.get()]() mutable {
instance.reset();
thread->Quit();
}));
// This works because just posted the quit task on the hosted thread.
application_thread->Join();
}
void Runner::SetupICU() {
if (!InitializeICU()) {
FML_LOG(ERROR) << "Could not initialize ICU data.";
}
}
#if !defined(DART_PRODUCT)
#if !defined(FUCHSIA_SDK)
void Runner::SetupTraceObserver() {
trace_observer_ = std::make_unique<trace::TraceObserver>();
trace_observer_->Start(loop_->dispatcher(), [runner = this]() {
if (!trace_is_category_enabled("dart:profiler")) {
return;
}
if (trace_state() == TRACE_STARTED) {
runner->prolonged_context_ = trace_acquire_prolonged_context();
Dart_StartProfiling();
} else if (trace_state() == TRACE_STOPPING) {
for (auto& it : runner->active_applications_) {
fml::AutoResetWaitableEvent latch;
async::PostTask(it.second.thread->dispatcher(), [&]() {
it.second.application->WriteProfileToTrace();
latch.Signal();
});
latch.Wait();
}
Dart_StopProfiling();
trace_release_prolonged_context(runner->prolonged_context_);
}
});
}
#endif // !defined(FUCHSIA_SDK)
#endif // !defined(DART_PRODUCT)
} // namespace flutter_runner

View File

@@ -0,0 +1,90 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_RUNNER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNNER_H_
#include <memory>
#include <unordered_map>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/component_context.h>
#if !defined(FUCHSIA_SDK)
#include <trace-engine/instrumentation.h>
#include <trace/observer.h>
#endif // !defined(FUCHSIA_SDK)
#include "component.h"
#include "flutter/fml/macros.h"
#include "lib/fidl/cpp/binding_set.h"
#include "runner_context.h"
#include "runtime/dart/utils/vmservice_object.h"
#include "thread.h"
namespace flutter_runner {
// Publishes the |fuchsia::sys::Runner| service and runs applications on
// their own threads.
class Runner final : public fuchsia::sys::Runner {
public:
explicit Runner(async::Loop* loop);
~Runner();
private:
async::Loop* loop_;
struct ActiveApplication {
std::unique_ptr<Thread> thread;
std::unique_ptr<Application> application;
ActiveApplication(
std::pair<std::unique_ptr<Thread>, std::unique_ptr<Application>> pair)
: thread(std::move(pair.first)), application(std::move(pair.second)) {}
ActiveApplication() = default;
};
std::unique_ptr<RunnerContext> runner_context_;
fidl::BindingSet<fuchsia::sys::Runner> active_applications_bindings_;
std::unordered_map<const Application*, ActiveApplication>
active_applications_;
#if !defined(DART_PRODUCT)
// The connection between the Dart VM service and The Hub.
std::unique_ptr<dart_utils::VMServiceObject> vmservice_object_;
#if !defined(FUCHSIA_SDK)
std::unique_ptr<trace::TraceObserver> trace_observer_;
trace_prolonged_context_t* prolonged_context_;
#endif // !defined(FUCHSIA_SDK)
#endif // !defined(DART_PRODUCT)
// |fuchsia::sys::Runner|
void StartComponent(fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
controller) override;
void RegisterApplication(
fidl::InterfaceRequest<fuchsia::sys::Runner> request);
void UnregisterApplication(const Application* application);
void OnApplicationTerminate(const Application* application);
void SetupICU();
#if !defined(DART_PRODUCT)
void SetupTraceObserver();
#endif // !defined(DART_PRODUCT)
FML_DISALLOW_COPY_AND_ASSIGN(Runner);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNNER_H_

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter 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 "runner_context.h"
namespace flutter_runner {
RunnerContext::RunnerContext(std::shared_ptr<sys::ServiceDirectory> svc,
zx::channel directory_request)
: svc_(std::move(svc)),
root_dir_(std::make_shared<vfs::PseudoDir>()),
public_dir_(std::make_shared<vfs::PseudoDir>()),
debug_dir_(std::make_shared<vfs::PseudoDir>()),
ctrl_dir_(std::make_shared<vfs::PseudoDir>()) {
root_dir_->AddSharedEntry("public", public_dir_);
root_dir_->AddSharedEntry("debug", debug_dir_);
root_dir_->AddSharedEntry("ctrl", ctrl_dir_);
root_dir_->Serve(
fuchsia::io::OPEN_RIGHT_READABLE | fuchsia::io::OPEN_RIGHT_WRITABLE,
std::move(directory_request));
}
RunnerContext::~RunnerContext() = default;
std::unique_ptr<RunnerContext> RunnerContext::CreateFromStartupInfo() {
zx_handle_t directory_request = zx_take_startup_handle(PA_DIRECTORY_REQUEST);
return std::make_unique<RunnerContext>(
sys::ServiceDirectory::CreateFromNamespace(),
zx::channel(directory_request));
}
zx_status_t RunnerContext::AddPublicService(
std::unique_ptr<vfs::Service> service,
std::string service_name) const {
return public_dir_->AddEntry(std::move(service_name), std::move(service));
}
} // namespace flutter_runner

View File

@@ -0,0 +1,70 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_RUNNER_CONTEXT_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNNER_CONTEXT_H_
#include <memory>
#include <unordered_map>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <lib/vfs/cpp/service.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include "flutter/fml/macros.h"
namespace flutter_runner {
class RunnerContext {
public:
RunnerContext(std::shared_ptr<sys::ServiceDirectory> svc,
zx::channel directory_request);
~RunnerContext();
static std::unique_ptr<RunnerContext> CreateFromStartupInfo();
const std::shared_ptr<sys::ServiceDirectory>& svc() const { return svc_; }
const std::shared_ptr<vfs::PseudoDir>& root_dir() const { return root_dir_; }
const std::shared_ptr<vfs::PseudoDir>& public_dir() const {
return public_dir_;
}
const std::shared_ptr<vfs::PseudoDir>& debug_dir() const {
return debug_dir_;
}
const std::shared_ptr<vfs::PseudoDir>& ctrl_dir() const { return ctrl_dir_; }
template <typename Interface>
zx_status_t AddPublicService(
fidl::InterfaceRequestHandler<Interface> handler,
std::string service_name = Interface::Name_) const {
return AddPublicService(std::make_unique<vfs::Service>(std::move(handler)),
std::move(service_name));
}
zx_status_t AddPublicService(std::unique_ptr<vfs::Service> service,
std::string service_name) const;
template <typename Interface>
zx_status_t RemovePublicService(
const std::string& name = Interface::Name_) const {
return public_dir_->RemoveEntry(name);
}
private:
std::shared_ptr<sys::ServiceDirectory> svc_;
std::shared_ptr<vfs::PseudoDir> root_dir_;
std::shared_ptr<vfs::PseudoDir> public_dir_;
std::shared_ptr<vfs::PseudoDir> debug_dir_;
std::shared_ptr<vfs::PseudoDir> ctrl_dir_;
FML_DISALLOW_COPY_AND_ASSIGN(RunnerContext);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNNER_CONTEXT_H_

View File

@@ -1,4 +1,4 @@
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

View File

@@ -0,0 +1,69 @@
// Copyright 2013 The Flutter 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 "service_provider_dir.h"
#include <lib/async/default.h>
#include <lib/fdio/directory.h>
#include <zircon/status.h>
namespace flutter_runner {
ServiceProviderDir::ServiceProviderDir() : root_(new vfs::PseudoDir()) {}
ServiceProviderDir::~ServiceProviderDir() {}
void ServiceProviderDir::set_fallback(
fidl::InterfaceHandle<fuchsia::io::Directory> fallback_dir) {
fallback_dir_ = fallback_dir.TakeChannel();
}
void ServiceProviderDir::AddService(const std::string& service_name,
std::unique_ptr<vfs::Service> service) {
root_->AddEntry(service_name, std::move(service));
}
zx_status_t ServiceProviderDir::GetAttr(
fuchsia::io::NodeAttributes* out_attributes) const {
return root_->GetAttr(out_attributes);
}
zx_status_t ServiceProviderDir::Readdir(uint64_t offset,
void* data,
uint64_t len,
uint64_t* out_offset,
uint64_t* out_actual) {
// TODO(anmittal): enumerate fallback_dir_ in future once we have simple
// implementation of fuchsia.io.Directory.
return root_->Readdir(offset, data, len, out_offset, out_actual);
}
zx_status_t ServiceProviderDir::Lookup(const std::string& name,
vfs::Node** out) const {
zx_status_t status = root_->Lookup(name, out);
if (status == ZX_OK) {
return status;
}
if (fallback_dir_) {
auto entry = fallback_services_.find(name);
if (entry != fallback_services_.end()) {
*out = entry->second.get();
} else {
auto service = std::make_unique<vfs::Service>(
[name = std::string(name.data(), name.length()),
dir = &fallback_dir_](zx::channel request,
async_dispatcher_t* dispatcher) {
fdio_service_connect_at(dir->get(), name.c_str(),
request.release());
});
*out = service.get();
fallback_services_[name] = std::move(service);
}
} else {
return ZX_ERR_NOT_FOUND;
}
return ZX_OK;
}
} // namespace flutter_runner

View File

@@ -0,0 +1,73 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_SERVICE_PROVIDER_DIR_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_SERVICE_PROVIDER_DIR_H_
#include <map>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include <fuchsia/io/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <lib/vfs/cpp/service.h>
#include "lib/fidl/cpp/binding_set.h"
namespace flutter_runner {
// A directory-like object which dynamically creates Service nodes
// for any file lookup. It also exposes service provider interface.
//
// It supports enumeration for only first level of services.
class ServiceProviderDir : public vfs::Directory {
public:
ServiceProviderDir();
~ServiceProviderDir() override;
void set_fallback(fidl::InterfaceHandle<fuchsia::io::Directory> fallback_dir);
void AddService(const std::string& service_name,
std::unique_ptr<vfs::Service> service);
//
// Overridden from |vfs::Node|:
//
zx_status_t Lookup(const std::string& name, vfs::Node** out_node) const final;
zx_status_t GetAttr(fuchsia::io::NodeAttributes* out_attributes) const final;
zx_status_t Readdir(uint64_t offset,
void* data,
uint64_t len,
uint64_t* out_offset,
uint64_t* out_actual) final;
private:
// |root_| has all services offered by this provider (including those
// inherited from the parent, if any).
std::unique_ptr<vfs::PseudoDir> root_;
zx::channel fallback_dir_;
// The collection of services that have been looked up on the fallback
// directory. These services are just passthrough in the sense that they
// forward connection requests to the fallback directory. Since there is no
// good way in the present context to know whether these service entries
// actually match an existing service, and since the present object must own
// these entries, we keep them around until the present object gets deleted.
// Needs to be marked mutable so that it can be altered by the Lookup method.
mutable std::map<std::string, std::unique_ptr<vfs::Service>>
fallback_services_;
// Disallow copy and assignment.
ServiceProviderDir(const ServiceProviderDir&) = delete;
ServiceProviderDir& operator=(const ServiceProviderDir&) = delete;
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_SERVICE_PROVIDER_DIR_H_

View File

@@ -0,0 +1,110 @@
// Copyright 2013 The Flutter 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 "session_connection.h"
#include "flutter/fml/make_copyable.h"
#include "lib/fidl/cpp/optional.h"
#include "lib/ui/scenic/cpp/commands.h"
#include "vsync_recorder.h"
#include "vsync_waiter.h"
namespace flutter_runner {
SessionConnection::SessionConnection(
std::string debug_label,
fuchsia::ui::views::ViewToken view_token,
fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session,
fit::closure session_error_callback,
zx_handle_t vsync_event_handle)
: debug_label_(std::move(debug_label)),
session_wrapper_(session.Bind(), nullptr),
root_view_(&session_wrapper_, std::move(view_token.value), debug_label),
root_node_(&session_wrapper_),
surface_producer_(
std::make_unique<VulkanSurfaceProducer>(&session_wrapper_)),
scene_update_context_(&session_wrapper_, surface_producer_.get()),
vsync_event_handle_(vsync_event_handle) {
session_wrapper_.set_error_handler(
[callback = std::move(session_error_callback)](zx_status_t status) {
callback();
});
session_wrapper_.SetDebugName(debug_label_);
// TODO(SCN-975): Re-enable.
// view_->GetToken(std::bind(&PlatformView::ConnectSemanticsProvider, this,
// std::placeholders::_1));
root_view_.AddChild(root_node_);
root_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask |
fuchsia::ui::gfx::kSizeChangeHintEventMask);
// Signal is initially high indicating availability of the session.
ToggleSignal(vsync_event_handle_, true);
PresentSession();
}
SessionConnection::~SessionConnection() = default;
void SessionConnection::Present(
flutter::CompositorContext::ScopedFrame& frame) {
// Flush all session ops. Paint tasks have not yet executed but those are
// fenced. The compositor can start processing ops while we finalize paint
// tasks.
PresentSession();
// Execute paint tasks and signal fences.
auto surfaces_to_submit = scene_update_context_.ExecutePaintTasks(frame);
// Tell the surface producer that a present has occurred so it can perform
// book-keeping on buffer caches.
surface_producer_->OnSurfacesPresented(std::move(surfaces_to_submit));
// Prepare for the next frame. These ops won't be processed till the next
// present.
EnqueueClearOps();
}
void SessionConnection::OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor) {
surface_producer_->OnSessionSizeChangeHint(width_change_factor,
height_change_factor);
}
void SessionConnection::EnqueueClearOps() {
// We are going to be sending down a fresh node hierarchy every frame. So just
// enqueue a detach op on the imported root node.
session_wrapper_.Enqueue(scenic::NewDetachChildrenCmd(root_node_.id()));
}
void SessionConnection::PresentSession() {
TRACE_EVENT0("gfx", "SessionConnection::PresentSession");
TRACE_FLOW_BEGIN("gfx", "Session::Present", next_present_trace_id_);
next_present_trace_id_++;
ToggleSignal(vsync_event_handle_, false);
session_wrapper_.Present(
0, // presentation_time. (placeholder).
[handle = vsync_event_handle_](
fuchsia::images::PresentationInfo presentation_info) {
VsyncRecorder::GetInstance().UpdateVsyncInfo(presentation_info);
ToggleSignal(handle, true);
} // callback
);
}
void SessionConnection::ToggleSignal(zx_handle_t handle, bool set) {
const auto signal = VsyncWaiter::SessionPresentSignal;
auto status = zx_object_signal(handle, // handle
set ? 0 : signal, // clear mask
set ? signal : 0 // set mask
);
if (status != ZX_OK) {
FML_LOG(ERROR) << "Could not toggle vsync signal: " << set;
}
}
} // namespace flutter_runner

View File

@@ -0,0 +1,90 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_SESSION_CONNECTION_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_SESSION_CONNECTION_H_
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fidl/cpp/interface_handle.h>
#include <lib/fidl/cpp/optional.h>
#include <lib/fit/function.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/session.h>
#include "flutter/flow/compositor_context.h"
#include "flutter/flow/scene_update_context.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/trace_event.h"
#include "vulkan_surface_producer.h"
namespace flutter_runner {
// The component residing on the GPU thread that is responsible for
// maintaining the Scenic session connection and presenting node updates.
class SessionConnection final {
public:
SessionConnection(std::string debug_label,
fuchsia::ui::views::ViewToken view_token,
fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session,
fit::closure session_error_callback,
zx_handle_t vsync_event_handle);
~SessionConnection();
bool has_metrics() const { return scene_update_context_.has_metrics(); }
const fuchsia::ui::gfx::MetricsPtr& metrics() const {
return scene_update_context_.metrics();
}
void set_metrics(const fuchsia::ui::gfx::Metrics& metrics) {
fuchsia::ui::gfx::Metrics metrics_copy;
metrics.Clone(&metrics_copy);
scene_update_context_.set_metrics(
fidl::MakeOptional(std::move(metrics_copy)));
}
flutter::SceneUpdateContext& scene_update_context() {
return scene_update_context_;
}
scenic::ContainerNode& root_node() { return root_node_; }
scenic::View* root_view() { return &root_view_; }
void Present(flutter::CompositorContext::ScopedFrame& frame);
void OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor);
private:
const std::string debug_label_;
scenic::Session session_wrapper_;
scenic::View root_view_;
scenic::EntityNode root_node_;
std::unique_ptr<VulkanSurfaceProducer> surface_producer_;
flutter::SceneUpdateContext scene_update_context_;
zx_handle_t vsync_event_handle_;
// A flow event trace id for following |Session::Present| calls into
// Scenic. This will be incremented each |Session::Present| call. By
// convention, the Scenic side will also contain its own trace id that
// begins at 0, and is incremented each |Session::Present| call.
uint64_t next_present_trace_id_ = 0;
void EnqueueClearOps();
void PresentSession();
static void ToggleSignal(zx_handle_t handle, bool raise);
FML_DISALLOW_COPY_AND_ASSIGN(SessionConnection);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_SESSION_CONNECTION_H_

View File

@@ -0,0 +1,70 @@
// Copyright 2013 The Flutter 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 "surface.h"
#include <fcntl.h>
#include <lib/fdio/watcher.h>
#include <unistd.h>
#include "flutter/fml/unique_fd.h"
namespace flutter_runner {
Surface::Surface(std::string debug_label)
: debug_label_(std::move(debug_label)) {}
Surface::~Surface() = default;
// |flutter::Surface|
bool Surface::IsValid() {
return valid_;
}
// |flutter::Surface|
std::unique_ptr<flutter::SurfaceFrame> Surface::AcquireFrame(
const SkISize& size) {
return std::make_unique<flutter::SurfaceFrame>(
nullptr, [](const flutter::SurfaceFrame& surface_frame,
SkCanvas* canvas) { return true; });
}
// |flutter::Surface|
GrContext* Surface::GetContext() {
return nullptr;
}
static zx_status_t DriverWatcher(int dirfd,
int event,
const char* fn,
void* cookie) {
if (event == WATCH_EVENT_ADD_FILE && !strcmp(fn, "000")) {
return ZX_ERR_STOP;
}
return ZX_OK;
}
bool Surface::CanConnectToDisplay() {
constexpr char kGpuDriverClass[] = "/dev/class/gpu";
fml::UniqueFD fd(open(kGpuDriverClass, O_DIRECTORY | O_RDONLY));
if (fd.get() < 0) {
FML_DLOG(ERROR) << "Failed to open " << kGpuDriverClass;
return false;
}
zx_status_t status = fdio_watch_directory(
fd.get(), DriverWatcher, zx_deadline_after(ZX_SEC(5)), nullptr);
return status == ZX_ERR_STOP;
}
// |flutter::Surface|
SkMatrix Surface::GetRootTransformation() const {
// This backend does not support delegating to the underlying platform to
// query for root surface transformations. Just return identity.
SkMatrix matrix;
matrix.reset();
return matrix;
}
} // namespace flutter_runner

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "compositor_context.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/shell/common/surface.h"
namespace flutter_runner {
// The interface between the Flutter rasterizer and the underlying platform. May
// be constructed on any thread but will be used by the engine only on the GPU
// thread.
class Surface final : public flutter::Surface {
public:
Surface(std::string debug_label);
~Surface() override;
private:
const bool valid_ = CanConnectToDisplay();
const std::string debug_label_;
// |flutter::Surface|
bool IsValid() override;
// |flutter::Surface|
std::unique_ptr<flutter::SurfaceFrame> AcquireFrame(
const SkISize& size) override;
// |flutter::Surface|
GrContext* GetContext() override;
// |flutter::Surface|
SkMatrix GetRootTransformation() const override;
static bool CanConnectToDisplay();
FML_DISALLOW_COPY_AND_ASSIGN(Surface);
};
} // namespace flutter_runner

View File

@@ -0,0 +1,30 @@
// Copyright 2013 The Flutter 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 "task_observers.h"
#include <map>
namespace flutter_runner {
thread_local std::map<intptr_t, fit::closure> tTaskObservers;
void ExecuteAfterTaskObservers() {
for (const auto& callback : tTaskObservers) {
callback.second();
}
}
void CurrentMessageLoopAddAfterTaskObserver(intptr_t key,
fit::closure observer) {
if (observer) {
tTaskObservers[key] = std::move(observer);
}
}
void CurrentMessageLoopRemoveAfterTaskObserver(intptr_t key) {
tTaskObservers.erase(key);
}
} // namespace flutter_runner

View File

@@ -0,0 +1,21 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_
#include <lib/fit/function.h>
namespace flutter_runner {
void ExecuteAfterTaskObservers();
void CurrentMessageLoopAddAfterTaskObserver(intptr_t key,
fit::closure observer);
void CurrentMessageLoopRemoveAfterTaskObserver(intptr_t key);
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_

View File

@@ -0,0 +1,54 @@
// Copyright 2013 The Flutter 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 "task_runner_adapter.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/zx/time.h>
#include "flutter/fml/message_loop_impl.h"
namespace flutter_runner {
class CompatTaskRunner : public fml::TaskRunner {
public:
CompatTaskRunner(async_dispatcher_t* dispatcher)
: fml::TaskRunner(nullptr), forwarding_target_(dispatcher) {
FML_DCHECK(forwarding_target_);
}
void PostTask(fml::closure task) override {
async::PostTask(forwarding_target_, std::move(task));
}
void PostTaskForTime(fml::closure task, fml::TimePoint target_time) override {
async::PostTaskForTime(
forwarding_target_, std::move(task),
zx::time(target_time.ToEpochDelta().ToNanoseconds()));
}
void PostDelayedTask(fml::closure task, fml::TimeDelta delay) override {
async::PostDelayedTask(forwarding_target_, std::move(task),
zx::duration(delay.ToNanoseconds()));
}
bool RunsTasksOnCurrentThread() override {
return forwarding_target_ == async_get_default_dispatcher();
}
private:
async_dispatcher_t* forwarding_target_;
FML_DISALLOW_COPY_AND_ASSIGN(CompatTaskRunner);
FML_FRIEND_MAKE_REF_COUNTED(CompatTaskRunner);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(CompatTaskRunner);
};
fml::RefPtr<fml::TaskRunner> CreateFMLTaskRunner(
async_dispatcher_t* dispatcher) {
return fml::MakeRefCounted<CompatTaskRunner>(dispatcher);
}
} // namespace flutter_runner

View File

@@ -0,0 +1,16 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <lib/async/dispatcher.h>
#include "flutter/fml/task_runner.h"
namespace flutter_runner {
fml::RefPtr<fml::TaskRunner> CreateFMLTaskRunner(
async_dispatcher_t* dispatcher);
} // namespace flutter_runner

View File

@@ -0,0 +1,27 @@
{
"families": [
{
"family": "Roboto",
"fallback": true,
"fallback_group": "sans-serif",
"fonts": [
{
"asset": "Roboto-Regular.ttf"
}
]
},
{
"family": "Roboto Slab",
"aliases": [
"RobotoSlab"
],
"fallback": true,
"fallback_group": "serif",
"fonts": [
{
"asset": "RobotoSlab-Regular.ttf"
}
]
}
]
}

View File

@@ -0,0 +1,103 @@
// Copyright 2013 The Flutter 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 "thread.h"
#include <limits.h>
#include <unistd.h>
#include <algorithm>
#include <lib/async-loop/cpp/loop.h>
#include "flutter/fml/logging.h"
#include "loop.h"
namespace flutter_runner {
typedef void (*ThreadEntry)(Thread*);
namespace {
size_t NextPageSizeMultiple(size_t size) {
const size_t page_size = sysconf(_SC_PAGE_SIZE);
FML_CHECK(page_size != 0);
size = std::max<size_t>(size, page_size);
size_t rem = size % page_size;
if (rem == 0) {
return size;
}
return size + page_size - rem;
}
bool CreateThread(pthread_t* thread,
ThreadEntry main,
Thread* argument,
size_t stack_size) {
pthread_attr_t thread_attributes;
if (pthread_attr_init(&thread_attributes) != 0) {
return false;
}
stack_size = std::max<size_t>(NextPageSizeMultiple(PTHREAD_STACK_MIN),
NextPageSizeMultiple(stack_size));
if (pthread_attr_setstacksize(&thread_attributes, stack_size) != 0) {
return false;
}
auto result =
pthread_create(thread, &thread_attributes,
reinterpret_cast<void* (*)(void*)>(main), argument);
pthread_attr_destroy(&thread_attributes);
return result == 0;
}
} // anonymous namespace
Thread::Thread() {
loop_.reset(MakeObservableLoop(false));
valid_ = CreateThread(
&thread_, [](Thread* thread) { thread->Main(); }, this, 1 << 20);
}
Thread::~Thread() {
Join();
}
bool Thread::IsValid() const {
return valid_;
}
async_dispatcher_t* Thread::dispatcher() const {
return loop_->dispatcher();
}
void Thread::Main() {
async_set_default_dispatcher(loop_->dispatcher());
loop_->Run();
}
void Thread::Quit() {
loop_->Quit();
}
bool Thread::Join() {
if (!valid_) {
return false;
}
bool result = pthread_join(thread_, nullptr) == 0;
valid_ = false;
return result;
}
} // namespace flutter_runner

View File

@@ -0,0 +1,44 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_THREAD_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_THREAD_H_
#include <pthread.h>
#include <functional>
#include <lib/async-loop/cpp/loop.h>
#include "flutter/fml/macros.h"
namespace flutter_runner {
class Thread {
public:
Thread();
~Thread();
void Quit();
bool Join();
bool IsValid() const;
async_dispatcher_t* dispatcher() const;
private:
bool valid_;
pthread_t thread_;
std::unique_ptr<async::Loop> loop_;
void Main();
FML_DISALLOW_COPY_AND_ASSIGN(Thread);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_THREAD_H_

View File

@@ -0,0 +1,34 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/logging.h"
#include "flutter/fml/unique_object.h"
#include "lib/fdio/namespace.h"
namespace flutter_runner {
struct UniqueFDIONSTraits {
static fdio_ns_t* InvalidValue() { return nullptr; }
static bool IsValid(fdio_ns_t* ns) { return ns != InvalidValue(); }
static void Free(fdio_ns_t* ns) {
auto status = fdio_ns_destroy(ns);
FML_DCHECK(status == ZX_OK);
}
};
using UniqueFDIONS = fml::UniqueObject<fdio_ns_t*, UniqueFDIONSTraits>;
inline UniqueFDIONS UniqueFDIONSCreate() {
fdio_ns_t* ns = nullptr;
if (fdio_ns_create(&ns) == ZX_OK) {
return UniqueFDIONS{ns};
}
return UniqueFDIONS{nullptr};
}
} // namespace flutter_runner

View File

@@ -0,0 +1,52 @@
// Copyright 2013 The Flutter 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 "vsync_recorder.h"
#include <mutex>
namespace flutter_runner {
namespace {
std::mutex g_mutex;
// Since we don't have any presentation info until we call |Present| for the
// first time, assume a 60hz refresh rate in the meantime.
constexpr fml::TimeDelta kDefaultPresentationInterval =
fml::TimeDelta::FromSecondsF(1.0 / 60.0);
} // namespace
VsyncRecorder& VsyncRecorder::GetInstance() {
static VsyncRecorder vsync_recorder;
return vsync_recorder;
}
VsyncInfo VsyncRecorder::GetCurrentVsyncInfo() const {
{
std::unique_lock<std::mutex> lock(g_mutex);
if (last_presentation_info_) {
return {fml::TimePoint::FromEpochDelta(fml::TimeDelta::FromNanoseconds(
last_presentation_info_->presentation_time)),
fml::TimeDelta::FromNanoseconds(
last_presentation_info_->presentation_interval)};
}
}
return {fml::TimePoint::Now(), kDefaultPresentationInterval};
}
void VsyncRecorder::UpdateVsyncInfo(
fuchsia::images::PresentationInfo presentation_info) {
std::unique_lock<std::mutex> lock(g_mutex);
if (last_presentation_info_ &&
presentation_info.presentation_time >
last_presentation_info_->presentation_time) {
last_presentation_info_ = presentation_info;
} else if (!last_presentation_info_) {
last_presentation_info_ = presentation_info;
}
}
} // namespace flutter_runner

View File

@@ -0,0 +1,49 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_VSYNC_RECORDER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_VSYNC_RECORDER_H_
#include <optional>
#include "flutter/fml/time/time_delta.h"
#include "flutter/fml/time/time_point.h"
#include "lib/ui/scenic/cpp/session.h"
namespace flutter_runner {
struct VsyncInfo {
fml::TimePoint presentation_time;
fml::TimeDelta presentation_interval;
};
class VsyncRecorder {
public:
static VsyncRecorder& GetInstance();
// Retrieve the most recent |PresentationInfo| provided to us by scenic.
// This function is safe to call from any thread.
VsyncInfo GetCurrentVsyncInfo() const;
// Update the current Vsync info to |presentation_info|. This is expected
// to be called in |scenic::Sesssion::Present| callbacks with the
// presentation info provided by scenic. Only the most recent vsync
// information will be saved (in order to handle edge cases involving
// multiple scenic sessions in the same process). This function is safe to
// call from any thread.
void UpdateVsyncInfo(fuchsia::images::PresentationInfo presentation_info);
private:
VsyncRecorder() = default;
std::optional<fuchsia::images::PresentationInfo> last_presentation_info_;
// Disallow copy and assignment.
VsyncRecorder(const VsyncRecorder&) = delete;
VsyncRecorder& operator=(const VsyncRecorder&) = delete;
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_VSYNC_RECORDER_H_

View File

@@ -0,0 +1,89 @@
// Copyright 2013 The Flutter 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 "vsync_waiter.h"
#include <lib/async/default.h>
#include "flutter/fml/trace_event.h"
#include "vsync_recorder.h"
namespace flutter_runner {
VsyncWaiter::VsyncWaiter(std::string debug_label,
zx_handle_t session_present_handle,
flutter::TaskRunners task_runners)
: flutter::VsyncWaiter(task_runners),
debug_label_(std::move(debug_label)),
session_wait_(session_present_handle, SessionPresentSignal),
weak_factory_(this) {
auto wait_handler = [&](async_dispatcher_t* dispatcher, //
async::Wait* wait, //
zx_status_t status, //
const zx_packet_signal_t* signal //
) {
if (status != ZX_OK) {
FML_LOG(ERROR) << "Vsync wait failed.";
return;
}
wait->Cancel();
FireCallbackNow();
};
session_wait_.set_handler(wait_handler);
}
VsyncWaiter::~VsyncWaiter() {
session_wait_.Cancel();
}
static fml::TimePoint SnapToNextPhase(fml::TimePoint value,
fml::TimePoint phase,
fml::TimeDelta interval) {
fml::TimeDelta offset = (phase - value) % interval;
if (offset < fml::TimeDelta::Zero()) {
offset = offset + interval;
}
return value + offset;
}
void VsyncWaiter::AwaitVSync() {
VsyncInfo vsync_info = VsyncRecorder::GetInstance().GetCurrentVsyncInfo();
fml::TimePoint now = fml::TimePoint::Now();
fml::TimePoint next_vsync = SnapToNextPhase(now, vsync_info.presentation_time,
vsync_info.presentation_interval);
task_runners_.GetUITaskRunner()->PostDelayedTask(
[self = weak_factory_.GetWeakPtr()] {
if (self) {
self->FireCallbackWhenSessionAvailable();
}
},
next_vsync - now);
}
void VsyncWaiter::FireCallbackWhenSessionAvailable() {
TRACE_EVENT0("flutter", "VsyncWaiter::FireCallbackWhenSessionAvailable");
FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
if (session_wait_.Begin(async_get_default_dispatcher()) != ZX_OK) {
FML_LOG(ERROR) << "Could not begin wait for Vsync.";
}
}
void VsyncWaiter::FireCallbackNow() {
FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
VsyncInfo vsync_info = VsyncRecorder::GetInstance().GetCurrentVsyncInfo();
fml::TimePoint now = fml::TimePoint::Now();
fml::TimePoint next_vsync = SnapToNextPhase(now, vsync_info.presentation_time,
vsync_info.presentation_interval);
fml::TimePoint previous_vsync = next_vsync - vsync_info.presentation_interval;
FireCallback(previous_vsync, next_vsync);
}
} // namespace flutter_runner

View File

@@ -0,0 +1,44 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_FUCHSIA_VSYNC_WAITER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_VSYNC_WAITER_H_
#include <lib/async/cpp/wait.h>
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/time/time_point.h"
#include "flutter/shell/common/vsync_waiter.h"
namespace flutter_runner {
class VsyncWaiter final : public flutter::VsyncWaiter {
public:
static constexpr zx_signals_t SessionPresentSignal = ZX_EVENT_SIGNALED;
VsyncWaiter(std::string debug_label,
zx_handle_t session_present_handle,
flutter::TaskRunners task_runners);
~VsyncWaiter() override;
private:
const std::string debug_label_;
async::Wait session_wait_;
fml::WeakPtrFactory<VsyncWaiter> weak_factory_;
// |flutter::VsyncWaiter|
void AwaitVSync() override;
void FireCallbackWhenSessionAvailable();
void FireCallbackNow();
FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiter);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_VSYNC_WAITER_H_

View File

@@ -0,0 +1,507 @@
// Copyright 2013 The Flutter 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 "vulkan_surface.h"
#include <lib/async/default.h>
#include <algorithm>
#include "flutter/fml/trace_event.h"
#include "runtime/dart/utils/inlines.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/gpu/GrBackendSemaphore.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace flutter_runner {
namespace {
constexpr SkColorType kSkiaColorType = kBGRA_8888_SkColorType;
} // namespace
bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider,
const SkISize& size,
VulkanImage* out_vulkan_image) {
TRACE_EVENT0("flutter", "CreateVulkanImage");
FML_DCHECK(!size.isEmpty());
FML_DCHECK(out_vulkan_image != nullptr);
// The image creation parameters need to be the same as those in scenic
// (garnet/lib/ui/gfx/resources/gpu_image.cc and
// garnet/public/lib/escher/util/image_utils.cc) or else the different vulkan
// devices may interpret the bytes differently.
// TODO(SCN-1369): Use API to coordinate this with scenic.
out_vulkan_image->vk_image_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = nullptr,
.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,
.imageType = VK_IMAGE_TYPE_2D,
.format = VK_FORMAT_B8G8R8A8_UNORM,
.extent = VkExtent3D{static_cast<uint32_t>(size.width()),
static_cast<uint32_t>(size.height()), 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
{
VkImage vk_image = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vulkan_provider.vk().CreateImage(
vulkan_provider.vk_device(),
&out_vulkan_image->vk_image_create_info, nullptr, &vk_image)) !=
VK_SUCCESS) {
return false;
}
out_vulkan_image->vk_image = {
vk_image, [& vulkan_provider = vulkan_provider](VkImage image) {
vulkan_provider.vk().DestroyImage(vulkan_provider.vk_device(), image,
NULL);
}};
}
vulkan_provider.vk().GetImageMemoryRequirements(
vulkan_provider.vk_device(), out_vulkan_image->vk_image,
&out_vulkan_image->vk_memory_requirements);
return true;
}
VulkanSurface::VulkanSurface(vulkan::VulkanProvider& vulkan_provider,
sk_sp<GrContext> context,
scenic::Session* session,
const SkISize& size)
: vulkan_provider_(vulkan_provider), session_(session), wait_(this) {
FML_DCHECK(session_);
zx::vmo exported_vmo;
if (!AllocateDeviceMemory(std::move(context), size, exported_vmo)) {
FML_DLOG(INFO) << "Could not allocate device memory.";
return;
}
uint64_t vmo_size;
zx_status_t status = exported_vmo.get_size(&vmo_size);
FML_DCHECK(status == ZX_OK);
if (!CreateFences()) {
FML_DLOG(INFO) << "Could not create signal fences.";
return;
}
scenic_memory_ = std::make_unique<scenic::Memory>(
session, std::move(exported_vmo), vmo_size,
fuchsia::images::MemoryType::VK_DEVICE_MEMORY);
if (!PushSessionImageSetupOps(session)) {
FML_DLOG(INFO) << "Could not push session image setup ops.";
return;
}
std::fill(size_history_.begin(), size_history_.end(), SkISize::MakeEmpty());
wait_.set_object(release_event_.get());
wait_.set_trigger(ZX_EVENT_SIGNALED);
Reset();
valid_ = true;
}
VulkanSurface::~VulkanSurface() {
wait_.Cancel();
wait_.set_object(ZX_HANDLE_INVALID);
}
bool VulkanSurface::IsValid() const {
return valid_;
}
SkISize VulkanSurface::GetSize() const {
if (!valid_) {
return SkISize::Make(0, 0);
}
return SkISize::Make(sk_surface_->width(), sk_surface_->height());
}
vulkan::VulkanHandle<VkSemaphore> VulkanSurface::SemaphoreFromEvent(
const zx::event& event) const {
VkResult result;
VkSemaphore semaphore;
zx::event semaphore_event;
zx_status_t status = event.duplicate(ZX_RIGHT_SAME_RIGHTS, &semaphore_event);
if (status != ZX_OK) {
FML_DLOG(ERROR) << "failed to duplicate semaphore event";
return vulkan::VulkanHandle<VkSemaphore>();
}
VkSemaphoreCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
result = VK_CALL_LOG_ERROR(vulkan_provider_.vk().CreateSemaphore(
vulkan_provider_.vk_device(), &create_info, nullptr, &semaphore));
if (result != VK_SUCCESS) {
return vulkan::VulkanHandle<VkSemaphore>();
}
VkImportSemaphoreZirconHandleInfoFUCHSIA import_info = {
.sType =
VK_STRUCTURE_TYPE_TEMP_IMPORT_SEMAPHORE_ZIRCON_HANDLE_INFO_FUCHSIA,
.pNext = nullptr,
.semaphore = semaphore,
.handleType =
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA,
.handle = static_cast<uint32_t>(semaphore_event.release())};
result = VK_CALL_LOG_ERROR(
vulkan_provider_.vk().ImportSemaphoreZirconHandleFUCHSIA(
vulkan_provider_.vk_device(), &import_info));
if (result != VK_SUCCESS) {
return vulkan::VulkanHandle<VkSemaphore>();
}
return vulkan::VulkanHandle<VkSemaphore>(
semaphore, [&vulkan_provider = vulkan_provider_](VkSemaphore semaphore) {
vulkan_provider.vk().DestroySemaphore(vulkan_provider.vk_device(),
semaphore, nullptr);
});
}
bool VulkanSurface::CreateFences() {
if (zx::event::create(0, &acquire_event_) != ZX_OK) {
return false;
}
acquire_semaphore_ = SemaphoreFromEvent(acquire_event_);
if (!acquire_semaphore_) {
FML_DLOG(ERROR) << "failed to create acquire semaphore";
return false;
}
if (zx::event::create(0, &release_event_) != ZX_OK) {
return false;
}
command_buffer_fence_ = vulkan_provider_.CreateFence();
return true;
}
bool VulkanSurface::AllocateDeviceMemory(sk_sp<GrContext> context,
const SkISize& size,
zx::vmo& exported_vmo) {
if (size.isEmpty()) {
return false;
}
VulkanImage vulkan_image;
if (!CreateVulkanImage(vulkan_provider_, size, &vulkan_image)) {
FML_DLOG(ERROR) << "Failed to create VkImage";
return false;
}
vulkan_image_ = std::move(vulkan_image);
const VkMemoryRequirements& memory_reqs =
vulkan_image_.vk_memory_requirements;
const VkImageCreateInfo& image_create_info =
vulkan_image_.vk_image_create_info;
uint32_t memory_type = 0;
for (; memory_type < 32; memory_type++) {
if ((memory_reqs.memoryTypeBits & (1 << memory_type))) {
break;
}
}
VkExportMemoryAllocateInfoKHR export_allocate_info = {
.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR,
.pNext = nullptr,
.handleTypes =
VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA};
const VkMemoryAllocateInfo alloc_info = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = &export_allocate_info,
.allocationSize = memory_reqs.size,
.memoryTypeIndex = memory_type,
};
{
TRACE_EVENT0("flutter", "vkAllocateMemory");
VkDeviceMemory vk_memory = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().AllocateMemory(
vulkan_provider_.vk_device(), &alloc_info, NULL, &vk_memory)) !=
VK_SUCCESS) {
return false;
}
vk_memory_ = {vk_memory, [& vulkan_provider =
vulkan_provider_](VkDeviceMemory memory) {
vulkan_provider.vk().FreeMemory(vulkan_provider.vk_device(),
memory, NULL);
}};
vk_memory_info_ = alloc_info;
}
// Bind image memory.
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().BindImageMemory(
vulkan_provider_.vk_device(), vulkan_image_.vk_image, vk_memory_,
0)) != VK_SUCCESS) {
return false;
}
{
// Acquire the VMO for the device memory.
uint32_t vmo_handle = 0;
VkMemoryGetZirconHandleInfoFUCHSIA get_handle_info = {
VK_STRUCTURE_TYPE_TEMP_MEMORY_GET_ZIRCON_HANDLE_INFO_FUCHSIA, nullptr,
vk_memory_, VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA};
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().GetMemoryZirconHandleFUCHSIA(
vulkan_provider_.vk_device(), &get_handle_info, &vmo_handle)) !=
VK_SUCCESS) {
return false;
}
exported_vmo.reset(static_cast<zx_handle_t>(vmo_handle));
}
// Assert that the VMO size was sufficient.
size_t vmo_size = 0;
if (exported_vmo.get_size(&vmo_size) != ZX_OK ||
vmo_size < memory_reqs.size) {
return false;
}
return SetupSkiaSurface(std::move(context), size, kSkiaColorType,
image_create_info, memory_reqs);
}
bool VulkanSurface::SetupSkiaSurface(sk_sp<GrContext> context,
const SkISize& size,
SkColorType color_type,
const VkImageCreateInfo& image_create_info,
const VkMemoryRequirements& memory_reqs) {
if (context == nullptr) {
return false;
}
const GrVkImageInfo image_info = {
vulkan_image_.vk_image, // image
{vk_memory_, 0, memory_reqs.size, 0}, // alloc
image_create_info.tiling, // tiling
image_create_info.initialLayout, // layout
image_create_info.format, // format
image_create_info.mipLevels, // level count
};
GrBackendRenderTarget sk_render_target(size.width(), size.height(), 0,
image_info);
SkSurfaceProps sk_surface_props(
SkSurfaceProps::InitType::kLegacyFontHost_InitType);
auto sk_surface =
SkSurface::MakeFromBackendRenderTarget(context.get(), //
sk_render_target, //
kTopLeft_GrSurfaceOrigin, //
color_type, //
nullptr, //
&sk_surface_props //
);
if (!sk_surface || sk_surface->getCanvas() == nullptr) {
return false;
}
sk_surface_ = std::move(sk_surface);
return true;
}
bool VulkanSurface::PushSessionImageSetupOps(scenic::Session* session) {
FML_DCHECK(scenic_memory_ != nullptr);
if (sk_surface_ == nullptr) {
return false;
}
fuchsia::images::ImageInfo image_info;
image_info.width = sk_surface_->width();
image_info.height = sk_surface_->height();
image_info.stride = 4 * sk_surface_->width();
image_info.pixel_format = fuchsia::images::PixelFormat::BGRA_8;
image_info.color_space = fuchsia::images::ColorSpace::SRGB;
switch (vulkan_image_.vk_image_create_info.tiling) {
case VK_IMAGE_TILING_OPTIMAL:
image_info.tiling = fuchsia::images::Tiling::GPU_OPTIMAL;
break;
case VK_IMAGE_TILING_LINEAR:
image_info.tiling = fuchsia::images::Tiling::LINEAR;
break;
default:
FML_DLOG(ERROR) << "Bad image tiling: "
<< vulkan_image_.vk_image_create_info.tiling;
return false;
}
session_image_ = std::make_unique<scenic::Image>(
*scenic_memory_, 0 /* memory offset */, std::move(image_info));
return session_image_ != nullptr;
}
scenic::Image* VulkanSurface::GetImage() {
if (!valid_) {
return 0;
}
return session_image_.get();
}
sk_sp<SkSurface> VulkanSurface::GetSkiaSurface() const {
return valid_ ? sk_surface_ : nullptr;
}
bool VulkanSurface::BindToImage(sk_sp<GrContext> context,
VulkanImage vulkan_image) {
FML_DCHECK(vulkan_image.vk_memory_requirements.size <=
vk_memory_info_.allocationSize);
vulkan_image_ = std::move(vulkan_image);
// Bind image memory.
if (VK_CALL_LOG_ERROR(vulkan_provider_.vk().BindImageMemory(
vulkan_provider_.vk_device(), vulkan_image_.vk_image, vk_memory_,
0)) != VK_SUCCESS) {
valid_ = false;
return false;
}
const auto& extent = vulkan_image.vk_image_create_info.extent;
auto size = SkISize::Make(extent.width, extent.height);
if (!SetupSkiaSurface(std::move(context), size, kSkiaColorType,
vulkan_image.vk_image_create_info,
vulkan_image.vk_memory_requirements)) {
FML_DLOG(ERROR) << "Failed to setup skia surface";
valid_ = false;
return false;
}
if (sk_surface_ == nullptr) {
valid_ = false;
return false;
}
if (!PushSessionImageSetupOps(session_)) {
FML_DLOG(ERROR) << "Could not push session image setup ops.";
valid_ = false;
return false;
}
return true;
}
size_t VulkanSurface::AdvanceAndGetAge() {
size_history_[size_history_index_] = GetSize();
size_history_index_ = (size_history_index_ + 1) % kSizeHistorySize;
age_++;
return age_;
}
bool VulkanSurface::FlushSessionAcquireAndReleaseEvents() {
zx::event acquire, release;
if (acquire_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &acquire) != ZX_OK ||
release_event_.duplicate(ZX_RIGHT_SAME_RIGHTS, &release) != ZX_OK) {
return false;
}
session_->EnqueueAcquireFence(std::move(acquire));
session_->EnqueueReleaseFence(std::move(release));
age_ = 0;
return true;
}
void VulkanSurface::SignalWritesFinished(
std::function<void(void)> on_writes_committed) {
FML_DCHECK(on_writes_committed);
if (!valid_) {
on_writes_committed();
return;
}
dart_utils::Check(pending_on_writes_committed_ == nullptr,
"Attempted to signal a write on the surface when the "
"previous write has not yet been acknowledged by the "
"compositor.");
pending_on_writes_committed_ = on_writes_committed;
}
void VulkanSurface::Reset() {
if (acquire_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK ||
release_event_.signal(ZX_EVENT_SIGNALED, 0u) != ZX_OK) {
valid_ = false;
FML_DLOG(ERROR)
<< "Could not reset fences. The surface is no longer valid.";
}
VkFence fence = command_buffer_fence_;
if (command_buffer_) {
VK_CALL_LOG_ERROR(vulkan_provider_.vk().WaitForFences(
vulkan_provider_.vk_device(), 1, &fence, VK_TRUE, UINT64_MAX));
command_buffer_.reset();
}
VK_CALL_LOG_ERROR(vulkan_provider_.vk().ResetFences(
vulkan_provider_.vk_device(), 1, &fence));
// Need to make a new acquire semaphore every frame or else validation layers
// get confused about why no one is waiting on it in this VkInstance
acquire_semaphore_.Reset();
acquire_semaphore_ = SemaphoreFromEvent(acquire_event_);
if (!acquire_semaphore_) {
FML_DLOG(ERROR) << "failed to create acquire semaphore";
}
wait_.Begin(async_get_default_dispatcher());
// It is safe for the caller to collect the surface in the callback.
auto callback = pending_on_writes_committed_;
pending_on_writes_committed_ = nullptr;
if (callback) {
callback();
}
}
void VulkanSurface::OnHandleReady(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal_t* signal) {
if (status != ZX_OK)
return;
FML_DCHECK(signal->observed & ZX_EVENT_SIGNALED);
Reset();
}
} // namespace flutter_runner

View File

@@ -0,0 +1,211 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <lib/async/cpp/wait.h>
#include <lib/zx/event.h>
#include <lib/zx/vmo.h>
#include <array>
#include <memory>
#include "flutter/flow/raster_cache_key.h"
#include "flutter/flow/scene_update_context.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/vulkan_command_buffer.h"
#include "flutter/vulkan/vulkan_handle.h"
#include "flutter/vulkan/vulkan_proc_table.h"
#include "flutter/vulkan/vulkan_provider.h"
#include "lib/ui/scenic/cpp/resources.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter_runner {
// A |VkImage| and its relevant metadata.
struct VulkanImage {
VulkanImage() = default;
VulkanImage(VulkanImage&&) = default;
VulkanImage& operator=(VulkanImage&&) = default;
VkImageCreateInfo vk_image_create_info;
VkMemoryRequirements vk_memory_requirements;
vulkan::VulkanHandle<VkImage> vk_image;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanImage);
};
// Create a new |VulkanImage| of size |size|, stored in
// |out_vulkan_image|. Returns whether creation of the |VkImage| was
// successful.
bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider,
const SkISize& size,
VulkanImage* out_vulkan_image);
class VulkanSurface final
: public flutter::SceneUpdateContext::SurfaceProducerSurface {
public:
VulkanSurface(vulkan::VulkanProvider& vulkan_provider,
sk_sp<GrContext> context,
scenic::Session* session,
const SkISize& size);
~VulkanSurface() override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
size_t AdvanceAndGetAge() override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
bool FlushSessionAcquireAndReleaseEvents() override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
bool IsValid() const override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
SkISize GetSize() const override;
// Note: It is safe for the caller to collect the surface in the
// |on_writes_committed| callback.
void SignalWritesFinished(
std::function<void(void)> on_writes_committed) override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
scenic::Image* GetImage() override;
// |flutter::SceneUpdateContext::SurfaceProducerSurface|
sk_sp<SkSurface> GetSkiaSurface() const override;
const vulkan::VulkanHandle<VkImage>& GetVkImage() {
return vulkan_image_.vk_image;
}
const vulkan::VulkanHandle<VkSemaphore>& GetAcquireVkSemaphore() {
return acquire_semaphore_;
}
vulkan::VulkanCommandBuffer* GetCommandBuffer(
const vulkan::VulkanHandle<VkCommandPool>& pool) {
if (!command_buffer_)
command_buffer_ = std::make_unique<vulkan::VulkanCommandBuffer>(
vulkan_provider_.vk(), vulkan_provider_.vk_device(), pool);
return command_buffer_.get();
}
const vulkan::VulkanHandle<VkFence>& GetCommandBufferFence() {
return command_buffer_fence_;
}
size_t GetAllocationSize() const { return vk_memory_info_.allocationSize; }
size_t GetImageMemoryRequirementsSize() const {
return vulkan_image_.vk_memory_requirements.size;
}
bool IsOversized() const {
return GetAllocationSize() > GetImageMemoryRequirementsSize();
}
bool HasStableSizeHistory() const {
return std::equal(size_history_.begin() + 1, size_history_.end(),
size_history_.begin());
}
// Bind |vulkan_image| to |vk_memory_| and create a new skia surface,
// replacing the previous |vk_image_|. |vulkan_image| MUST require less
// than or equal the amount of memory contained in |vk_memory_|. Returns
// whether the swap was successful. The |VulkanSurface| will become invalid
// if the swap was not successful.
bool BindToImage(sk_sp<GrContext> context, VulkanImage vulkan_image);
// Flutter may retain a |VulkanSurface| for a |flutter::Layer| subtree to
// improve the performance. The |retained_key_| identifies which layer subtree
// this |VulkanSurface| is retained for. The key has two parts. One is the
// pointer to the root of that layer subtree: |retained_key_.id()|. Another is
// the transformation matrix: |retained_key_.matrix()|. We need the matrix
// part because a different matrix would invalidate the pixels (raster cache)
// in this |VulkanSurface|.
const flutter::LayerRasterCacheKey& GetRetainedKey() const {
return retained_key_;
}
// For better safety in retained rendering, Flutter uses a retained
// |EntityNode| associated with the retained surface instead of using the
// retained surface directly. Hence Flutter can't modify the surface during
// retained rendering.
const scenic::EntityNode& GetRetainedNode() {
used_in_retained_rendering_ = true;
return *retained_node_;
}
// Check whether the retained surface (and its associated |EntityNode|) is
// used in the current frame or not. If unused, the |VulkanSurfacePool| will
// try to recycle the surface. This flag is reset after each frame.
bool IsUsedInRetainedRendering() const { return used_in_retained_rendering_; }
void ResetIsUsedInRetainedRendering() { used_in_retained_rendering_ = false; }
// Let this surface own the retained EntityNode associated with it (see
// |GetRetainedNode|), and set the retained key (see |GetRetainedKey|).
void SetRetainedInfo(const flutter::LayerRasterCacheKey& key,
std::unique_ptr<scenic::EntityNode> node) {
retained_key_ = key;
retained_node_ = std::move(node);
}
private:
static constexpr int kSizeHistorySize = 4;
void OnHandleReady(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal_t* signal);
bool AllocateDeviceMemory(sk_sp<GrContext> context,
const SkISize& size,
zx::vmo& exported_vmo);
bool SetupSkiaSurface(sk_sp<GrContext> context,
const SkISize& size,
SkColorType color_type,
const VkImageCreateInfo& image_create_info,
const VkMemoryRequirements& memory_reqs);
bool CreateFences();
bool PushSessionImageSetupOps(scenic::Session* session);
void Reset();
vulkan::VulkanHandle<VkSemaphore> SemaphoreFromEvent(
const zx::event& event) const;
vulkan::VulkanProvider& vulkan_provider_;
scenic::Session* session_;
VulkanImage vulkan_image_;
vulkan::VulkanHandle<VkDeviceMemory> vk_memory_;
VkMemoryAllocateInfo vk_memory_info_;
vulkan::VulkanHandle<VkFence> command_buffer_fence_;
sk_sp<SkSurface> sk_surface_;
// TODO: Don't heap allocate this once SCN-268 is resolved.
std::unique_ptr<scenic::Memory> scenic_memory_;
std::unique_ptr<scenic::Image> session_image_;
zx::event acquire_event_;
vulkan::VulkanHandle<VkSemaphore> acquire_semaphore_;
std::unique_ptr<vulkan::VulkanCommandBuffer> command_buffer_;
zx::event release_event_;
async::WaitMethod<VulkanSurface, &VulkanSurface::OnHandleReady> wait_;
std::function<void()> pending_on_writes_committed_;
std::array<SkISize, kSizeHistorySize> size_history_;
int size_history_index_ = 0;
size_t age_ = 0;
bool valid_ = false;
flutter::LayerRasterCacheKey retained_key_ = {0, SkMatrix::MakeScale(1, 1)};
std::unique_ptr<scenic::EntityNode> retained_node_ = nullptr;
std::atomic<bool> used_in_retained_rendering_ = {false};
FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface);
};
} // namespace flutter_runner

View File

@@ -0,0 +1,333 @@
// Copyright 2013 The Flutter 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 "vulkan_surface_pool.h"
#include <algorithm>
#include <string>
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace flutter_runner {
namespace {
std::string ToString(const SkISize& size) {
return "{width: " + std::to_string(size.width()) +
", height: " + std::to_string(size.height()) + "}";
}
} // namespace
VulkanSurfacePool::VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider,
sk_sp<GrContext> context,
scenic::Session* scenic_session)
: vulkan_provider_(vulkan_provider),
context_(std::move(context)),
scenic_session_(scenic_session) {}
VulkanSurfacePool::~VulkanSurfacePool() {}
std::unique_ptr<VulkanSurface> VulkanSurfacePool::AcquireSurface(
const SkISize& size) {
auto surface = GetCachedOrCreateSurface(size);
if (surface == nullptr) {
FML_DLOG(ERROR) << "Could not acquire surface";
return nullptr;
}
if (!surface->FlushSessionAcquireAndReleaseEvents()) {
FML_DLOG(ERROR) << "Could not flush acquire/release events for buffer.";
return nullptr;
}
return surface;
}
std::unique_ptr<VulkanSurface> VulkanSurfacePool::GetCachedOrCreateSurface(
const SkISize& size) {
// First try to find a surface that exactly matches |size|.
{
auto exact_match_it =
std::find_if(available_surfaces_.begin(), available_surfaces_.end(),
[&size](const auto& surface) {
return surface->IsValid() && surface->GetSize() == size;
});
if (exact_match_it != available_surfaces_.end()) {
auto acquired_surface = std::move(*exact_match_it);
available_surfaces_.erase(exact_match_it);
return acquired_surface;
}
}
// Then, look for a surface that has enough |VkDeviceMemory| to hold a
// |VkImage| of size |size|, but is currently holding a |VkImage| of a
// different size.
VulkanImage vulkan_image;
if (!CreateVulkanImage(vulkan_provider_, size, &vulkan_image)) {
FML_DLOG(ERROR) << "Failed to create a VkImage of size: " << ToString(size);
return nullptr;
}
auto best_it = available_surfaces_.end();
for (auto it = available_surfaces_.begin(); it != available_surfaces_.end();
++it) {
const auto& surface = *it;
if (!surface->IsValid() || surface->GetAllocationSize() <
vulkan_image.vk_memory_requirements.size) {
continue;
}
if (best_it == available_surfaces_.end() ||
surface->GetAllocationSize() < (*best_it)->GetAllocationSize()) {
best_it = it;
}
}
// If no such surface exists, then create a new one.
if (best_it == available_surfaces_.end()) {
return CreateSurface(size);
}
auto acquired_surface = std::move(*best_it);
available_surfaces_.erase(best_it);
bool swap_succeeded =
acquired_surface->BindToImage(context_, std::move(vulkan_image));
if (!swap_succeeded) {
FML_DLOG(ERROR) << "Failed to swap VulkanSurface to new VkImage of size: "
<< ToString(size);
return CreateSurface(size);
}
FML_DCHECK(acquired_surface->IsValid());
trace_surfaces_reused_++;
return acquired_surface;
}
void VulkanSurfacePool::SubmitSurface(
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
p_surface) {
TRACE_EVENT0("flutter", "VulkanSurfacePool::SubmitSurface");
// This cast is safe because |VulkanSurface| is the only implementation of
// |SurfaceProducerSurface| for Flutter on Fuchsia. Additionally, it is
// required, because we need to access |VulkanSurface| specific information
// of the surface (such as the amount of VkDeviceMemory it contains).
auto vulkan_surface = std::unique_ptr<VulkanSurface>(
static_cast<VulkanSurface*>(p_surface.release()));
if (!vulkan_surface) {
return;
}
const flutter::LayerRasterCacheKey& retained_key =
vulkan_surface->GetRetainedKey();
if (retained_key.id() != 0) {
// Add the surface to |retained_surfaces_| if its retained key has a valid
// layer id (|retained_key.id()|).
//
// We have to add the entry to |retained_surfaces_| map early when it's
// still pending (|is_pending| = true). Otherwise (if we add the surface
// later when |SignalRetainedReady| is called), Flutter would fail to find
// the retained node before the painting is done (which could take multiple
// frames). Flutter would then create a new |VulkanSurface| for the layer
// upon the failed lookup. The new |VulkanSurface| would invalidate this
// surface, and before the new |VulkanSurface| is done painting, another
// newer |VulkanSurface| is likely to be created to replace the new
// |VulkanSurface|. That would make the retained rendering much less useful
// in improving the performance.
auto insert_iterator = retained_surfaces_.insert(std::make_pair(
retained_key, RetainedSurface({true, std::move(vulkan_surface)})));
if (insert_iterator.second) {
insert_iterator.first->second.vk_surface->SignalWritesFinished(std::bind(
&VulkanSurfacePool::SignalRetainedReady, this, retained_key));
}
} else {
uintptr_t surface_key = reinterpret_cast<uintptr_t>(vulkan_surface.get());
auto insert_iterator = pending_surfaces_.insert(std::make_pair(
surface_key, // key
std::move(vulkan_surface) // value
));
if (insert_iterator.second) {
insert_iterator.first->second->SignalWritesFinished(std::bind(
&VulkanSurfacePool::RecyclePendingSurface, this, surface_key));
}
}
}
std::unique_ptr<VulkanSurface> VulkanSurfacePool::CreateSurface(
const SkISize& size) {
TRACE_EVENT0("flutter", "VulkanSurfacePool::CreateSurface");
auto surface = std::make_unique<VulkanSurface>(vulkan_provider_, context_,
scenic_session_, size);
if (!surface->IsValid()) {
return nullptr;
}
trace_surfaces_created_++;
return surface;
}
void VulkanSurfacePool::RecyclePendingSurface(uintptr_t surface_key) {
// Before we do anything, we must clear the surface from the collection of
// pending surfaces.
auto found_in_pending = pending_surfaces_.find(surface_key);
if (found_in_pending == pending_surfaces_.end()) {
return;
}
// Grab a hold of the surface to recycle and clear the entry in the pending
// surfaces collection.
auto surface_to_recycle = std::move(found_in_pending->second);
pending_surfaces_.erase(found_in_pending);
RecycleSurface(std::move(surface_to_recycle));
}
void VulkanSurfacePool::RecycleSurface(std::unique_ptr<VulkanSurface> surface) {
// The surface may have become invalid (for example it the fences could
// not be reset).
if (!surface->IsValid()) {
return;
}
// Recycle the buffer by putting it in the list of available surfaces if we
// have not reached the maximum amount of cached surfaces.
if (available_surfaces_.size() < kMaxSurfaces) {
available_surfaces_.push_back(std::move(surface));
}
}
void VulkanSurfacePool::RecycleRetainedSurface(
const flutter::LayerRasterCacheKey& key) {
auto it = retained_surfaces_.find(key);
if (it == retained_surfaces_.end()) {
return;
}
// The surface should not be pending.
FML_DCHECK(!it->second.is_pending);
auto surface_to_recycle = std::move(it->second.vk_surface);
retained_surfaces_.erase(it);
RecycleSurface(std::move(surface_to_recycle));
}
void VulkanSurfacePool::SignalRetainedReady(flutter::LayerRasterCacheKey key) {
retained_surfaces_[key].is_pending = false;
}
void VulkanSurfacePool::AgeAndCollectOldBuffers() {
TRACE_EVENT0("flutter", "VulkanSurfacePool::AgeAndCollectOldBuffers");
// Remove all surfaces that are no longer valid or are too old.
available_surfaces_.erase(
std::remove_if(available_surfaces_.begin(), available_surfaces_.end(),
[&](auto& surface) {
return !surface->IsValid() ||
surface->AdvanceAndGetAge() >= kMaxSurfaceAge;
}),
available_surfaces_.end());
// Look for a surface that has both a larger |VkDeviceMemory| allocation
// than is necessary for its |VkImage|, and has a stable size history.
auto surface_to_remove_it = std::find_if(
available_surfaces_.begin(), available_surfaces_.end(),
[](const auto& surface) {
return surface->IsOversized() && surface->HasStableSizeHistory();
});
// If we found such a surface, then destroy it and cache a new one that only
// uses a necessary amount of memory.
if (surface_to_remove_it != available_surfaces_.end()) {
auto size = (*surface_to_remove_it)->GetSize();
available_surfaces_.erase(surface_to_remove_it);
auto new_surface = CreateSurface(size);
if (new_surface != nullptr) {
available_surfaces_.push_back(std::move(new_surface));
} else {
FML_DLOG(ERROR) << "Failed to create a new shrunk surface";
}
}
// Recycle retained surfaces that are not used and not pending in this frame.
//
// It's safe to recycle any retained surfaces that are not pending no matter
// whether they're used or not. Hence if there's memory pressure, feel free to
// recycle all retained surfaces that are not pending.
std::vector<flutter::LayerRasterCacheKey> recycle_keys;
for (auto& [key, retained_surface] : retained_surfaces_) {
if (retained_surface.is_pending ||
retained_surface.vk_surface->IsUsedInRetainedRendering()) {
// Reset the flag for the next frame
retained_surface.vk_surface->ResetIsUsedInRetainedRendering();
} else {
recycle_keys.push_back(key);
}
}
for (auto& key : recycle_keys) {
RecycleRetainedSurface(key);
}
TraceStats();
}
void VulkanSurfacePool::ShrinkToFit() {
// Reset all oversized surfaces in |available_surfaces_| so that the old
// surfaces and new surfaces don't exist at the same time at any point,
// reducing our peak memory footprint.
std::vector<SkISize> sizes_to_recreate;
for (auto& surface : available_surfaces_) {
if (surface->IsOversized()) {
sizes_to_recreate.push_back(surface->GetSize());
surface.reset();
}
}
available_surfaces_.erase(std::remove(available_surfaces_.begin(),
available_surfaces_.end(), nullptr),
available_surfaces_.end());
for (const auto& size : sizes_to_recreate) {
auto surface = CreateSurface(size);
if (surface != nullptr) {
available_surfaces_.push_back(std::move(surface));
} else {
FML_DLOG(ERROR) << "Failed to create resized surface";
}
}
TraceStats();
}
void VulkanSurfacePool::TraceStats() {
// Resources held in cached buffers.
size_t cached_surfaces = 0;
size_t cached_surfaces_bytes = 0;
for (const auto& surface : available_surfaces_) {
cached_surfaces++;
cached_surfaces_bytes += surface->GetAllocationSize();
}
// Resources held by Skia.
int skia_resources = 0;
size_t skia_bytes = 0;
context_->getResourceCacheUsage(&skia_resources, &skia_bytes);
const size_t skia_cache_purgeable =
context_->getResourceCachePurgeableBytes();
FML_TRACE_COUNTER("flutter", "SurfacePool", 0u, //
"CachedCount", cached_surfaces, //
"CachedBytes", cached_surfaces_bytes, //
"Created", trace_surfaces_created_, //
"Reused", trace_surfaces_reused_, //
"PendingInCompositor", pending_surfaces_.size(), //
"Retained", retained_surfaces_.size(), //
"SkiaCacheResources", skia_resources, //
"SkiaCacheBytes", skia_bytes, //
"SkiaCachePurgeable", skia_cache_purgeable //
);
// Reset per present/frame stats.
trace_surfaces_created_ = 0;
trace_surfaces_reused_ = 0;
}
} // namespace flutter_runner

View File

@@ -0,0 +1,95 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <unordered_map>
#include <vector>
#include "flutter/fml/macros.h"
#include "vulkan_surface.h"
namespace flutter_runner {
class VulkanSurfacePool final {
public:
// Only keep 12 surfaces at a time. This value was based on how many
// surfaces got cached in the old, exact-match-only caching logic.
static constexpr int kMaxSurfaces = 12;
// If a surface doesn't get used for 3 or more generations, we discard it.
static constexpr int kMaxSurfaceAge = 3;
VulkanSurfacePool(vulkan::VulkanProvider& vulkan_provider,
sk_sp<GrContext> context,
scenic::Session* scenic_session);
~VulkanSurfacePool();
std::unique_ptr<VulkanSurface> AcquireSurface(const SkISize& size);
void SubmitSurface(
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
surface);
void AgeAndCollectOldBuffers();
// Shrink all oversized |VulkanSurfaces| in |available_surfaces_| to as
// small as they can be.
void ShrinkToFit();
// For |VulkanSurfaceProducer::HasRetainedNode|.
bool HasRetainedNode(const flutter::LayerRasterCacheKey& key) const {
return retained_surfaces_.find(key) != retained_surfaces_.end();
}
// For |VulkanSurfaceProducer::GetRetainedNode|.
const scenic::EntityNode& GetRetainedNode(
const flutter::LayerRasterCacheKey& key) {
FML_DCHECK(HasRetainedNode(key));
return retained_surfaces_[key].vk_surface->GetRetainedNode();
}
private:
// Struct for retained_surfaces_ map.
struct RetainedSurface {
// If |is_pending| is true, the |vk_surface| is still under painting
// (similar to those in |pending_surfaces_|) so we can't recycle the
// |vk_surface| yet.
bool is_pending;
std::unique_ptr<VulkanSurface> vk_surface;
};
vulkan::VulkanProvider& vulkan_provider_;
sk_sp<GrContext> context_;
scenic::Session* scenic_session_;
std::vector<std::unique_ptr<VulkanSurface>> available_surfaces_;
std::unordered_map<uintptr_t, std::unique_ptr<VulkanSurface>>
pending_surfaces_;
// Retained surfaces keyed by the layer that created and used the surface.
flutter::LayerRasterCacheKey::Map<RetainedSurface> retained_surfaces_;
size_t trace_surfaces_created_ = 0;
size_t trace_surfaces_reused_ = 0;
std::unique_ptr<VulkanSurface> GetCachedOrCreateSurface(const SkISize& size);
std::unique_ptr<VulkanSurface> CreateSurface(const SkISize& size);
void RecycleSurface(std::unique_ptr<VulkanSurface> surface);
void RecyclePendingSurface(uintptr_t surface_key);
// Clear the |is_pending| flag of the retained surface.
void SignalRetainedReady(flutter::LayerRasterCacheKey key);
// Remove the corresponding surface from |retained_surfaces| and recycle it.
// The surface must not be pending.
void RecycleRetainedSurface(const flutter::LayerRasterCacheKey& key);
void TraceStats();
FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurfacePool);
};
} // namespace flutter_runner

View File

@@ -0,0 +1,246 @@
// Copyright 2013 The Flutter 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 "vulkan_surface_producer.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <memory>
#include <string>
#include <vector>
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/gpu/GrBackendSemaphore.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h"
#include "third_party/skia/include/gpu/vk/GrVkTypes.h"
namespace flutter_runner {
namespace {
// TODO: Properly tune these values. See FL-153.
constexpr int kGrCacheMaxCount = 8192;
constexpr size_t kGrCacheMaxByteSize = 8 * (1 << 20);
} // namespace
VulkanSurfaceProducer::VulkanSurfaceProducer(scenic::Session* scenic_session) {
valid_ = Initialize(scenic_session);
if (valid_) {
FML_DLOG(INFO)
<< "Flutter engine: Vulkan surface producer initialization: Successful";
} else {
FML_LOG(ERROR)
<< "Flutter engine: Vulkan surface producer initialization: Failed";
}
}
VulkanSurfaceProducer::~VulkanSurfaceProducer() {
// Make sure queue is idle before we start destroying surfaces
if (valid_) {
VkResult wait_result = VK_CALL_LOG_ERROR(
vk_->QueueWaitIdle(logical_device_->GetQueueHandle()));
FML_DCHECK(wait_result == VK_SUCCESS);
}
};
bool VulkanSurfaceProducer::Initialize(scenic::Session* scenic_session) {
vk_ = fml::MakeRefCounted<vulkan::VulkanProcTable>();
std::vector<std::string> extensions = {
VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
};
application_ = std::make_unique<vulkan::VulkanApplication>(
*vk_, "FlutterRunner", std::move(extensions), VK_MAKE_VERSION(1, 0, 0),
VK_MAKE_VERSION(1, 1, 0));
if (!application_->IsValid() || !vk_->AreInstanceProcsSetup()) {
// Make certain the application instance was created and it setup the
// instance proc table entries.
FML_LOG(ERROR) << "Instance proc addresses have not been setup.";
return false;
}
// Create the device.
logical_device_ = application_->AcquireFirstCompatibleLogicalDevice();
if (logical_device_ == nullptr || !logical_device_->IsValid() ||
!vk_->AreDeviceProcsSetup()) {
// Make certain the device was created and it setup the device proc table
// entries.
FML_LOG(ERROR) << "Device proc addresses have not been setup.";
return false;
}
if (!vk_->HasAcquiredMandatoryProcAddresses()) {
FML_LOG(ERROR) << "Failed to acquire mandatory proc addresses.";
return false;
}
if (!vk_->IsValid()) {
FML_LOG(ERROR) << "VulkanProcTable invalid";
return false;
}
auto getProc = vk_->CreateSkiaGetProc();
if (getProc == nullptr) {
FML_LOG(ERROR) << "Failed to create skia getProc.";
return false;
}
uint32_t skia_features = 0;
if (!logical_device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) {
FML_LOG(ERROR) << "Failed to get physical device features.";
return false;
}
GrVkBackendContext backend_context;
backend_context.fInstance = application_->GetInstance();
backend_context.fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle();
backend_context.fDevice = logical_device_->GetHandle();
backend_context.fQueue = logical_device_->GetQueueHandle();
backend_context.fGraphicsQueueIndex =
logical_device_->GetGraphicsQueueIndex();
backend_context.fMinAPIVersion = application_->GetAPIVersion();
backend_context.fFeatures = skia_features;
backend_context.fGetProc = std::move(getProc);
backend_context.fOwnsInstanceAndDevice = false;
context_ = GrContext::MakeVulkan(backend_context);
// Use local limits specified in this file above instead of flutter defaults.
context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize);
surface_pool_ =
std::make_unique<VulkanSurfacePool>(*this, context_, scenic_session);
return true;
}
void VulkanSurfaceProducer::OnSurfacesPresented(
std::vector<
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>>
surfaces) {
TRACE_EVENT0("flutter", "VulkanSurfaceProducer::OnSurfacesPresented");
// Do a single flush for all canvases derived from the context.
{
TRACE_EVENT0("flutter", "GrContext::flushAndSignalSemaphores");
context_->flush();
}
if (!TransitionSurfacesToExternal(surfaces))
FML_LOG(ERROR) << "TransitionSurfacesToExternal failed";
// Submit surface
for (auto& surface : surfaces) {
SubmitSurface(std::move(surface));
}
// Buffer management.
surface_pool_->AgeAndCollectOldBuffers();
// If no further surface production has taken place for 10 frames (TODO:
// Don't hardcode refresh rate here), then shrink our surface pool to fit.
constexpr auto kShouldShrinkThreshold = zx::msec(10 * 16.67);
async::PostDelayedTask(
async_get_default_dispatcher(),
[self = weak_factory_.GetWeakPtr(), kShouldShrinkThreshold] {
if (!self) {
return;
}
auto time_since_last_produce =
async::Now(async_get_default_dispatcher()) -
self->last_produce_time_;
if (time_since_last_produce >= kShouldShrinkThreshold) {
self->surface_pool_->ShrinkToFit();
}
},
kShouldShrinkThreshold);
}
bool VulkanSurfaceProducer::TransitionSurfacesToExternal(
const std::vector<
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>>&
surfaces) {
for (auto& surface : surfaces) {
auto vk_surface = static_cast<VulkanSurface*>(surface.get());
vulkan::VulkanCommandBuffer* command_buffer =
vk_surface->GetCommandBuffer(logical_device_->GetCommandPool());
if (!command_buffer->Begin())
return false;
GrBackendRenderTarget backendRT =
vk_surface->GetSkiaSurface()->getBackendRenderTarget(
SkSurface::kFlushRead_BackendHandleAccess);
if (!backendRT.isValid()) {
return false;
}
GrVkImageInfo imageInfo;
if (!backendRT.getVkImageInfo(&imageInfo)) {
return false;
}
VkImageMemoryBarrier image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = nullptr,
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
.dstAccessMask = 0,
.oldLayout = imageInfo.fImageLayout,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = 0,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL_KHR,
.image = vk_surface->GetVkImage(),
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
if (!command_buffer->InsertPipelineBarrier(
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, // dependencyFlags
0, nullptr, // memory barriers
0, nullptr, // buffer barriers
1, &image_barrier))
return false;
backendRT.setVkImageLayout(image_barrier.newLayout);
if (!command_buffer->End())
return false;
if (!logical_device_->QueueSubmit(
{}, {}, {vk_surface->GetAcquireVkSemaphore()},
{command_buffer->Handle()}, vk_surface->GetCommandBufferFence()))
return false;
}
return true;
}
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
VulkanSurfaceProducer::ProduceSurface(
const SkISize& size,
const flutter::LayerRasterCacheKey& layer_key,
std::unique_ptr<scenic::EntityNode> entity_node) {
FML_DCHECK(valid_);
last_produce_time_ = async::Now(async_get_default_dispatcher());
auto surface = surface_pool_->AcquireSurface(size);
surface->SetRetainedInfo(layer_key, std::move(entity_node));
return surface;
}
void VulkanSurfaceProducer::SubmitSurface(
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
surface) {
FML_DCHECK(valid_ && surface != nullptr);
surface_pool_->SubmitSurface(std::move(surface));
}
} // namespace flutter_runner

View File

@@ -0,0 +1,103 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <lib/async/cpp/time.h>
#include <lib/async/default.h>
#include <lib/syslog/global.h>
#include "flutter/flow/scene_update_context.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/vulkan_application.h"
#include "flutter/vulkan/vulkan_device.h"
#include "flutter/vulkan/vulkan_proc_table.h"
#include "flutter/vulkan/vulkan_provider.h"
#include "lib/ui/scenic/cpp/resources.h"
#include "lib/ui/scenic/cpp/session.h"
#include "logging.h"
#include "vulkan_surface.h"
#include "vulkan_surface_pool.h"
namespace flutter_runner {
class VulkanSurfaceProducer final
: public flutter::SceneUpdateContext::SurfaceProducer,
public vulkan::VulkanProvider {
public:
VulkanSurfaceProducer(scenic::Session* scenic_session);
~VulkanSurfaceProducer();
bool IsValid() const { return valid_; }
// |flutter::SceneUpdateContext::SurfaceProducer|
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
ProduceSurface(const SkISize& size,
const flutter::LayerRasterCacheKey& layer_key,
std::unique_ptr<scenic::EntityNode> entity_node) override;
// |flutter::SceneUpdateContext::SurfaceProducer|
void SubmitSurface(
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>
surface) override;
// |flutter::SceneUpdateContext::HasRetainedNode|
bool HasRetainedNode(const flutter::LayerRasterCacheKey& key) const override {
return surface_pool_->HasRetainedNode(key);
}
// |flutter::SceneUpdateContext::GetRetainedNode|
const scenic::EntityNode& GetRetainedNode(
const flutter::LayerRasterCacheKey& key) override {
return surface_pool_->GetRetainedNode(key);
}
void OnSurfacesPresented(
std::vector<
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>>
surfaces);
void OnSessionSizeChangeHint(float width_change_factor,
float height_change_factor) {
FX_LOGF(INFO, LOG_TAG,
"VulkanSurfaceProducer:OnSessionSizeChangeHint %f, %f",
width_change_factor, height_change_factor);
}
private:
// VulkanProvider
const vulkan::VulkanProcTable& vk() override { return *vk_.get(); }
const vulkan::VulkanHandle<VkDevice>& vk_device() override {
return logical_device_->GetHandle();
}
bool TransitionSurfacesToExternal(
const std::vector<
std::unique_ptr<flutter::SceneUpdateContext::SurfaceProducerSurface>>&
surfaces);
// Note: the order here is very important. The proctable must be destroyed
// last because it contains the function pointers for VkDestroyDevice and
// VkDestroyInstance.
fml::RefPtr<vulkan::VulkanProcTable> vk_;
std::unique_ptr<vulkan::VulkanApplication> application_;
std::unique_ptr<vulkan::VulkanDevice> logical_device_;
sk_sp<GrContext> context_;
std::unique_ptr<VulkanSurfacePool> surface_pool_;
bool valid_ = false;
// Keep track of the last time we produced a surface. This is used to
// determine whether it is safe to shrink |surface_pool_| or not.
zx::time last_produce_time_ = async::Now(async_get_default_dispatcher());
fml::WeakPtrFactory<VulkanSurfaceProducer> weak_factory_{this};
bool Initialize(scenic::Session* scenic_session);
// Disallow copy and assignment.
VulkanSurfaceProducer(const VulkanSurfaceProducer&) = delete;
VulkanSurfaceProducer& operator=(const VulkanSurfaceProducer&) = delete;
};
} // namespace flutter_runner