Move shell to //flutter and split shell/BUILD.gn into smaller pieces for each subcomponent. (flutter/engine#3053)

* Namespaces have been updated to reflect the move from //flutter/sky/shell to //flutter/shell.
* shell/BUILD.gn file has been split into smaller GN files for each subcomponent of the shell (common, GPU, diagnostic, testing).
* GN dependencies have been rewritten to stop exposing common shell dependencies as public. Duplicates have also been removed.
* GPU subcomponent has been updated make it more suitable for Vulkan integration.
* The GLFW backend has been resurrected.
This commit is contained in:
Chinmay Garde
2016-09-23 15:33:25 -07:00
committed by GitHub
parent 722a87a076
commit b2e97acdb8
126 changed files with 11844 additions and 3 deletions

2
DEPS
View File

@@ -45,7 +45,7 @@ allowed_hosts = [
]
deps = {
'src': 'https://github.com/flutter/buildroot.git' + '@' + '7b77c0acedf708749b68304cc5f0ac469c9d7136',
'src': 'https://github.com/flutter/buildroot.git' + '@' + '1c9494e60378bd119d910d530344077fc091b3a5',
# Fuchsia compatibility
#

View File

@@ -24,7 +24,6 @@ group("flutter") {
if (is_ios) {
deps += [
"//flutter/services/dynamic:sdk_lib_archive",
"//flutter/sky/shell:flutter_framework",
]
}
}

View File

@@ -0,0 +1,7 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
group("shell") {
deps = [ "platform" ]
}

View File

@@ -0,0 +1,70 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//mojo/dart/embedder/embedder.gni")
dart_embedder_resources("generate_embedder_diagnostic_server_resources_cc") {
inputs = [
"//flutter/shell/common/diagnostic/diagnostic_server.dart"
]
root_prefix = "//flutter/shell/common/diagnostic/"
output = "$target_gen_dir/embedder_diagnostic_server_resources.cc"
table_name = "sky_embedder_diagnostic_server"
}
source_set("common") {
sources = [
"$target_gen_dir/embedder_diagnostic_server_resources.cc",
"animator.cc",
"animator.h",
"diagnostic/diagnostic_server.cc",
"diagnostic/diagnostic_server.h",
"engine.cc",
"engine.h",
"picture_serializer.cc",
"picture_serializer.h",
"platform_view.cc",
"platform_view.h",
"platform_view_service_protocol.cc",
"platform_view_service_protocol.h",
"rasterizer.cc",
"rasterizer.h",
"shell.cc",
"shell.h",
"switches.cc",
"switches.h",
"systrace_logger.cc",
"systrace_logger.h",
"tracing_controller.cc",
"tracing_controller.h",
"ui_delegate.cc",
"ui_delegate.h",
]
deps = [
"//base",
"//base:i18n",
"//dart/runtime/vm:libdart_platform",
"//dart/runtime:libdart",
"//flutter/assets",
"//flutter/common",
"//flutter/flow",
"//flutter/glue",
"//flutter/lib/ui",
"//flutter/runtime",
"//flutter/services/engine:interfaces",
"//flutter/services/vsync",
"//flutter/skia",
"//flutter/sky/engine/wtf",
"//flutter/synchronization",
"//lib/ftl",
"//lib/tonic",
"//mojo/application",
"//mojo/message_pump",
"//mojo/public/cpp/bindings:utility",
"//mojo/public/interfaces/application",
"//mojo/services/vsync/interfaces",
":generate_embedder_diagnostic_server_resources_cc",
]
}

View File

@@ -0,0 +1,145 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/animator.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/trace_event/trace_event.h"
#include "flutter/common/threads.h"
#include "lib/ftl/time/stopwatch.h"
namespace shell {
Animator::Animator(Rasterizer* rasterizer, Engine* engine)
: rasterizer_(rasterizer->GetWeakRasterizerPtr()),
engine_(engine),
layer_tree_pipeline_(ftl::MakeRefCounted<LayerTreePipeline>(3)),
pending_frame_semaphore_(1),
paused_(false),
weak_factory_(this) {
new sky::services::vsync::VsyncProviderFallbackImpl(
mojo::InterfaceRequest<::vsync::VSyncProvider>(
mojo::GetProxy(&fallback_vsync_provider_)));
}
Animator::~Animator() = default;
void Animator::Stop() {
paused_ = true;
}
void Animator::Start() {
if (!paused_) {
return;
}
paused_ = false;
RequestFrame();
}
void Animator::BeginFrame(int64_t time_stamp) {
pending_frame_semaphore_.Signal();
if (!producer_continuation_) {
// We may already have a valid pipeline continuation in case a previous
// begin frame did not result in an Animation::Render. Simply reuse that
// instead of asking the pipeline for a fresh continuation.
producer_continuation_ = layer_tree_pipeline_->Produce();
if (!producer_continuation_) {
// If we still don't have valid continuation, the pipeline is currently
// full because the consumer is being too slow. Try again at the next
// frame interval.
TRACE_EVENT_INSTANT0("flutter", "ConsumerSlowDefer",
TRACE_EVENT_SCOPE_PROCESS);
RequestFrame();
return;
}
}
// We have acquired a valid continuation from the pipeline and are ready
// to service potential frame.
DCHECK(producer_continuation_);
last_begin_frame_time_ = ftl::TimePoint::Now();
engine_->BeginFrame(last_begin_frame_time_);
}
void Animator::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
if (layer_tree) {
// Note the frame time for instrumentation.
layer_tree->set_construction_time(ftl::TimePoint::Now() -
last_begin_frame_time_);
}
// Commit the pending continuation.
producer_continuation_.Complete(std::move(layer_tree));
// Notify the rasterizer that the pipeline has items it may consume.
auto weak_rasterizer(rasterizer_);
auto pipeline = layer_tree_pipeline_;
blink::Threads::Gpu()->PostTask([weak_rasterizer, pipeline]() {
if (!weak_rasterizer) {
return;
}
weak_rasterizer->Draw(pipeline);
});
}
void Animator::RequestFrame() {
if (paused_) {
return;
}
if (!pending_frame_semaphore_.TryWait()) {
// Multiple calls to Animator::RequestFrame will still result in a single
// request to the VSyncProvider.
return;
}
// The AwaitVSync is going to call us back at the next VSync. However, we want
// to be reasonably certain that the UI thread is not in the middle of a
// particularly expensive callout. We post the AwaitVSync to run right after
// an idle. This does NOT provide a guarantee that the UI thread has not
// started an expensive operation right after posting this message however.
// To support that, we need edge triggered wakes on VSync.
auto weak = weak_factory_.GetWeakPtr();
blink::Threads::UI()->PostTask([weak]() {
if (!weak) {
return;
}
TRACE_EVENT_INSTANT0("flutter", "RequestFrame", TRACE_EVENT_SCOPE_PROCESS);
weak->AwaitVSync(base::Bind(&Animator::BeginFrame, weak));
});
}
void Animator::set_vsync_provider(vsync::VSyncProviderPtr vsync_provider) {
vsync_provider_ = vsync_provider.Pass();
// We may be waiting on a VSync signal from the old VSync provider.
pending_frame_semaphore_.Signal();
RequestFrame();
}
void Animator::AwaitVSync(
const vsync::VSyncProvider::AwaitVSyncCallback& callback) {
// First, try the platform provided VSync provider.
if (vsync_provider_) {
vsync_provider_->AwaitVSync(callback);
return;
}
// Then, use the fallback provider if the platform cannot reliably supply
// VSync signals to us.
return fallback_vsync_provider_->AwaitVSync(callback);
}
} // namespace shell

View File

@@ -0,0 +1,60 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_ANIMATOR_H_
#define SHELL_COMMON_ANIMATOR_H_
#include "base/memory/weak_ptr.h"
#include "flutter/services/vsync/fallback/vsync_provider_fallback_impl.h"
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/synchronization/pipeline.h"
#include "flutter/synchronization/semaphore.h"
#include "lib/ftl/memory/ref_ptr.h"
#include "lib/ftl/time/time_point.h"
#include "mojo/services/vsync/interfaces/vsync.mojom.h"
namespace shell {
class Animator {
public:
explicit Animator(Rasterizer* rasterizer, Engine* engine);
~Animator();
void RequestFrame();
void Render(std::unique_ptr<flow::LayerTree> layer_tree);
void Start();
void Stop();
void set_vsync_provider(vsync::VSyncProviderPtr vsync_provider);
private:
using LayerTreePipeline = flutter::Pipeline<flow::LayerTree>;
void BeginFrame(int64_t time_stamp);
void AwaitVSync(const vsync::VSyncProvider::AwaitVSyncCallback& callback);
ftl::WeakPtr<Rasterizer> rasterizer_;
Engine* engine_;
vsync::VSyncProviderPtr vsync_provider_;
vsync::VSyncProviderPtr fallback_vsync_provider_;
ftl::TimePoint last_begin_frame_time_;
ftl::RefPtr<LayerTreePipeline> layer_tree_pipeline_;
flutter::Semaphore pending_frame_semaphore_;
LayerTreePipeline::ProducerContinuation producer_continuation_;
bool paused_;
base::WeakPtrFactory<Animator> weak_factory_;
FTL_DISALLOW_COPY_AND_ASSIGN(Animator);
};
} // namespace shell
#endif // SHELL_COMMON_ANIMATOR_H_

View File

@@ -0,0 +1,150 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/diagnostic/diagnostic_server.h"
#include "dart/runtime/include/dart_api.h"
#include "dart/runtime/include/dart_native_api.h"
#include "flutter/common/threads.h"
#include "flutter/flow/compositor_context.h"
#include "flutter/runtime/embedder_resources.h"
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/picture_serializer.h"
#include "lib/ftl/logging.h"
#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"
#include "lib/tonic/logging/dart_invoke.h"
#include "third_party/skia/include/core/SkStream.h"
namespace mojo {
namespace dart {
extern ResourcesEntry __sky_embedder_diagnostic_server_resources_[];
}
}
namespace shell {
using tonic::DartLibraryNatives;
using blink::EmbedderResources;
using tonic::DartInvokeField;
using tonic::LogIfError;
namespace {
DartLibraryNatives* g_natives = nullptr;
constexpr char kDiagnosticServerScript[] = "/diagnostic_server.dart";
Dart_NativeFunction GetNativeFunction(Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
FTL_CHECK(g_natives);
return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope);
}
const uint8_t* GetSymbol(Dart_NativeFunction native_function) {
FTL_CHECK(g_natives);
return g_natives->GetSymbol(native_function);
}
void SendNull(Dart_Port port_id) {
Dart_CObject null_object;
null_object.type = Dart_CObject_kNull;
Dart_PostCObject(port_id, &null_object);
}
} // namespace
DART_NATIVE_CALLBACK_STATIC(DiagnosticServer, HandleSkiaPictureRequest);
void DiagnosticServer::Start() {
if (!g_natives) {
g_natives = new DartLibraryNatives();
g_natives->Register({
DART_REGISTER_NATIVE_STATIC(DiagnosticServer, HandleSkiaPictureRequest),
});
}
EmbedderResources resources(
&mojo::dart::__sky_embedder_diagnostic_server_resources_[0]);
const char* source = nullptr;
int source_length =
resources.ResourceLookup(kDiagnosticServerScript, &source);
FTL_DCHECK(source_length != EmbedderResources::kNoSuchInstance);
Dart_Handle diagnostic_library = Dart_LoadLibrary(
Dart_NewStringFromCString("dart:diagnostic_server"), Dart_Null(),
Dart_NewStringFromUTF8(reinterpret_cast<const uint8_t*>(source),
source_length),
0, 0);
FTL_CHECK(!LogIfError(diagnostic_library));
FTL_CHECK(!LogIfError(Dart_SetNativeResolver(diagnostic_library,
GetNativeFunction, GetSymbol)));
FTL_CHECK(!LogIfError(Dart_LibraryImportLibrary(
Dart_RootLibrary(), diagnostic_library, Dart_Null())));
FTL_CHECK(!LogIfError(Dart_FinalizeLoading(false)));
DartInvokeField(Dart_RootLibrary(), "diagnosticServerStart", {});
}
void DiagnosticServer::HandleSkiaPictureRequest(Dart_Handle send_port) {
Dart_Port port_id;
FTL_CHECK(!LogIfError(Dart_SendPortGetId(send_port, &port_id)));
blink::Threads::Gpu()->PostTask([port_id]() { SkiaPictureTask(port_id); });
}
void DiagnosticServer::SkiaPictureTask(Dart_Port port_id) {
std::vector<ftl::WeakPtr<Rasterizer>> rasterizers;
Shell::Shared().GetRasterizers(&rasterizers);
if (rasterizers.size() != 1) {
SendNull(port_id);
return;
}
Rasterizer* rasterizer = rasterizers[0].get();
if (rasterizer == nullptr) {
SendNull(port_id);
return;
}
flow::LayerTree* layer_tree = rasterizer->GetLastLayerTree();
if (layer_tree == nullptr) {
SendNull(port_id);
return;
}
SkPictureRecorder recorder;
recorder.beginRecording(SkRect::MakeWH(layer_tree->frame_size().width(),
layer_tree->frame_size().height()));
flow::CompositorContext compositor_context;
flow::CompositorContext::ScopedFrame frame = compositor_context.AcquireFrame(
nullptr, *recorder.getRecordingCanvas(), false);
layer_tree->Raster(frame);
sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture();
SkDynamicMemoryWStream stream;
PngPixelSerializer serializer;
picture->serialize(&stream, &serializer);
SkAutoTUnref<SkData> picture_data(stream.copyToData());
Dart_CObject c_object;
c_object.type = Dart_CObject_kTypedData;
c_object.value.as_typed_data.type = Dart_TypedData_kUint8;
c_object.value.as_typed_data.values =
const_cast<uint8_t*>(picture_data->bytes());
c_object.value.as_typed_data.length = picture_data->size();
Dart_PostCObject(port_id, &c_object);
}
} // namespace shell

View File

@@ -0,0 +1,59 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library diagnostic_server;
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
void handleSkiaPictureRequest(SendPort sendPort)
native 'DiagnosticServer_HandleSkiaPictureRequest';
void diagnosticServerStart() {
HttpServer.bind('127.0.0.1', 0).then((HttpServer server) {
server.listen(dispatchRequest, cancelOnError: true);
String ip = server.address.address.toString();
String port = server.port.toString();
print('Diagnostic server listening on http://$ip:$port');
});
}
void sendError(HttpResponse response, String error) {
response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
response.headers.contentType = ContentType.TEXT;
response.write(error);
}
void dispatchRequest(HttpRequest request) {
HttpResponse response = request.response;
try {
if (request.uri.path == '/skp') {
ReceivePort port = new ReceivePort();
port.first.then((Uint8List data) => onReceiveSkiaPicture(response, data));
handleSkiaPictureRequest(port.sendPort);
return;
}
sendError(response, 'Diagnostic server: unexpected request, uri=${request.uri}');
} catch (e) {
sendError(response, 'Diagnostic server: error processing request, uri=${request.uri}\n${e}');
}
response.close();
}
void onReceiveSkiaPicture(HttpResponse response, Uint8List data) {
if (data != null) {
response.statusCode = HttpStatus.OK;
response.headers.contentType = ContentType.BINARY;
response.headers.contentLength = data.length;
response.add(data);
} else {
sendError(response, 'Unable to capture Skia picture');
}
response.close();
}

View File

@@ -0,0 +1,23 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_ENGINE_CORE_DIAGNOSTIC_DIAGNOSTIC_SERVER_H_
#define SKY_ENGINE_CORE_DIAGNOSTIC_DIAGNOSTIC_SERVER_H_
#include "dart/runtime/include/dart_api.h"
namespace shell {
class DiagnosticServer {
public:
static void Start();
static void HandleSkiaPictureRequest(Dart_Handle send_port);
private:
static void SkiaPictureTask(Dart_Port port_id);
};
} // namespace shell
#endif // SKY_ENGINE_CORE_DIAGNOSTIC_DIAGNOSTIC_SERVER_H_

View File

@@ -0,0 +1,336 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/engine.h"
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/assets/unzipper_provider.h"
#include "flutter/assets/zip_asset_bundle.h"
#include "flutter/common/threads.h"
#include "flutter/glue/movable_wrapper.h"
#include "flutter/glue/trace_event.h"
#include "flutter/lib/ui/mojo_services.h"
#include "flutter/runtime/asset_font_selector.h"
#include "flutter/runtime/dart_controller.h"
#include "flutter/runtime/dart_init.h"
#include "flutter/runtime/runtime_init.h"
#include "flutter/shell/common/animator.h"
#include "flutter/sky/engine/public/web/Sky.h"
#include "lib/ftl/files/path.h"
#include "mojo/public/cpp/application/connect.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
namespace shell {
namespace {
bool PathExists(const std::string& path) {
return access(path.c_str(), R_OK) == 0;
}
std::string FindPackagesPath(const std::string& main_dart) {
std::string directory = files::GetDirectoryName(main_dart);
std::string packages_path = directory + "/.packages";
if (!PathExists(packages_path)) {
directory = files::GetDirectoryName(directory);
packages_path = directory + "/.packages";
if (!PathExists(packages_path))
packages_path = std::string();
}
return packages_path;
}
} // namespace
Engine::Engine(Rasterizer* rasterizer)
: animator_(new Animator(rasterizer, this)),
binding_(this),
activity_running_(false),
have_surface_(false),
weak_factory_(this) {}
Engine::~Engine() {}
ftl::WeakPtr<Engine> Engine::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void Engine::Init() {
blink::InitRuntime();
}
void Engine::BeginFrame(ftl::TimePoint frame_time) {
TRACE_EVENT0("flutter", "Engine::BeginFrame");
if (runtime_)
runtime_->BeginFrame(frame_time);
}
void Engine::RunFromSource(const std::string& main,
const std::string& packages,
const std::string& bundle) {
TRACE_EVENT0("flutter", "Engine::RunFromSource");
std::string packages_path = packages;
if (packages_path.empty())
packages_path = FindPackagesPath(main);
if (!bundle.empty())
ConfigureAssetBundle(bundle);
ConfigureRuntime(main);
runtime_->dart_controller()->RunFromSource(main, packages_path);
}
Dart_Port Engine::GetUIIsolateMainPort() {
if (!runtime_)
return ILLEGAL_PORT;
return runtime_->GetMainPort();
}
std::string Engine::GetUIIsolateName() {
if (!runtime_) {
return "";
}
return runtime_->GetIsolateName();
}
void Engine::ConnectToEngine(mojo::InterfaceRequest<SkyEngine> request) {
binding_.Bind(request.Pass());
}
void Engine::OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) {
blink::Threads::Gpu()->PostTask(gpu_continuation);
have_surface_ = true;
StartAnimatorIfPossible();
if (runtime_)
ScheduleFrame();
}
void Engine::OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) {
have_surface_ = false;
StopAnimator();
blink::Threads::Gpu()->PostTask(gpu_continuation);
}
void Engine::SetServices(sky::ServicesDataPtr services) {
services_ = services.Pass();
if (services_->incoming_services) {
incoming_services_ =
mojo::ServiceProviderPtr::Create(services_->incoming_services.Pass());
service_provider_impl_.set_fallback_service_provider(
incoming_services_.get());
}
vsync::VSyncProviderPtr vsync_provider;
if (services_->shell) {
// We bind and unbind our Shell here, since this is the only place we use
// it in this class.
auto shell = mojo::ShellPtr::Create(services_->shell.Pass());
mojo::ConnectToService(shell.get(), "mojo:vsync",
mojo::GetProxy(&vsync_provider));
services_->shell = shell.Pass();
} else {
mojo::ConnectToService(incoming_services_.get(),
mojo::GetProxy(&vsync_provider));
}
animator_->set_vsync_provider(vsync_provider.Pass());
}
void Engine::OnViewportMetricsChanged(sky::ViewportMetricsPtr metrics) {
viewport_metrics_ = metrics.Pass();
if (runtime_)
runtime_->SetViewportMetrics(viewport_metrics_);
}
void Engine::OnLocaleChanged(const mojo::String& language_code,
const mojo::String& country_code) {
language_code_ = language_code;
country_code_ = country_code;
if (runtime_)
runtime_->SetLocale(language_code_, country_code_);
}
void Engine::OnPointerPacket(pointer::PointerPacketPtr packet) {
TRACE_EVENT0("flutter", "Engine::OnPointerPacket");
if (runtime_)
runtime_->HandlePointerPacket(packet);
}
void Engine::RunFromSnapshotStream(
const std::string& script_uri,
mojo::ScopedDataPipeConsumerHandle snapshot) {
TRACE_EVENT0("flutter", "Engine::RunFromSnapshotStream");
ConfigureRuntime(script_uri);
snapshot_drainer_.reset(new glue::DrainDataPipeJob(
std::move(snapshot), [this](std::vector<char> snapshot) {
FTL_DCHECK(runtime_);
FTL_DCHECK(runtime_->dart_controller());
runtime_->dart_controller()->RunFromSnapshot(
reinterpret_cast<uint8_t*>(snapshot.data()), snapshot.size());
}));
}
void Engine::ConfigureAssetBundle(const std::string& path) {
struct stat stat_result = {0};
if (::stat(path.c_str(), &stat_result) != 0) {
LOG(INFO) << "Could not configure asset bundle at path: " << path;
return;
}
if (S_ISDIR(stat_result.st_mode)) {
// Directory asset bundle.
new blink::DirectoryAssetBundle(mojo::GetProxy(&root_bundle_), path,
blink::Threads::IO());
return;
}
if (S_ISREG(stat_result.st_mode)) {
// Zip asset bundle.
asset_store_ = ftl::MakeRefCounted<blink::ZipAssetStore>(
blink::GetUnzipperProviderForPath(path), blink::Threads::IO());
new blink::ZipAssetBundle(mojo::GetProxy(&root_bundle_), asset_store_);
return;
}
}
void Engine::ConfigureRuntime(const std::string& script_uri) {
snapshot_drainer_.reset();
runtime_ = blink::RuntimeController::Create(this);
runtime_->CreateDartController(std::move(script_uri));
runtime_->SetViewportMetrics(viewport_metrics_);
runtime_->SetLocale(language_code_, country_code_);
if (!initial_route_.empty())
runtime_->PushRoute(initial_route_);
}
void Engine::RunFromPrecompiledSnapshot(const mojo::String& bundle_path) {
TRACE_EVENT0("flutter", "Engine::RunFromPrecompiledSnapshot");
ConfigureAssetBundle(bundle_path.get());
ConfigureRuntime("http://localhost");
runtime_->dart_controller()->RunFromPrecompiledSnapshot();
}
void Engine::RunFromFile(const mojo::String& main,
const mojo::String& packages,
const mojo::String& bundle) {
RunFromSource(main, packages, bundle);
}
void Engine::RunFromBundle(const mojo::String& script_uri,
const mojo::String& path) {
TRACE_EVENT0("flutter", "Engine::RunFromBundle");
ConfigureAssetBundle(path);
mojo::DataPipe pipe;
asset_store_->GetAsStream(blink::kSnapshotAssetKey,
std::move(pipe.producer_handle));
RunFromSnapshotStream(script_uri, std::move(pipe.consumer_handle));
}
void Engine::RunFromBundleAndSnapshot(const mojo::String& script_uri,
const mojo::String& bundle_path,
const mojo::String& snapshot_path) {
TRACE_EVENT0("flutter", "Engine::RunFromBundleAndSnapshot");
ConfigureAssetBundle(bundle_path);
asset_store_->AddOverlayFile(blink::kSnapshotAssetKey, snapshot_path);
mojo::DataPipe pipe;
asset_store_->GetAsStream(blink::kSnapshotAssetKey,
std::move(pipe.producer_handle));
RunFromSnapshotStream(script_uri, std::move(pipe.consumer_handle));
}
void Engine::PushRoute(const mojo::String& route) {
if (runtime_)
runtime_->PushRoute(route);
else
initial_route_ = route;
}
void Engine::PopRoute() {
if (runtime_)
runtime_->PopRoute();
}
void Engine::OnAppLifecycleStateChanged(sky::AppLifecycleState state) {
switch (state) {
case sky::AppLifecycleState::PAUSED:
activity_running_ = false;
StopAnimator();
break;
case sky::AppLifecycleState::RESUMED:
activity_running_ = true;
StartAnimatorIfPossible();
break;
}
if (runtime_)
runtime_->OnAppLifecycleStateChanged(state);
}
void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
mojo::ServiceProviderPtr services_from_embedder;
service_provider_bindings_.AddBinding(
&service_provider_impl_, mojo::GetProxy(&services_from_embedder));
blink::MojoServices::Create(isolate, std::move(services_),
std::move(services_from_embedder),
std::move(root_bundle_));
if (asset_store_)
blink::AssetFontSelector::Install(asset_store_);
}
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {
mojo::ServiceProviderPtr services_from_embedder;
auto request = glue::WrapMovable(mojo::GetProxy(&services_from_embedder));
ftl::WeakPtr<Engine> engine = weak_factory_.GetWeakPtr();
blink::Threads::UI()->PostTask([engine, request]() mutable {
if (engine)
engine->BindToServiceProvider(request.Unwrap());
});
blink::MojoServices::Create(isolate, nullptr,
std::move(services_from_embedder), nullptr);
}
void Engine::BindToServiceProvider(
mojo::InterfaceRequest<mojo::ServiceProvider> request) {
service_provider_bindings_.AddBinding(&service_provider_impl_,
request.Pass());
}
void Engine::StopAnimator() {
animator_->Stop();
}
void Engine::StartAnimatorIfPossible() {
if (activity_running_ && have_surface_)
animator_->Start();
}
void Engine::ScheduleFrame() {
animator_->RequestFrame();
}
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
if (!layer_tree)
return;
if (!viewport_metrics_)
return;
SkISize frame_size = SkISize::Make(viewport_metrics_->physical_width,
viewport_metrics_->physical_height);
if (frame_size.isEmpty())
return;
layer_tree->set_scene_version(viewport_metrics_->scene_version);
layer_tree->set_frame_size(frame_size);
animator_->Render(std::move(layer_tree));
}
} // namespace shell

View File

@@ -0,0 +1,125 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_ENGINE_H_
#define SHELL_COMMON_ENGINE_H_
#include "flutter/assets/zip_asset_store.h"
#include "flutter/glue/drain_data_pipe_job.h"
#include "flutter/runtime/runtime_controller.h"
#include "flutter/runtime/runtime_delegate.h"
#include "flutter/services/engine/sky_engine.mojom.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/ui_delegate.h"
#include "lib/ftl/macros.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "mojo/public/cpp/application/service_provider_impl.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/handle.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"
#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace shell {
class Animator;
class Engine : public UIDelegate,
public sky::SkyEngine,
public blink::RuntimeDelegate {
public:
explicit Engine(Rasterizer* rasterizer);
~Engine() override;
ftl::WeakPtr<Engine> GetWeakPtr();
static void Init();
void BeginFrame(ftl::TimePoint frame_time);
void RunFromSource(const std::string& main,
const std::string& packages,
const std::string& bundle);
Dart_Port GetUIIsolateMainPort();
std::string GetUIIsolateName();
private:
// UIDelegate implementation:
void ConnectToEngine(mojo::InterfaceRequest<SkyEngine> request) override;
void OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) override;
void OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) override;
// SkyEngine implementation:
void SetServices(sky::ServicesDataPtr services) override;
void OnViewportMetricsChanged(sky::ViewportMetricsPtr metrics) override;
void OnLocaleChanged(const mojo::String& language_code,
const mojo::String& country_code) override;
void OnPointerPacket(pointer::PointerPacketPtr packet) override;
void RunFromFile(const mojo::String& main,
const mojo::String& packages,
const mojo::String& bundle) override;
void RunFromPrecompiledSnapshot(const mojo::String& bundle_path) override;
void RunFromBundle(const mojo::String& script_uri,
const mojo::String& bundle_path) override;
void RunFromBundleAndSnapshot(const mojo::String& script_uri,
const mojo::String& bundle_path,
const mojo::String& snapshot_path) override;
void PushRoute(const mojo::String& route) override;
void PopRoute() override;
void OnAppLifecycleStateChanged(sky::AppLifecycleState state) override;
// RuntimeDelegate methods:
void ScheduleFrame() override;
void Render(std::unique_ptr<flow::LayerTree> layer_tree) override;
void DidCreateMainIsolate(Dart_Isolate isolate) override;
void DidCreateSecondaryIsolate(Dart_Isolate isolate) override;
void BindToServiceProvider(
mojo::InterfaceRequest<mojo::ServiceProvider> request);
void RunFromSnapshotStream(const std::string& script_uri,
mojo::ScopedDataPipeConsumerHandle snapshot);
void StopAnimator();
void StartAnimatorIfPossible();
void ConfigureAssetBundle(const std::string& path);
void ConfigureRuntime(const std::string& script_uri);
std::unique_ptr<Animator> animator_;
sky::ServicesDataPtr services_;
mojo::ServiceProviderImpl service_provider_impl_;
mojo::ServiceProviderPtr incoming_services_;
mojo::BindingSet<mojo::ServiceProvider> service_provider_bindings_;
mojo::asset_bundle::AssetBundlePtr root_bundle_;
std::unique_ptr<blink::RuntimeController> runtime_;
std::unique_ptr<glue::DrainDataPipeJob> snapshot_drainer_;
std::string initial_route_;
sky::ViewportMetricsPtr viewport_metrics_;
std::string language_code_;
std::string country_code_;
mojo::Binding<SkyEngine> binding_;
ftl::RefPtr<blink::ZipAssetStore> asset_store_;
// TODO(eseidel): This should move into an AnimatorStateMachine.
bool activity_running_;
bool have_surface_;
ftl::WeakPtrFactory<Engine> weak_factory_;
FTL_DISALLOW_COPY_AND_ASSIGN(Engine);
};
} // namespace shell
#endif // SHELL_COMMON_ENGINE_H_

View File

@@ -0,0 +1,36 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/picture_serializer.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkImageEncoder.h"
#include "third_party/skia/include/core/SkPixelSerializer.h"
#include "third_party/skia/include/core/SkStream.h"
namespace shell {
bool PngPixelSerializer::onUseEncodedData(const void*, size_t) {
return true;
}
SkData* PngPixelSerializer::onEncode(const SkPixmap& pixmap) {
SkBitmap bitmap;
if (!bitmap.installPixels(pixmap)) {
return nullptr;
}
return SkImageEncoder::EncodeData(bitmap, SkImageEncoder::Type::kPNG_Type,
SkImageEncoder::kDefaultQuality);
}
void SerializePicture(const std::string& path, SkPicture* picture) {
SkFILEWStream stream(path.c_str());
PngPixelSerializer serializer;
picture->serialize(&stream, &serializer);
}
} // namespace shell

View File

@@ -0,0 +1,25 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_PICTURE_SERIALIZER_H_
#define SHELL_GPU_PICTURE_SERIALIZER_H_
#include <string>
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPixelSerializer.h"
namespace shell {
class PngPixelSerializer : public SkPixelSerializer {
public:
bool onUseEncodedData(const void*, size_t) override;
SkData* onEncode(const SkPixmap& pixmap) override;
};
void SerializePicture(const std::string& path, SkPicture* picture);
} // namespace shell
#endif // SHELL_GPU_PICTURE_SERIALIZER_H_

View File

@@ -0,0 +1,140 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/platform_view.h"
#include <utility>
#include "flutter/common/threads.h"
#include "flutter/glue/movable_wrapper.h"
#include "flutter/lib/ui/painting/resource_context.h"
#include "flutter/shell/common/rasterizer.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace shell {
PlatformView::Config::Config() : rasterizer(nullptr) {}
PlatformView::Config::~Config() = default;
PlatformView::PlatformView()
: rasterizer_(Rasterizer::Create()), size_(SkISize::Make(0, 0)) {
engine_.reset(new Engine(rasterizer_.get()));
// Setup the platform config.
config_.ui_delegate = engine_->GetWeakPtr();
config_.rasterizer = rasterizer_.get();
}
PlatformView::~PlatformView() {
blink::Threads::UI()->PostTask(
[]() { Shell::Shared().PurgePlatformViews(); });
Rasterizer* rasterizer = rasterizer_.release();
blink::Threads::Gpu()->PostTask([rasterizer]() { delete rasterizer; });
Engine* engine = engine_.release();
blink::Threads::UI()->PostTask([engine]() { delete engine; });
}
void PlatformView::ConnectToEngine(
mojo::InterfaceRequest<sky::SkyEngine> request) {
ftl::WeakPtr<UIDelegate> ui_delegate = config_.ui_delegate;
auto wrapped_request = glue::WrapMovable(std::move(request));
blink::Threads::UI()->PostTask([ui_delegate, wrapped_request]() mutable {
if (ui_delegate)
ui_delegate->ConnectToEngine(wrapped_request.Unwrap());
});
ftl::WeakPtr<PlatformView> view = GetWeakViewPtr();
blink::Threads::UI()->PostTask(
[view]() { Shell::Shared().AddPlatformView(view); });
}
void PlatformView::NotifyCreated() {
PlatformView::NotifyCreated([]() {});
}
void PlatformView::NotifyCreated(ftl::Closure rasterizer_continuation) {
FTL_CHECK(config_.rasterizer);
ftl::AutoResetWaitableEvent latch;
auto delegate_continuation = [this, rasterizer_continuation, &latch]() {
config_.rasterizer->Setup(this, rasterizer_continuation, &latch);
};
auto delegate = config_.ui_delegate;
blink::Threads::UI()->PostTask([delegate, delegate_continuation]() {
delegate->OnOutputSurfaceCreated(delegate_continuation);
});
latch.Wait();
}
void PlatformView::NotifyDestroyed() {
FTL_CHECK(config_.rasterizer != nullptr);
auto delegate = config_.ui_delegate;
auto rasterizer = config_.rasterizer->GetWeakRasterizerPtr();
ftl::AutoResetWaitableEvent latch;
auto delegate_continuation = [rasterizer, &latch]() {
if (rasterizer)
rasterizer->Teardown(&latch);
// TODO(abarth): We should signal the latch if the rasterizer is gone.
};
blink::Threads::UI()->PostTask([delegate, delegate_continuation]() {
if (delegate)
delegate->OnOutputSurfaceDestroyed(delegate_continuation);
// TODO(abarth): We should signal the latch if the delegate is gone.
});
latch.Wait();
}
SkISize PlatformView::GetSize() {
return size_;
}
void PlatformView::Resize(const SkISize& size) {
size_ = size;
}
void PlatformView::SetupResourceContextOnIOThread() {
ftl::AutoResetWaitableEvent latch;
blink::Threads::IO()->PostTask(
[this, &latch]() { SetupResourceContextOnIOThreadPerform(&latch); });
latch.Wait();
}
void PlatformView::SetupResourceContextOnIOThreadPerform(
ftl::AutoResetWaitableEvent* latch) {
if (blink::ResourceContext::Get() != nullptr) {
// The resource context was already setup. This could happen if platforms
// try to setup a context multiple times, or, if there are multiple platform
// views. In any case, there is nothing else to do. So just signal the
// latch.
latch->Signal();
return;
}
bool current = ResourceContextMakeCurrent();
if (!current) {
LOG(WARNING)
<< "WARNING: Could not setup an OpenGL context on the resource loader.";
}
blink::ResourceContext::Set(GrContext::Create(
GrBackend::kOpenGL_GrBackend,
reinterpret_cast<GrBackendContext>(GrGLCreateNativeInterface())));
latch->Signal();
}
} // namespace shell

View File

@@ -0,0 +1,95 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMMON_PLATFORM_VIEW_H_
#define COMMON_PLATFORM_VIEW_H_
#include <memory>
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/ui_delegate.h"
#include "lib/ftl/macros.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "lib/ftl/synchronization/waitable_event.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace shell {
class Rasterizer;
class PlatformView {
public:
struct Config {
Config();
~Config();
ftl::WeakPtr<UIDelegate> ui_delegate;
Rasterizer* rasterizer;
};
struct SurfaceConfig {
uint8_t red_bits = 8;
uint8_t green_bits = 8;
uint8_t blue_bits = 8;
uint8_t alpha_bits = 8;
uint8_t depth_bits = 0;
uint8_t stencil_bits = 8;
};
void SetupResourceContextOnIOThread();
virtual ~PlatformView();
void ConnectToEngine(mojo::InterfaceRequest<sky::SkyEngine> request);
void NotifyCreated();
void NotifyCreated(ftl::Closure continuation);
void NotifyDestroyed();
virtual ftl::WeakPtr<PlatformView> GetWeakViewPtr() = 0;
virtual uint64_t DefaultFramebuffer() const = 0;
virtual bool ContextMakeCurrent() = 0;
virtual bool ResourceContextMakeCurrent() = 0;
virtual bool SwapBuffers() = 0;
virtual SkISize GetSize();
virtual void Resize(const SkISize& size);
Engine& engine() { return *engine_; }
virtual void RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) = 0;
protected:
Config config_;
SurfaceConfig surface_config_;
std::unique_ptr<Rasterizer> rasterizer_;
std::unique_ptr<Engine> engine_;
SkISize size_;
explicit PlatformView();
void SetupResourceContextOnIOThreadPerform(
ftl::AutoResetWaitableEvent* event);
private:
FTL_DISALLOW_COPY_AND_ASSIGN(PlatformView);
};
} // namespace shell
#endif // COMMON_PLATFORM_VIEW_H_

View File

@@ -0,0 +1,216 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/platform_view_service_protocol.h"
#include <string.h>
#include <string>
#include "flutter/shell/common/shell.h"
namespace shell {
namespace {
constexpr char kViewIdPrefx[] = "_flutterView/";
constexpr size_t kViewIdPrefxLength = sizeof(kViewIdPrefx) - 1;
static intptr_t KeyIndex(const char** param_keys,
intptr_t num_params,
const char* key) {
if (param_keys == NULL) {
return -1;
}
for (intptr_t i = 0; i < num_params; i++) {
if (strcmp(param_keys[i], key) == 0) {
return i;
}
}
return -1;
}
static const char* ValueForKey(const char** param_keys,
const char** param_values,
intptr_t num_params,
const char* key) {
intptr_t index = KeyIndex(param_keys, num_params, key);
if (index < 0) {
return NULL;
}
return param_values[index];
}
static bool ErrorMissingParameter(const char** json_object, const char* name) {
const intptr_t kInvalidParams = -32602;
std::stringstream response;
response << "{\"code\":" << std::to_string(kInvalidParams) << ",";
response << "\"message\":\"Invalid params\",";
response << "\"data\": {\"details\": \"" << name << "\"}}";
*json_object = strdup(response.str().c_str());
return false;
}
static bool ErrorBadParameter(const char** json_object,
const char* name,
const char* value) {
const intptr_t kInvalidParams = -32602;
std::stringstream response;
response << "{\"code\":" << std::to_string(kInvalidParams) << ",";
response << "\"message\":\"Invalid params\",";
response << "\"data\": {\"details\": \"parameter: " << name << " has a bad ";
response << "value: " << value << "\"}}";
*json_object = strdup(response.str().c_str());
return false;
}
static bool ErrorUnknownView(const char** json_object, const char* view_id) {
const intptr_t kInvalidParams = -32602;
std::stringstream response;
response << "{\"code\":" << std::to_string(kInvalidParams) << ",";
response << "\"message\":\"Invalid params\",";
response << "\"data\": {\"details\": \"view not found: " << view_id << "\"}}";
*json_object = strdup(response.str().c_str());
return false;
}
static void AppendIsolateRef(std::stringstream* stream,
int64_t main_port,
const std::string name) {
*stream << "{\"type\":\"@Isolate\",\"fixedId\":true,\"id\":\"isolates/";
*stream << main_port << "\",\"name\":\"" << name << "\",";
*stream << "\"number\":\"" << main_port << "\"}";
}
static void AppendFlutterView(std::stringstream* stream,
uintptr_t view_id,
int64_t isolate_id,
const std::string isolate_name) {
*stream << "{\"type\":\"FlutterView\", \"id\": \"" << kViewIdPrefx << "0x"
<< std::hex << view_id << std::dec;
if (isolate_id != ILLEGAL_PORT) {
// Append the isolate (if it exists).
*stream << "\","
<< "\"isolate\":";
AppendIsolateRef(stream, isolate_id, isolate_name);
}
*stream << "}";
}
} // namespace
void PlatformViewServiceProtocol::RegisterHook(bool running_precompiled_code) {
// Listing of FlutterViews.
Dart_RegisterRootServiceRequestCallback(kListViewsExtensionName, &ListViews,
nullptr);
// The following set of service protocol extensions require debug build
if (running_precompiled_code) {
return;
}
Dart_RegisterRootServiceRequestCallback(kRunInViewExtensionName, &RunInView,
nullptr);
}
const char* PlatformViewServiceProtocol::kRunInViewExtensionName =
"_flutter.runInView";
bool PlatformViewServiceProtocol::RunInView(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object) {
const char* view_id =
ValueForKey(param_keys, param_values, num_params, "viewId");
const char* asset_directory =
ValueForKey(param_keys, param_values, num_params, "assetDirectory");
const char* main_script =
ValueForKey(param_keys, param_values, num_params, "mainScript");
const char* packages_file =
ValueForKey(param_keys, param_values, num_params, "packagesFile");
if (view_id == NULL) {
return ErrorMissingParameter(json_object, "viewId");
}
if (strncmp(view_id, kViewIdPrefx, kViewIdPrefxLength) != 0) {
return ErrorBadParameter(json_object, "viewId", view_id);
}
if (asset_directory == NULL) {
return ErrorMissingParameter(json_object, "assetDirectory");
}
if (main_script == NULL) {
return ErrorMissingParameter(json_object, "mainScript");
}
if (packages_file == NULL) {
return ErrorMissingParameter(json_object, "packagesFile");
}
// Convert the actual flutter view hex id into a number.
uintptr_t view_id_as_num =
std::stoull((view_id + kViewIdPrefxLength), nullptr, 16);
// Ask the Shell to run this script in the specified view. This will run a
// task on the UI thread before returning.
Shell& shell = Shell::Shared();
bool view_existed = false;
Dart_Port main_port = ILLEGAL_PORT;
std::string isolate_name;
shell.RunInPlatformView(view_id_as_num, main_script, packages_file,
asset_directory, &view_existed, &main_port,
&isolate_name);
if (!view_existed) {
// If the view did not exist this request has definitely failed.
return ErrorUnknownView(json_object, view_id);
} else {
// The view existed and the isolate was created. Success.
std::stringstream response;
response << "{\"type\":\"Success\","
<< "\"view\":";
AppendFlutterView(&response, view_id_as_num, main_port, isolate_name);
response << "}";
*json_object = strdup(response.str().c_str());
return true;
}
return true;
}
const char* PlatformViewServiceProtocol::kListViewsExtensionName =
"_flutter.listViews";
bool PlatformViewServiceProtocol::ListViews(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object) {
// Ask the Shell for the list of platform views. This will run a task on
// the UI thread before returning.
Shell& shell = Shell::Shared();
std::vector<Shell::PlatformViewInfo> platform_views;
shell.WaitForPlatformViewIds(&platform_views);
std::stringstream response;
response << "{\"type\":\"FlutterViewList\",\"views\":[";
bool prefix_comma = false;
for (auto it = platform_views.begin(); it != platform_views.end(); it++) {
uintptr_t view_id = it->view_id;
int64_t isolate_id = it->isolate_id;
const std::string& isolate_name = it->isolate_name;
if (!view_id) {
continue;
}
if (prefix_comma) {
response << ',';
} else {
prefix_comma = true;
}
AppendFlutterView(&response, view_id, isolate_id, isolate_name);
}
response << "]}";
// Copy the response.
*json_object = strdup(response.str().c_str());
return true;
}
} // namespace shell

View File

@@ -0,0 +1,39 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_VIEW_SERVICE_PROTOCOL_H_
#define SHELL_COMMON_VIEW_SERVICE_PROTOCOL_H_
#include <memory>
#include "dart/runtime/include/dart_tools_api.h"
#include "flutter/shell/common/platform_view.h"
namespace shell {
class PlatformViewServiceProtocol {
public:
static void RegisterHook(bool running_precompiled_code);
private:
static const char* kRunInViewExtensionName;
static bool RunInView(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object);
static const char* kListViewsExtensionName;
static bool ListViews(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object);
};
} // namespace shell
#endif // SHELL_COMMON_VIEW_SERVICE_PROTOCOL_H_

View File

@@ -0,0 +1,11 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/rasterizer.h"
namespace shell {
Rasterizer::~Rasterizer() {}
} // namespace shell

View File

@@ -0,0 +1,47 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_RASTERIZER_H_
#define SHELL_COMMON_RASTERIZER_H_
#include <memory>
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/synchronization/pipeline.h"
#include "lib/ftl/functional/closure.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "lib/ftl/synchronization/waitable_event.h"
#include "mojo/public/cpp/bindings/binding.h"
namespace shell {
class PlatformView;
class Rasterizer {
public:
virtual ~Rasterizer();
virtual void Setup(PlatformView* platform_view,
ftl::Closure rasterizer_continuation,
ftl::AutoResetWaitableEvent* setup_completion_event) = 0;
virtual void Clear(SkColor color) = 0;
virtual void Teardown(
ftl::AutoResetWaitableEvent* teardown_completion_event) = 0;
virtual ftl::WeakPtr<Rasterizer> GetWeakRasterizerPtr() = 0;
virtual flow::LayerTree* GetLastLayerTree() = 0;
virtual void Draw(
ftl::RefPtr<flutter::Pipeline<flow::LayerTree>> pipeline) = 0;
// Implemented by each GPU backend.
static std::unique_ptr<Rasterizer> Create();
};
} // namespace shell
#endif // SHELL_COMMON_RASTERIZER_H_

View File

@@ -0,0 +1,327 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/shell.h"
#include <fcntl.h>
#include <memory>
#include <sstream>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/memory/discardable_memory.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/posix/eintr_wrapper.h"
#include "base/single_thread_task_runner.h"
#include "base/trace_event/trace_event.h"
#include "dart/runtime/include/dart_tools_api.h"
#include "flutter/common/settings.h"
#include "flutter/common/threads.h"
#include "flutter/glue/task_runner_adaptor.h"
#include "flutter/runtime/dart_init.h"
#include "flutter/shell/common/engine.h"
#include "flutter/shell/common/platform_view_service_protocol.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/diagnostic/diagnostic_server.h"
#include "flutter/skia/ext/event_tracer_impl.h"
#include "lib/ftl/files/unique_fd.h"
#include "mojo/message_pump/message_pump_mojo.h"
namespace shell {
namespace {
static Shell* g_shell = nullptr;
scoped_ptr<base::MessagePump> CreateMessagePumpMojo() {
return make_scoped_ptr(new mojo::common::MessagePumpMojo);
}
bool IsInvalid(const ftl::WeakPtr<Rasterizer>& rasterizer) {
return !rasterizer;
}
bool IsViewInvalid(const ftl::WeakPtr<PlatformView>& platform_view) {
return !platform_view;
}
class NonDiscardableMemory : public base::DiscardableMemory {
public:
explicit NonDiscardableMemory(size_t size) : data_(new uint8_t[size]) {}
bool Lock() override { return false; }
void Unlock() override {}
void* data() const override { return data_.get(); }
private:
std::unique_ptr<uint8_t[]> data_;
};
class NonDiscardableMemoryAllocator : public base::DiscardableMemoryAllocator {
public:
scoped_ptr<base::DiscardableMemory> AllocateLockedDiscardableMemory(
size_t size) override {
return make_scoped_ptr(new NonDiscardableMemory(size));
}
};
base::LazyInstance<NonDiscardableMemoryAllocator> g_discardable;
void ServiceIsolateHook(bool running_precompiled) {
if (!running_precompiled) {
const blink::Settings& settings = blink::Settings::Get();
if (settings.enable_observatory)
DiagnosticServer::Start();
}
}
} // namespace
Shell::Shell() {
DCHECK(!g_shell);
base::Thread::Options options;
options.message_pump_factory = base::Bind(&CreateMessagePumpMojo);
gpu_thread_.reset(new base::Thread("gpu_thread"));
gpu_thread_->StartWithOptions(options);
ui_thread_.reset(new base::Thread("ui_thread"));
ui_thread_->StartWithOptions(options);
io_thread_.reset(new base::Thread("io_thread"));
io_thread_->StartWithOptions(options);
blink::Threads threads(ftl::MakeRefCounted<glue::TaskRunnerAdaptor>(
gpu_thread_->message_loop()->task_runner()),
ftl::MakeRefCounted<glue::TaskRunnerAdaptor>(
ui_thread_->message_loop()->task_runner()),
ftl::MakeRefCounted<glue::TaskRunnerAdaptor>(
io_thread_->message_loop()->task_runner()));
blink::Threads::Set(threads);
blink::Threads::Gpu()->PostTask([this]() { InitGpuThread(); });
blink::Threads::UI()->PostTask([this]() { InitUIThread(); });
blink::SetServiceIsolateHook(ServiceIsolateHook);
blink::SetRegisterNativeServiceProtocolExtensionHook(
PlatformViewServiceProtocol::RegisterHook);
}
Shell::~Shell() {}
void Shell::InitStandalone(std::string icu_data_path) {
TRACE_EVENT0("flutter", "Shell::InitStandalone");
ftl::UniqueFD icu_fd(
icu_data_path.empty() ? -1 : HANDLE_EINTR(::open(icu_data_path.c_str(),
O_RDONLY)));
if (icu_fd.get() == -1) {
// If the embedder did not specify a valid file, fallback to looking through
// internal search paths.
FTL_CHECK(base::i18n::InitializeICU());
} else {
FTL_CHECK(base::i18n::InitializeICUWithFileDescriptor(
icu_fd.get(), base::MemoryMappedFile::Region::kWholeFile));
icu_fd.reset();
}
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
blink::Settings settings;
// Enable Observatory
settings.enable_observatory =
!command_line.HasSwitch(switches::kDisableObservatory);
// Set Observatory Port
if (command_line.HasSwitch(switches::kDeviceObservatoryPort)) {
auto port_string =
command_line.GetSwitchValueASCII(switches::kDeviceObservatoryPort);
std::stringstream stream(port_string);
uint32_t port = 0;
if (stream >> port) {
settings.observatory_port = port;
} else {
FTL_LOG(INFO)
<< "Observatory port specified was malformed. Will default to "
<< settings.observatory_port;
}
}
settings.start_paused = command_line.HasSwitch(switches::kStartPaused);
settings.endless_trace_buffer =
command_line.HasSwitch(switches::kEndlessTraceBuffer);
settings.trace_startup = command_line.HasSwitch(switches::kTraceStartup);
settings.aot_snapshot_path =
command_line.GetSwitchValueASCII(switches::kAotSnapshotPath);
settings.aot_isolate_snapshot_file_name =
command_line.GetSwitchValueASCII(switches::kAotIsolateSnapshot);
settings.aot_vm_isolate_snapshot_file_name =
command_line.GetSwitchValueASCII(switches::kAotVmIsolateSnapshot);
settings.aot_instructions_blob_file_name =
command_line.GetSwitchValueASCII(switches::kAotInstructionsBlob);
settings.aot_rodata_blob_file_name =
command_line.GetSwitchValueASCII(switches::kAotRodataBlob);
settings.temp_directory_path =
command_line.GetSwitchValueASCII(switches::kCacheDirPath);
if (command_line.HasSwitch(switches::kDartFlags)) {
std::stringstream stream(
command_line.GetSwitchValueNative(switches::kDartFlags));
std::istream_iterator<std::string> end;
for (std::istream_iterator<std::string> it(stream); it != end; ++it)
settings.dart_flags.push_back(*it);
}
blink::Settings::Set(settings);
Init();
}
void Shell::Init() {
base::DiscardableMemoryAllocator::SetInstance(&g_discardable.Get());
#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE
InitSkiaEventTracer();
#endif
FTL_DCHECK(!g_shell);
g_shell = new Shell();
blink::Threads::UI()->PostTask(Engine::Init);
}
Shell& Shell::Shared() {
FTL_DCHECK(g_shell);
return *g_shell;
}
TracingController& Shell::tracing_controller() {
return tracing_controller_;
}
void Shell::InitGpuThread() {
gpu_thread_checker_.reset(new base::ThreadChecker());
}
void Shell::InitUIThread() {
ui_thread_checker_.reset(new base::ThreadChecker());
}
void Shell::AddRasterizer(const ftl::WeakPtr<Rasterizer>& rasterizer) {
FTL_DCHECK(gpu_thread_checker_ && gpu_thread_checker_->CalledOnValidThread());
rasterizers_.push_back(rasterizer);
}
void Shell::PurgeRasterizers() {
FTL_DCHECK(gpu_thread_checker_ && gpu_thread_checker_->CalledOnValidThread());
rasterizers_.erase(
std::remove_if(rasterizers_.begin(), rasterizers_.end(), IsInvalid),
rasterizers_.end());
}
void Shell::GetRasterizers(std::vector<ftl::WeakPtr<Rasterizer>>* rasterizers) {
FTL_DCHECK(gpu_thread_checker_ && gpu_thread_checker_->CalledOnValidThread());
*rasterizers = rasterizers_;
}
void Shell::AddPlatformView(const ftl::WeakPtr<PlatformView>& platform_view) {
FTL_DCHECK(ui_thread_checker_ && ui_thread_checker_->CalledOnValidThread());
if (platform_view) {
platform_views_.push_back(platform_view);
}
}
void Shell::PurgePlatformViews() {
FTL_DCHECK(ui_thread_checker_ && ui_thread_checker_->CalledOnValidThread());
platform_views_.erase(std::remove_if(platform_views_.begin(),
platform_views_.end(), IsViewInvalid),
platform_views_.end());
}
void Shell::GetPlatformViews(
std::vector<ftl::WeakPtr<PlatformView>>* platform_views) {
FTL_DCHECK(ui_thread_checker_ && ui_thread_checker_->CalledOnValidThread());
*platform_views = platform_views_;
}
void Shell::WaitForPlatformViewIds(
std::vector<PlatformViewInfo>* platform_view_ids) {
ftl::AutoResetWaitableEvent latch;
blink::Threads::UI()->PostTask([this, platform_view_ids, &latch]() {
WaitForPlatformViewsIdsUIThread(platform_view_ids, &latch);
});
latch.Wait();
}
void Shell::WaitForPlatformViewsIdsUIThread(
std::vector<PlatformViewInfo>* platform_view_ids,
ftl::AutoResetWaitableEvent* latch) {
std::vector<ftl::WeakPtr<PlatformView>> platform_views;
GetPlatformViews(&platform_views);
for (auto it = platform_views.begin(); it != platform_views.end(); it++) {
PlatformView* view = it->get();
if (!view) {
// Skip dead views.
continue;
}
PlatformViewInfo info;
info.view_id = reinterpret_cast<uintptr_t>(view);
info.isolate_id = view->engine().GetUIIsolateMainPort();
info.isolate_name = view->engine().GetUIIsolateName();
platform_view_ids->push_back(info);
}
latch->Signal();
}
void Shell::RunInPlatformView(uintptr_t view_id,
const char* main_script,
const char* packages_file,
const char* asset_directory,
bool* view_existed,
int64_t* dart_isolate_id,
std::string* isolate_name) {
ftl::AutoResetWaitableEvent latch;
FTL_DCHECK(view_id != 0);
FTL_DCHECK(main_script);
FTL_DCHECK(packages_file);
FTL_DCHECK(asset_directory);
FTL_DCHECK(view_existed);
blink::Threads::UI()->PostTask([this, view_id, main_script, packages_file,
asset_directory, view_existed,
dart_isolate_id, isolate_name, &latch]() {
RunInPlatformViewUIThread(view_id, main_script, packages_file,
asset_directory, view_existed, dart_isolate_id,
isolate_name, &latch);
});
latch.Wait();
}
void Shell::RunInPlatformViewUIThread(uintptr_t view_id,
const std::string& main,
const std::string& packages,
const std::string& assets_directory,
bool* view_existed,
int64_t* dart_isolate_id,
std::string* isolate_name,
ftl::AutoResetWaitableEvent* latch) {
FTL_DCHECK(ui_thread_checker_ && ui_thread_checker_->CalledOnValidThread());
*view_existed = false;
for (auto it = platform_views_.begin(); it != platform_views_.end(); it++) {
PlatformView* view = it->get();
if (reinterpret_cast<uintptr_t>(view) == view_id) {
*view_existed = true;
view->RunFromSource(main, packages, assets_directory);
*dart_isolate_id = view->engine().GetUIIsolateMainPort();
*isolate_name = view->engine().GetUIIsolateName();
break;
}
}
latch->Signal();
}
} // namespace shell

View File

@@ -0,0 +1,105 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_SHELL_H_
#define SHELL_COMMON_SHELL_H_
#include "base/threading/thread.h"
#include "flutter/shell/common/tracing_controller.h"
#include "lib/ftl/macros.h"
#include "lib/ftl/memory/ref_ptr.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "lib/ftl/synchronization/waitable_event.h"
#include "lib/ftl/tasks/task_runner.h"
namespace shell {
class PlatformView;
class Rasterizer;
class Shell {
public:
~Shell();
// Init the shell to stand alone from MojoShell.
static void InitStandalone(std::string icu_data_path = "");
// Init the shell to run inside MojoShell.
static void Init();
static Shell& Shared();
TracingController& tracing_controller();
// Maintain a list of rasterizers.
// These APIs must only be accessed on the GPU thread.
void AddRasterizer(const ftl::WeakPtr<Rasterizer>& rasterizer);
void PurgeRasterizers();
void GetRasterizers(std::vector<ftl::WeakPtr<Rasterizer>>* rasterizer);
// List of PlatformViews.
// These APIs must only be accessed on UI thread.
void AddPlatformView(const ftl::WeakPtr<PlatformView>& platform_view);
void PurgePlatformViews();
void GetPlatformViews(
std::vector<ftl::WeakPtr<PlatformView>>* platform_views);
struct PlatformViewInfo {
uintptr_t view_id;
int64_t isolate_id;
std::string isolate_name;
};
// These APIs can be called from any thread.
// Return the list of platform view ids at the time of this call.
void WaitForPlatformViewIds(std::vector<PlatformViewInfo>* platform_view_ids);
// Attempt to run a script inside a flutter view indicated by |view_id|.
// Will set |view_existed| to true if the view was found and false otherwise.
void RunInPlatformView(uintptr_t view_id,
const char* main_script,
const char* packages_file,
const char* asset_directory,
bool* view_existed,
int64_t* dart_isolate_id,
std::string* isolate_name);
private:
Shell();
void InitGpuThread();
void InitUIThread();
void WaitForPlatformViewsIdsUIThread(
std::vector<PlatformViewInfo>* platform_views,
ftl::AutoResetWaitableEvent* latch);
void RunInPlatformViewUIThread(uintptr_t view_id,
const std::string& main,
const std::string& packages,
const std::string& assets_directory,
bool* view_existed,
int64_t* dart_isolate_id,
std::string* isolate_name,
ftl::AutoResetWaitableEvent* latch);
std::unique_ptr<base::Thread> gpu_thread_;
std::unique_ptr<base::Thread> ui_thread_;
std::unique_ptr<base::Thread> io_thread_;
std::unique_ptr<base::ThreadChecker> gpu_thread_checker_;
std::unique_ptr<base::ThreadChecker> ui_thread_checker_;
TracingController tracing_controller_;
std::vector<ftl::WeakPtr<Rasterizer>> rasterizers_;
std::vector<ftl::WeakPtr<PlatformView>> platform_views_;
FTL_DISALLOW_COPY_AND_ASSIGN(Shell);
};
} // namespace shell
#endif // SHELL_COMMON_SHELL_H_

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/switches.h"
#include <iostream>
namespace shell {
namespace switches {
const char kAotInstructionsBlob[] = "instructions-blob";
const char kAotIsolateSnapshot[] = "isolate-snapshot";
const char kAotRodataBlob[] = "rodata-blob";
const char kAotSnapshotPath[] = "aot-snapshot-path";
const char kAotVmIsolateSnapshot[] = "vm-isolate-snapshot";
const char kCacheDirPath[] = "cache-dir-path";
const char kDartFlags[] = "dart-flags";
const char kDeviceObservatoryPort[] = "observatory-port";
const char kDisableObservatory[] = "disable-observatory";
const char kEndlessTraceBuffer[] = "endless-trace-buffer";
const char kFLX[] = "flx";
const char kHelp[] = "help";
const char kMainDartFile[] = "dart-main";
const char kNonInteractive[] = "non-interactive";
const char kNoRedirectToSyslog[] = "no-redirect-to-syslog";
const char kPackages[] = "packages";
const char kStartPaused[] = "start-paused";
const char kTraceStartup[] = "trace-startup";
void PrintUsage(const std::string& executable_name) {
// clang-format off
std::cerr << "Usage: " << executable_name
<< " --" << kNonInteractive
<< " --" << kStartPaused
<< " --" << kTraceStartup
<< " --" << kFLX << "=FLX"
<< " --" << kPackages << "=PACKAGES"
<< " --" << kDeviceObservatoryPort << "=8181"
<< " [ MAIN_DART ]" << std::endl;
// clang-format on
}
} // namespace switches
} // namespace shell

View File

@@ -0,0 +1,37 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_SWITCHES_H_
#define SHELL_COMMON_SWITCHES_H_
#include <string>
namespace shell {
namespace switches {
extern const char kAotInstructionsBlob[];
extern const char kAotIsolateSnapshot[];
extern const char kAotRodataBlob[];
extern const char kAotSnapshotPath[];
extern const char kAotVmIsolateSnapshot[];
extern const char kCacheDirPath[];
extern const char kDartFlags[];
extern const char kDeviceObservatoryPort[];
extern const char kDisableObservatory[];
extern const char kEndlessTraceBuffer[];
extern const char kFLX[];
extern const char kHelp[];
extern const char kMainDartFile[];
extern const char kNonInteractive[];
extern const char kNoRedirectToSyslog[];
extern const char kPackages[];
extern const char kStartPaused[];
extern const char kTraceStartup[];
void PrintUsage(const std::string& executable_name);
} // namespace switches
} // namespace shell
#endif // SHELL_COMMON_SWITCHES_H_

View File

@@ -0,0 +1,55 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/systrace_logger.h"
#include "lib/ftl/files/eintr_wrapper.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
namespace shell {
static const int kBufferSize = 256;
SystraceLogger::SystraceLogger()
: trace_fd_(HANDLE_EINTR(
::open("/sys/kernel/debug/tracing/trace_marker", O_WRONLY))),
pid_(getpid()) {}
SystraceLogger::~SystraceLogger() {
IGNORE_EINTR(::close(trace_fd_));
}
void SystraceLogger::TraceBegin(const char* label) const {
char buffer[kBufferSize];
int buffer_written = snprintf(buffer, sizeof(buffer), "B|%d|%s", pid_, label);
if (buffer_written <= 0 || buffer_written > kBufferSize) {
return;
}
HANDLE_EINTR(::write(trace_fd_, buffer, buffer_written));
}
void SystraceLogger::TraceEnd() const {
HANDLE_EINTR(::write(trace_fd_, "E", 1));
}
void SystraceLogger::TraceCount(const char* label, int count) const {
char buffer[kBufferSize];
int buffer_written =
snprintf(buffer, sizeof(buffer), "C|%d|%s|%d", pid_, label, count);
if (buffer_written <= 0 || buffer_written > kBufferSize) {
return;
}
HANDLE_EINTR(::write(trace_fd_, buffer, buffer_written));
}
} // namespace shell

View File

@@ -0,0 +1,35 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_SYSTRACE_LOGGER_H_
#define SHELL_COMMON_SYSTRACE_LOGGER_H_
#include "lib/ftl/macros.h"
#include <sys/types.h>
namespace shell {
class SystraceLogger {
public:
SystraceLogger();
~SystraceLogger();
void TraceBegin(const char* label) const;
void TraceEnd() const;
void TraceCount(const char* label, int count) const;
private:
int trace_fd_;
int pid_;
FTL_DISALLOW_COPY_AND_ASSIGN(SystraceLogger);
};
} // namespace shell
#endif // SHELL_COMMON_SYSTRACE_LOGGER_H_

View File

@@ -0,0 +1,212 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/tracing_controller.h"
#include <string>
#include "base/trace_event/trace_event.h"
#include "dart/runtime/include/dart_tools_api.h"
#include "flutter/common/threads.h"
#include "flutter/runtime/dart_init.h"
#include "flutter/shell/common/shell.h"
#include "lib/ftl/logging.h"
namespace shell {
TracingController::TracingController()
: picture_tracing_enabled_(false), tracing_active_(false) {
blink::SetEmbedderTracingCallbacks(
std::unique_ptr<blink::EmbedderTracingCallbacks>(
new blink::EmbedderTracingCallbacks([this]() { StartTracing(); },
[this]() { StopTracing(); })));
}
TracingController::~TracingController() {
blink::SetEmbedderTracingCallbacks(nullptr);
}
static const char* WARN_UNUSED_RESULT
ConstructDartTimelineValue(std::vector<void*>& free_list,
const char* format,
...) {
static const char* kConversionError = "Argument Conversion Error";
const char* return_value = nullptr;
va_list args;
va_start(args, format);
char* string;
if (vasprintf(&string, format, args) != -1) {
return_value = string;
free_list.push_back(string);
} else {
return_value = kConversionError;
}
va_end(args);
return return_value;
}
static void BaseTraceEventCallback(base::TraceTicks timestamp,
char phase,
const unsigned char* category_group_enabled,
const char* name,
unsigned long long id,
int num_args,
const char* const arg_names[],
const unsigned char arg_types[],
const unsigned long long arg_values[],
unsigned int flags) {
Dart_Timeline_Event_Type type = Dart_Timeline_Event_Begin;
switch (phase) {
case TRACE_EVENT_PHASE_BEGIN:
type = Dart_Timeline_Event_Begin;
break;
case TRACE_EVENT_PHASE_END:
type = Dart_Timeline_Event_End;
break;
case TRACE_EVENT_PHASE_INSTANT:
type = Dart_Timeline_Event_Instant;
break;
case TRACE_EVENT_PHASE_ASYNC_BEGIN:
type = Dart_Timeline_Event_Async_Begin;
break;
case TRACE_EVENT_PHASE_ASYNC_END:
type = Dart_Timeline_Event_Async_End;
break;
case TRACE_EVENT_PHASE_COUNTER:
type = Dart_Timeline_Event_Counter;
break;
default:
// For TRACE_EVENT_PHASE_COMPLETE events, this callback still receives
// discrete begin-end pairs. This greatly simplifies things. We dont have
// to track the second timestamp to pass to the Dart timeline event
// because we never see a Dart_Timeline_Event_Duration event.
FTL_DCHECK(false) << "Unknown trace event phase";
return;
}
// Try to convert all arguments to strings to pass to the Dart timeline.
char const* dart_argument_values[num_args];
std::vector<void*> free_list;
#define CONVERT_VAL(format) \
dart_argument_values[i] = \
ConstructDartTimelineValue(free_list, format, arg_values[i])
for (int i = 0; i < num_args; i++) {
switch (arg_types[i]) {
case TRACE_VALUE_TYPE_BOOL:
CONVERT_VAL("%d");
break;
case TRACE_VALUE_TYPE_UINT:
CONVERT_VAL("%u");
break;
case TRACE_VALUE_TYPE_INT:
CONVERT_VAL("%d");
break;
case TRACE_VALUE_TYPE_DOUBLE:
CONVERT_VAL("%f");
break;
case TRACE_VALUE_TYPE_POINTER:
CONVERT_VAL("%p");
break;
case TRACE_VALUE_TYPE_STRING:
case TRACE_VALUE_TYPE_COPY_STRING:
// We don't need to reallocate for strings since the string will be
// used within this scope.
dart_argument_values[i] = reinterpret_cast<char*>(arg_values[i]);
break;
default:
continue;
}
}
#undef CONVERT_VAL
Dart_TimelineEvent(name, // label
timestamp.ToInternalValue(), // timestamp0
0, // timestamp1_or_async_id
type, // event type
num_args, // argument_count
(const char**)(arg_names), // argument_names
(const char**)(dart_argument_values) // argument_values
);
// Free up the items that had to be heap allocated (if any)
for (void* item : free_list) {
free(item);
}
}
static void AddTraceMetadata() {
blink::Threads::Gpu()->PostTask([]() { Dart_SetThreadName("gpu_thread"); });
blink::Threads::UI()->PostTask([]() { Dart_SetThreadName("ui_thread"); });
blink::Threads::IO()->PostTask([]() { Dart_SetThreadName("io_thread"); });
}
void TracingController::StartTracing() {
if (tracing_active_)
return;
tracing_active_ = true;
StartBaseTracing();
AddTraceMetadata();
}
void TracingController::StartBaseTracing() {
auto config = base::trace_event::TraceConfig(
"*,disabled-by-default-skia", base::trace_event::RECORD_CONTINUOUSLY);
auto log = base::trace_event::TraceLog::GetInstance();
log->SetEnabled(config, base::trace_event::TraceLog::MONITORING_MODE);
log->SetEventCallbackEnabled(config, &BaseTraceEventCallback);
}
void TracingController::StopTracing() {
if (!tracing_active_) {
return;
}
tracing_active_ = false;
StopBaseTracing();
}
void TracingController::StopBaseTracing() {
auto trace_log = base::trace_event::TraceLog::GetInstance();
trace_log->SetDisabled();
trace_log->SetEventCallbackDisabled();
}
std::string TracingController::TracePathWithExtension(
const std::string& directory,
const std::string& extension) const {
base::Time::Exploded exploded;
base::Time now = base::Time::Now();
now.LocalExplode(&exploded);
std::stringstream stream;
// Example: trace_2015-10-08_at_11.38.25.121_.extension
stream << directory << "/trace_" << exploded.year << "-" << exploded.month
<< "-" << exploded.day_of_month << "_at_" << exploded.hour << "."
<< exploded.minute << "." << exploded.second << "."
<< exploded.millisecond << "." << extension;
return stream.str();
}
std::string TracingController::PictureTracingPathForCurrentTime() const {
return PictureTracingPathForCurrentTime(traces_base_path_);
}
std::string TracingController::PictureTracingPathForCurrentTime(
const std::string& directory) const {
return TracePathWithExtension(directory, "skp");
}
} // namespace shell

View File

@@ -0,0 +1,60 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_TRACING_CONTROLLER_H_
#define SHELL_COMMON_TRACING_CONTROLLER_H_
#include <string>
#include "lib/ftl/macros.h"
namespace shell {
class TracingController {
public:
TracingController();
~TracingController();
void StartTracing();
void StopTracing();
// Enables tracing in base. Only use this if an instance of a tracing
// controller cannot be obtained (can happen early in the lifecycle of the
// process). In most cases, the |StartTracing| method on an instance of the
// tracing controller should be used.
static void StartBaseTracing();
std::string PictureTracingPathForCurrentTime() const;
std::string PictureTracingPathForCurrentTime(
const std::string& directory) const;
bool tracing_active() const { return tracing_active_; }
void set_traces_base_path(std::string base_path) {
traces_base_path_ = std::move(base_path);
}
void set_picture_tracing_enabled(bool enabled) {
picture_tracing_enabled_ = enabled;
}
bool picture_tracing_enabled() const { return picture_tracing_enabled_; }
private:
std::string traces_base_path_;
bool picture_tracing_enabled_;
bool tracing_active_;
void StopBaseTracing();
std::string TracePathWithExtension(const std::string& directory,
const std::string& extension) const;
FTL_DISALLOW_COPY_AND_ASSIGN(TracingController);
};
} // namespace shell
#endif // SHELL_COMMON_TRACING_CONTROLLER_H_

View File

@@ -0,0 +1,11 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/ui_delegate.h"
namespace shell {
UIDelegate::~UIDelegate() = default;
} // namespace shell

View File

@@ -0,0 +1,30 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_DELEGATE_H_
#define SHELL_COMMON_DELEGATE_H_
#include "flutter/services/engine/sky_engine.mojom.h"
#include "lib/ftl/functional/closure.h"
#include "mojo/public/cpp/bindings/interface_request.h"
namespace shell {
class UIDelegate {
public:
virtual void ConnectToEngine(
mojo::InterfaceRequest<sky::SkyEngine> request) = 0;
virtual void OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) = 0;
virtual void OnOutputSurfaceDestroyed(
const ftl::Closure& gpu_continuation) = 0;
protected:
virtual ~UIDelegate();
};
} // namespace shell
#endif // SHELL_COMMON_DELEGATE_H_

View File

@@ -0,0 +1,28 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
source_set("gpu") {
sources = [
"ganesh_canvas.cc",
"ganesh_canvas.h",
"gpu_canvas.cc",
"gpu_canvas.h",
"gpu_canvas_gl.cc",
"gpu_canvas_gl.h",
"gpu_canvas_vulkan.cc",
"gpu_canvas_vulkan.h",
"gpu_rasterizer.cc",
"gpu_rasterizer.h",
]
deps = [
"../common",
"//lib/ftl",
"//flutter/skia",
"//flutter/flow",
"//flutter/common",
"//flutter/glue",
"//mojo/public/cpp/system",
]
}

View File

@@ -0,0 +1,89 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/gpu/ganesh_canvas.h"
#include "flutter/flow/gl_connection.h"
#include "lib/ftl/arraysize.h"
#include "lib/ftl/logging.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace shell {
namespace {
// The limit of the number of GPU resources we hold in the GrContext's
// GPU cache.
const int kMaxGaneshResourceCacheCount = 2048;
// The limit of the bytes allocated toward GPU resources in the GrContext's
// GPU cache.
const size_t kMaxGaneshResourceCacheBytes = 96 * 1024 * 1024;
} // namespace
GaneshCanvas::GaneshCanvas() {}
GaneshCanvas::~GaneshCanvas() {}
bool GaneshCanvas::SetupGrGLInterface() {
sk_surface_ = nullptr;
gr_context_ = sk_sp<GrContext>(GrContext::Create(
kOpenGL_GrBackend,
reinterpret_cast<GrBackendContext>(GrGLCreateNativeInterface())));
if (gr_context_ == nullptr) {
flow::GLConnection connection;
FTL_LOG(INFO) << "Failed to setup GL context. Aborting.";
FTL_LOG(INFO) << connection.Description();
}
if (!gr_context_)
return false;
gr_context_->setResourceCacheLimits(kMaxGaneshResourceCacheCount,
kMaxGaneshResourceCacheBytes);
return true;
}
bool GaneshCanvas::SelectPixelConfig(GrPixelConfig* config) {
static const GrPixelConfig kConfigOptions[] = {
kSkia8888_GrPixelConfig, kRGBA_4444_GrPixelConfig,
};
for (size_t i = 0; i < arraysize(kConfigOptions); i++) {
if (gr_context_->caps()->isConfigRenderable(kConfigOptions[i], false)) {
*config = kConfigOptions[i];
return true;
}
}
return false;
}
SkCanvas* GaneshCanvas::GetCanvas(int32_t fbo, const SkISize& size) {
FTL_DCHECK(IsValid());
if (sk_surface_ && sk_surface_->width() == size.width() &&
sk_surface_->height() == size.height())
return sk_surface_->getCanvas();
GrBackendRenderTargetDesc desc;
desc.fWidth = size.width();
desc.fHeight = size.height();
FTL_CHECK(SelectPixelConfig(&desc.fConfig));
desc.fStencilBits = 8;
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
desc.fRenderTargetHandle = fbo;
sk_surface_ =
SkSurface::MakeFromBackendRenderTarget(gr_context_.get(), desc, nullptr);
FTL_DCHECK(sk_surface_);
return sk_surface_->getCanvas();
}
bool GaneshCanvas::IsValid() {
return gr_context_;
}
} // namespace shell

View File

@@ -0,0 +1,41 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_DIRECT_GANESH_CANVAS_H_
#define SHELL_GPU_DIRECT_GANESH_CANVAS_H_
#include "lib/ftl/macros.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace shell {
class GaneshCanvas {
public:
GaneshCanvas();
~GaneshCanvas();
bool SetupGrGLInterface();
SkCanvas* GetCanvas(int32_t fbo, const SkISize& size);
bool IsValid();
GrContext* gr_context() { return gr_context_.get(); }
private:
bool SelectPixelConfig(GrPixelConfig* config);
sk_sp<GrContext> gr_context_;
sk_sp<SkSurface> sk_surface_;
FTL_DISALLOW_COPY_AND_ASSIGN(GaneshCanvas);
};
} // namespace shell
#endif // SHELL_GPU_DIRECT_GANESH_CANVAS_H_

View File

@@ -0,0 +1,11 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu_canvas.h"
namespace shell {
//
} // namespace shell

View File

@@ -0,0 +1,16 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_GPU_CANVAS_H_
#define SHELL_GPU_GPU_CANVAS_H_
#include "lib/ftl/macros.h"
namespace shell {
//
} // namespace shell
#endif // SHELL_GPU_GPU_CANVAS_H_

View File

@@ -0,0 +1,11 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu_canvas_gl.h"
namespace shell {
//
} // namespace shell

View File

@@ -0,0 +1,16 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_GPU_CANVAS_GL_H_
#define SHELL_GPU_GPU_CANVAS_GL_H_
#include "lib/ftl/macros.h"
namespace shell {
//
} // namespace shell
#endif // SHELL_GPU_GPU_CANVAS_GL_H_

View File

@@ -0,0 +1,11 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu_canvas_vulkan.h"
namespace shell {
//
} // namespace shell

View File

@@ -0,0 +1,16 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_GPU_CANVAS_VULKAN_H_
#define SHELL_GPU_GPU_CANVAS_VULKAN_H_
#include "lib/ftl/macros.h"
namespace shell {
//
} // namespace shell
#endif // SHELL_GPU_GPU_CANVAS_VULKAN_H_

View File

@@ -0,0 +1,184 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu_rasterizer.h"
#include <string>
#include <utility>
#include "flutter/common/threads.h"
#include "flutter/glue/trace_event.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/picture_serializer.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace shell {
GPURasterizer::GPURasterizer() : platform_view_(nullptr), weak_factory_(this) {
auto weak_ptr = weak_factory_.GetWeakPtr();
blink::Threads::Gpu()->PostTask(
[weak_ptr]() { Shell::Shared().AddRasterizer(weak_ptr); });
}
GPURasterizer::~GPURasterizer() {
weak_factory_.InvalidateWeakPtrs();
Shell::Shared().PurgeRasterizers();
}
std::unique_ptr<Rasterizer> Rasterizer::Create() {
return std::unique_ptr<GPURasterizer>(new GPURasterizer());
}
ftl::WeakPtr<Rasterizer> GPURasterizer::GetWeakRasterizerPtr() {
return weak_factory_.GetWeakPtr();
}
void GPURasterizer::Setup(PlatformView* platform_view,
ftl::Closure continuation,
ftl::AutoResetWaitableEvent* setup_completion_event) {
FTL_CHECK(platform_view) << "Must be able to acquire the view.";
// The context needs to be made current before the GrGL interface can be
// setup.
bool success = platform_view->ContextMakeCurrent();
if (success) {
success = ganesh_canvas_.SetupGrGLInterface();
if (!success)
FTL_LOG(ERROR) << "Could not create the GL interface";
} else {
FTL_LOG(ERROR) << "Could not make the context current for initial GL setup";
}
if (success) {
platform_view_ = platform_view;
} else {
FTL_LOG(ERROR)
<< "WARNING: Flutter will be unable to render to the display";
}
continuation();
setup_completion_event->Signal();
}
void GPURasterizer::Clear(SkColor color) {
SkCanvas* canvas = ganesh_canvas_.GetCanvas(
platform_view_->DefaultFramebuffer(), platform_view_->GetSize());
canvas->clear(color);
canvas->flush();
platform_view_->SwapBuffers();
}
void GPURasterizer::Teardown(
ftl::AutoResetWaitableEvent* teardown_completion_event) {
platform_view_ = nullptr;
last_layer_tree_.reset();
compositor_context_.OnGrContextDestroyed();
teardown_completion_event->Signal();
}
flow::LayerTree* GPURasterizer::GetLastLayerTree() {
return last_layer_tree_.get();
}
void GPURasterizer::Draw(
ftl::RefPtr<flutter::Pipeline<flow::LayerTree>> pipeline) {
TRACE_EVENT0("flutter", "GPURasterizer::Draw");
if (!platform_view_)
return;
flutter::Pipeline<flow::LayerTree>::Consumer consumer =
std::bind(&GPURasterizer::DoDraw, this, std::placeholders::_1);
// Consume as many pipeline items as possible. But yield the event loop
// between successive tries.
switch (pipeline->Consume(consumer)) {
case flutter::PipelineConsumeResult::MoreAvailable: {
auto weak_this = weak_factory_.GetWeakPtr();
blink::Threads::Gpu()->PostTask([weak_this, pipeline]() {
if (weak_this) {
weak_this->Draw(pipeline);
}
});
break;
}
default:
break;
}
}
void GPURasterizer::DoDraw(std::unique_ptr<flow::LayerTree> layer_tree) {
if (!layer_tree) {
return;
}
// There is no way for the compositor to know how long the layer tree
// construction took. Fortunately, the layer tree does. Grab that time
// for instrumentation.
compositor_context_.engine_time().SetLapTime(layer_tree->construction_time());
SkISize size = layer_tree->frame_size();
if (platform_view_->GetSize() != size) {
platform_view_->Resize(size);
}
if (!platform_view_->ContextMakeCurrent() || !layer_tree->root_layer()) {
return;
}
{
SkCanvas* canvas = ganesh_canvas_.GetCanvas(
platform_view_->DefaultFramebuffer(), layer_tree->frame_size());
flow::CompositorContext::ScopedFrame frame =
compositor_context_.AcquireFrame(ganesh_canvas_.gr_context(), *canvas);
canvas->clear(SK_ColorBLACK);
layer_tree->Raster(frame);
{
TRACE_EVENT0("flutter", "SkCanvas::Flush");
canvas->flush();
}
platform_view_->SwapBuffers();
}
// Trace to a file if necessary
static const double kOneFrameDuration = 1e3 / 60.0;
bool frameExceededThreshold = false;
uint32_t thresholdInterval = layer_tree->rasterizer_tracing_threshold();
if (thresholdInterval != 0 &&
compositor_context_.frame_time().LastLap().ToMillisecondsF() >
thresholdInterval * kOneFrameDuration) {
// While rendering the last frame, if we exceeded the tracing threshold
// specified in the layer tree, we force a trace to disk.
frameExceededThreshold = true;
}
const auto& tracingController = Shell::Shared().tracing_controller();
if (frameExceededThreshold || tracingController.picture_tracing_enabled()) {
std::string path = tracingController.PictureTracingPathForCurrentTime();
LOG(INFO) << "Frame threshold exceeded. Capturing SKP to " << path;
SkPictureRecorder recorder;
recorder.beginRecording(SkRect::MakeWH(size.width(), size.height()));
{
auto frame = compositor_context_.AcquireFrame(
nullptr, *recorder.getRecordingCanvas(), false);
layer_tree->Raster(frame, true);
}
sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture();
SerializePicture(path, picture.get());
}
last_layer_tree_ = std::move(layer_tree);
}
} // namespace shell

View File

@@ -0,0 +1,51 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_GPU_DIRECT_GPU_RASTERIZER_H_
#define SHELL_GPU_DIRECT_GPU_RASTERIZER_H_
#include "flutter/flow/compositor_context.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/gpu/ganesh_canvas.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "lib/ftl/synchronization/waitable_event.h"
namespace shell {
class GPURasterizer : public Rasterizer {
public:
GPURasterizer();
~GPURasterizer() override;
void Setup(PlatformView* platform_view,
ftl::Closure continuation,
ftl::AutoResetWaitableEvent* setup_completion_event) override;
void Clear(SkColor color) override;
void Teardown(
ftl::AutoResetWaitableEvent* teardown_completion_event) override;
ftl::WeakPtr<Rasterizer> GetWeakRasterizerPtr() override;
flow::LayerTree* GetLastLayerTree() override;
void Draw(ftl::RefPtr<flutter::Pipeline<flow::LayerTree>> pipeline) override;
private:
GaneshCanvas ganesh_canvas_;
flow::CompositorContext compositor_context_;
std::unique_ptr<flow::LayerTree> last_layer_tree_;
PlatformView* platform_view_;
ftl::WeakPtrFactory<GPURasterizer> weak_factory_;
void DoDraw(std::unique_ptr<flow::LayerTree> tree);
FTL_DISALLOW_COPY_AND_ASSIGN(GPURasterizer);
};
} // namespace shell
#endif // SHELL_GPU_DIRECT_GPU_RASTERIZER_H_

View File

@@ -0,0 +1,15 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
group("platform") {
if (is_mac || is_ios) {
deps = [ "darwin" ]
} else if (is_android) {
deps = [ "android" ]
} else if (is_linux) {
deps = [ "linux" ]
} else {
assert(false, "Unknown/Unsupported platform.")
}
}

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.domokit.sky.shell" android:versionCode="1" android:versionName="0.0.1">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<application android:label="Sky Shell" android:name="SkyApplication" android:debuggable="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:launchMode="standard"
android:name="SkyActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,127 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
generate_jni("jni_headers") {
visibility = [ ":*" ]
sources = [
"io/flutter/view/FlutterMain.java",
"io/flutter/view/FlutterView.java",
]
jni_package = "shell"
}
shared_library("sky_shell") {
visibility = [ ":*" ]
sources = [
"flutter_main.cc",
"flutter_main.h",
"library_loader.cc",
"platform_view_android.cc",
"platform_view_android.h",
]
deps = [
"//base",
"//dart/runtime:libdart",
"//flutter/common",
"//flutter/flow",
"//flutter/lib/jni",
"//flutter/runtime",
"//flutter/shell/common",
"//flutter/shell/gpu",
"//flutter/skia",
"//flutter/vulkan",
"//lib/ftl",
"//mojo/android:libsystem_java",
"//mojo/edk/base_edk",
"//mojo/edk/system",
":jni_headers",
]
ldflags = [
"-landroid",
"-lEGL",
"-lGLESv2",
]
}
android_library("java") {
visibility = [ ":*" ]
java_files = [
"io/flutter/view/AccessibilityBridge.java",
"io/flutter/view/FlutterMain.java",
"io/flutter/view/FlutterView.java",
"io/flutter/view/ResourceCleaner.java",
"io/flutter/view/ResourceExtractor.java",
"io/flutter/view/ServiceFactory.java",
"io/flutter/view/ServiceProviderImpl.java",
"io/flutter/view/ServiceRegistry.java",
"org/domokit/sky/shell/SkyActivity.java",
"org/domokit/sky/shell/SkyApplication.java",
]
deps = [
"//base:base_java",
"//flutter/services/activity:activity_lib",
"//flutter/services/activity:interfaces_java",
"//flutter/services/common:common_lib",
"//flutter/services/editing:editing_lib",
"//flutter/services/editing:interfaces_java",
"//flutter/services/engine:interfaces_java",
"//flutter/services/media:interfaces_java",
"//flutter/services/media:media_lib",
"//flutter/services/platform:interfaces_java",
"//flutter/services/platform:platform_lib",
"//flutter/services/pointer:interfaces_java",
"//flutter/services/raw_keyboard:interfaces_java",
"//flutter/services/raw_keyboard:raw_keyboard_lib",
"//flutter/services/semantics:interfaces_java",
"//flutter/services/sensors:sensors_lib",
"//flutter/services/vsync:vsync_lib",
"//mojo/android:system_java",
"//mojo/public/interfaces/application:application_java",
"//mojo/public/java:bindings",
"//mojo/public/java:system",
"//mojo/services/sensors/interfaces:interfaces_java",
"//mojo/services/vsync/interfaces:interfaces_java",
]
}
copy_ex("assets") {
visibility = [ ":*" ]
clear_dir = true
dest = "$root_build_dir/sky_shell/assets"
sources = [
"$root_build_dir/icudtl.dat",
]
deps = [
"//third_party/icu:icudata",
]
}
android_apk("android") {
apk_name = "SkyShell"
android_manifest = "AndroidManifest.xml"
native_libs = [ "libsky_shell.so" ]
asset_location = "$root_build_dir/sky_shell/assets"
extensions_to_not_compress = ".flx"
flutter_dist_jar = "$root_build_dir/flutter.jar"
deps = [
"//base:base_java",
":assets",
":java",
":sky_shell",
]
}

View File

@@ -0,0 +1,99 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/android/flutter_main.h"
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/threading/simple_thread.h"
#include "dart/runtime/include/dart_tools_api.h"
#include "flutter/runtime/start_up.h"
#include "flutter/shell/common/shell.h"
#include "jni/FlutterMain_jni.h"
#include "lib/ftl/macros.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
using base::LazyInstance;
namespace shell {
namespace {
LazyInstance<std::unique_ptr<base::MessageLoop>> g_java_message_loop =
LAZY_INSTANCE_INITIALIZER;
void InitializeLogging() {
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
logging::InitLogging(settings);
// To view log output with IDs and timestamps use "adb logcat -v threadtime".
logging::SetLogItems(false, // Process ID
false, // Thread ID
false, // Timestamp
false); // Tick count
}
void InitializeTracing() {
base::FilePath path;
bool result = ::PathService::Get(base::DIR_ANDROID_APP_DATA, &path);
DCHECK(result);
shell::Shell::Shared().tracing_controller().set_traces_base_path(
path.AsUTF8Unsafe());
}
} // namespace
static void Init(JNIEnv* env,
jclass clazz,
jobject context,
jobjectArray jargs) {
base::PlatformThread::SetName("java_ui_thread");
base::android::ScopedJavaLocalRef<jobject> scoped_context(env, context);
base::android::InitApplicationContext(env, scoped_context);
std::vector<std::string> args;
args.push_back("sky_shell");
base::android::AppendJavaStringArrayToStringVector(env, jargs, &args);
base::CommandLine::Init(0, nullptr);
base::CommandLine::ForCurrentProcess()->InitFromArgv(args);
InitializeLogging();
g_java_message_loop.Get().reset(new base::MessageLoopForUI);
base::MessageLoopForUI::current()->Start();
mojo::embedder::Init(mojo::embedder::CreateSimplePlatformSupport());
Shell::InitStandalone();
InitializeTracing();
}
static void RecordStartTimestamp(JNIEnv* env,
jclass jcaller,
jlong initTimeMillis) {
int64_t initTimeMicros =
static_cast<int64_t>(initTimeMillis) * static_cast<int64_t>(1000);
blink::engine_main_enter_ts = Dart_TimelineGetMicros() - initTimeMicros;
}
bool RegisterFlutterMain(JNIEnv* env) {
return RegisterNativesImpl(env);
}
} // namespace shell

View File

@@ -0,0 +1,16 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_
#define SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_
#include <jni.h>
namespace shell {
bool RegisterFlutterMain(JNIEnv* env);
} // namespace shell
#endif // SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_

View File

@@ -0,0 +1,502 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.graphics.Rect;
import android.opengl.Matrix;
import android.os.Bundle;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojom.semantics.SemanticAction;
import org.chromium.mojom.semantics.SemanticsListener;
import org.chromium.mojom.semantics.SemanticsNode;
import org.chromium.mojom.semantics.SemanticsServer;
import org.chromium.mojom.sky.ViewportMetrics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
class AccessibilityBridge extends AccessibilityNodeProvider implements SemanticsListener {
private Map<Integer, SemanticObject> mObjects;
private FlutterView mOwner;
private SemanticsServer.Proxy mSemanticsServer;
private boolean mAccessibilityEnabled = false;
private SemanticObject mFocusedObject;
private SemanticObject mHoveredObject;
AccessibilityBridge(FlutterView owner, SemanticsServer.Proxy semanticsServer) {
assert owner != null;
assert semanticsServer != null;
mOwner = owner;
mObjects = new HashMap<Integer, SemanticObject>();
mSemanticsServer = semanticsServer;
mSemanticsServer.addSemanticsListener(this);
}
void setAccessibilityEnabled(boolean accessibilityEnabled) {
mAccessibilityEnabled = accessibilityEnabled;
}
@Override
public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) {
if (virtualViewId == View.NO_ID) {
AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner);
mOwner.onInitializeAccessibilityNodeInfo(result);
if (mObjects.containsKey(0))
result.addChild(mOwner, 0);
return result;
}
SemanticObject object = mObjects.get(virtualViewId);
if (object == null)
return null;
AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId);
result.setPackageName(mOwner.getContext().getPackageName());
result.setClassName("Flutter"); // Prettier than the more conventional node.getClass().getName()
result.setSource(mOwner, virtualViewId);
if (object.parent != null) {
assert object.id > 0;
result.setParent(mOwner, object.parent.id);
} else {
assert object.id == 0;
result.setParent(mOwner);
}
Rect bounds = object.getGlobalRect();
if (object.parent != null) {
Rect parentBounds = object.parent.getGlobalRect();
Rect boundsInParent = new Rect(bounds);
boundsInParent.offset(-parentBounds.left, -parentBounds.top);
result.setBoundsInParent(boundsInParent);
} else {
result.setBoundsInParent(bounds);
}
result.setBoundsInScreen(bounds);
result.setVisibleToUser(true);
result.setEnabled(true); // TODO(ianh): Expose disabled subtrees
if (object.canBeTapped) {
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK);
result.setClickable(true);
}
if (object.canBeLongPressed) {
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_LONG_CLICK);
result.setLongClickable(true);
}
if (object.canBeScrolledHorizontally || object.canBeScrolledVertically) {
// TODO(ianh): Once we're on SDK v23+, call addAction to
// expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT,
// _UP, and _DOWN when appropriate.
// TODO(ianh): Only include the actions if you can actually scroll that way.
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
result.setScrollable(true);
}
result.setCheckable(object.hasCheckedState);
result.setChecked(object.isChecked);
result.setText(object.label);
// TODO(ianh): use setTraversalBefore/setTraversalAfter to set
// the relative order of the views. For each set of siblings,
// the views should be ordered top-to-bottom, tie-breaking
// left-to-right (right-to-left in rtl environments), height,
// width, and finally by list order.
// Accessibility Focus
if (mFocusedObject != null && mFocusedObject.id == virtualViewId) {
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
} else {
result.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS);
}
if (object.children != null) {
for (SemanticObject child : object.children) {
result.addChild(mOwner, child.id);
}
}
return result;
}
@Override
public boolean performAction(int virtualViewId, int action, Bundle arguments) {
SemanticObject object = mObjects.get(virtualViewId);
if (object == null) {
return false;
}
switch (action) {
case AccessibilityNodeInfo.ACTION_CLICK: {
mSemanticsServer.performAction(virtualViewId, SemanticAction.TAP);
return true;
}
case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
mSemanticsServer.performAction(virtualViewId, SemanticAction.LONG_PRESS);
return true;
}
case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
if (object.canBeScrolledVertically) {
mSemanticsServer.performAction(virtualViewId, SemanticAction.SCROLL_UP);
} else if (object.canBeScrolledHorizontally) {
// TODO(ianh): bidi support
mSemanticsServer.performAction(virtualViewId, SemanticAction.SCROLL_LEFT);
} else {
return false;
}
return true;
}
case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
if (object.canBeScrolledVertically) {
mSemanticsServer.performAction(virtualViewId, SemanticAction.SCROLL_DOWN);
} else if (object.canBeScrolledHorizontally) {
// TODO(ianh): bidi support
mSemanticsServer.performAction(virtualViewId, SemanticAction.SCROLL_RIGHT);
} else {
return false;
}
return true;
}
case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mFocusedObject = null;
return true;
}
case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
if (mFocusedObject == null) {
// When Android focuses a node, it doesn't invalidate the view.
// (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so
// we only have to worry about this when the focused node is null.)
mOwner.invalidate();
}
mFocusedObject = object;
return true;
}
}
return false;
}
// TODO(ianh): implement findAccessibilityNodeInfosByText()
// TODO(ianh): implement findFocus()
private SemanticObject getRootObject() {
return mObjects.get(0);
}
void handleTouchExplorationExit() {
if (mHoveredObject != null) {
sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
mHoveredObject = null;
}
}
void handleTouchExploration(float x, float y) {
if (mObjects.isEmpty()) {
return;
}
assert mObjects.containsKey(0);
SemanticObject newObject = getRootObject().hitTest(Math.round(x), Math.round(y));
if (newObject != mHoveredObject) {
// sending ENTER before EXIT is how Android wants it
if (newObject != null) {
sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
}
if (mHoveredObject != null) {
sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
}
mHoveredObject = newObject;
}
}
@Override
public void updateSemanticsTree(SemanticsNode[] nodes) {
Set<SemanticObject> updatedObjects = new HashSet<SemanticObject>();
Set<SemanticObject> removedObjects = new HashSet<SemanticObject>();
for (SemanticsNode node : nodes) {
updateSemanticObject(node, updatedObjects, removedObjects);
sendAccessibilityEvent(node.id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
for (SemanticObject object : removedObjects) {
if (!updatedObjects.contains(object)) {
removeSemanticObject(object, updatedObjects);
}
}
}
private SemanticObject updateSemanticObject(SemanticsNode node,
Set<SemanticObject> updatedObjects,
Set<SemanticObject> removedObjects) {
SemanticObject object = mObjects.get(node.id);
if (object == null) {
object = new SemanticObject();
mObjects.put(node.id, object);
}
object.updateWith(node);
updatedObjects.add(object);
if (node.children != null) {
if (node.children.length == 0) {
if (object.children != null) {
removedObjects.addAll(object.children);
}
object.children = null;
} else {
if (object.children == null) {
object.children = new ArrayList<SemanticObject>(node.children.length);
} else {
removedObjects.addAll(object.children);
object.children.clear();
}
for (SemanticsNode childNode : node.children) {
SemanticObject childObject = updateSemanticObject(childNode, updatedObjects, removedObjects);
childObject.parent = object;
object.children.add(childObject);
}
}
}
if (node.geometry != null) {
// has to be done after children are updated
// since they also get marked dirty
object.invalidateGlobalGeometry();
}
return object;
}
private void sendAccessibilityEvent(int virtualViewId, int eventType) {
if (!mAccessibilityEnabled) {
return;
}
if (virtualViewId == 0) {
mOwner.sendAccessibilityEvent(eventType);
} else {
AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
event.setPackageName(mOwner.getContext().getPackageName());
event.setSource(mOwner, virtualViewId);
mOwner.getParent().requestSendAccessibilityEvent(mOwner, event);
}
}
private void removeSemanticObject(SemanticObject object, Set<SemanticObject> updatedObjects) {
assert mObjects.containsKey(object.id);
assert mObjects.get(object.id) == object;
object.parent = null;
mObjects.remove(object.id);
if (mFocusedObject == object) {
sendAccessibilityEvent(mFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mFocusedObject = null;
}
if (mHoveredObject == object) {
mHoveredObject = null;
}
if (object.children != null) {
for (SemanticObject child : object.children) {
if (!updatedObjects.contains(child)) {
assert child.parent == object;
removeSemanticObject(child, updatedObjects);
}
}
}
}
void reset(SemanticsServer.Proxy newSemanticsServer) {
mObjects.clear();
sendAccessibilityEvent(mFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mFocusedObject = null;
mHoveredObject = null;
mSemanticsServer.close();
sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
mSemanticsServer = newSemanticsServer;
mSemanticsServer.addSemanticsListener(this);
}
private class SemanticObject {
SemanticObject() { }
void updateWith(SemanticsNode node) {
if (id == -1) {
id = node.id;
assert node.flags != null;
assert node.strings != null;
assert node.geometry != null;
assert node.children != null;
}
assert id == node.id;
if (node.flags != null) {
hasCheckedState = node.flags.hasCheckedState;
isChecked = node.flags.isChecked;
}
if (node.strings != null) {
label = node.strings.label;
}
if (node.geometry != null) {
transform = node.geometry.transform;
left = node.geometry.left;
top = node.geometry.top;
width = node.geometry.width;
height = node.geometry.height;
}
if (node.actions != null) {
canBeTapped = false;
canBeLongPressed = false;
canBeScrolledHorizontally = false;
canBeScrolledVertically = false;
for (int action : node.actions) {
switch (action) {
case SemanticAction.TAP:
canBeTapped = true;
break;
case SemanticAction.LONG_PRESS:
canBeLongPressed = true;
break;
case SemanticAction.SCROLL_LEFT:
canBeScrolledHorizontally = true;
break;
case SemanticAction.SCROLL_RIGHT:
canBeScrolledHorizontally = true;
break;
case SemanticAction.SCROLL_UP:
canBeScrolledVertically = true;
break;
case SemanticAction.SCROLL_DOWN:
canBeScrolledVertically = true;
break;
case SemanticAction.INCREASE:
// Not implemented.
break;
case SemanticAction.DECREASE:
// Not implemented.
break;
}
}
}
}
// fields that we pass straight to the Android accessibility API
int id = -1;
SemanticObject parent;
boolean canBeTapped;
boolean canBeLongPressed;
boolean canBeScrolledHorizontally;
boolean canBeScrolledVertically;
boolean hasCheckedState;
boolean isChecked;
String label;
List<SemanticObject> children;
// geometry, which we have to convert to global coordinates to send to Android
private float[] transform; // can be null, meaning identity transform
private float left;
private float top;
private float width;
private float height;
private boolean geometryDirty = true;
private void invalidateGlobalGeometry() {
if (geometryDirty) {
return;
}
geometryDirty = true;
// TODO(ianh): if we are the AccessibilityBridge.this.mFocusedObject
// then we may have to unfocus and refocus ourselves to get Android to update the focus rect
if (children != null) {
for (SemanticObject child : children) {
child.invalidateGlobalGeometry();
}
}
}
private float[] globalTransform; // cached transform from the root node to this node
private Rect globalRect; // cached Rect of bounds of this node in coordinate space of the root node
private float[] getGlobalTransform() {
if (geometryDirty) {
if (parent == null) {
globalTransform = transform;
} else {
float[] parentTransform = parent.getGlobalTransform();
if (transform == null) {
globalTransform = parentTransform;
} else if (parentTransform == null) {
globalTransform = transform;
} else {
globalTransform = new float[16];
Matrix.multiplyMM(globalTransform, 0, transform, 0, parentTransform, 0);
}
}
}
return globalTransform;
}
private float[] transformPoint(float[] transform, float[] point) {
if (transform == null)
return point; // this is a 4-item array but the caller will ignore all but the first two items
float[] transformedPoint = new float[4];
Matrix.multiplyMV(transformedPoint, 0, transform, 0, point, 0);
assert transformedPoint[2] == 0;
return new float[]{transformedPoint[0] / transformedPoint[3],
transformedPoint[1] / transformedPoint[3]};
}
private float min(float a, float b, float c, float d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
private float max(float a, float b, float c, float d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
Rect getGlobalRect() {
if (geometryDirty) {
float[] transform = getGlobalTransform();
float[] point1 = transformPoint(transform, new float[]{left, top, 0, 1});
float[] point2 = transformPoint(transform, new float[]{left + width, top, 0, 1});
float[] point3 = transformPoint(transform, new float[]{left + width, top + height, 0, 1});
float[] point4 = transformPoint(transform, new float[]{left, top + height, 0, 1});
// TODO(ianh): Scaling here is a hack to work around #1360.
float scale = mOwner.getDevicePixelRatio();
globalRect = new Rect(
Math.round(min(point1[0], point2[0], point3[0], point4[0]) * scale),
Math.round(min(point1[1], point2[1], point3[1], point4[1]) * scale),
Math.round(max(point1[0], point2[0], point3[0], point4[0]) * scale),
Math.round(max(point1[1], point2[1], point3[1], point4[1]) * scale)
);
}
return globalRect;
}
SemanticObject hitTest(int x, int y) {
Rect rect = getGlobalRect();
if (!rect.contains(x, y))
return null;
if (children != null) {
for (int index = children.size()-1; index >= 0; index -= 1) {
SemanticObject child = children.get(index);
SemanticObject result = child.hitTest(x, y);
if (result != null) {
return result;
}
}
}
return this;
}
}
@Override
public void close() {}
@Override
public void onConnectionError(MojoException e) {}
}

View File

@@ -0,0 +1,412 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.content.Context;
import android.util.Log;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.SystemClock;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.chromium.base.JNINamespace;
import org.chromium.base.PathUtils;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.sensors.SensorServiceImpl;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.impl.CoreImpl;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojom.activity.Activity;
import org.chromium.mojom.editing.Clipboard;
import org.chromium.mojom.flutter.platform.HapticFeedback;
import org.chromium.mojom.flutter.platform.PathProvider;
import org.chromium.mojom.flutter.platform.SystemChrome;
import org.chromium.mojom.flutter.platform.SystemSound;
import org.chromium.mojom.flutter.platform.UrlLauncher;
import org.chromium.mojom.media.MediaService;
import org.chromium.mojom.sensors.SensorService;
import org.chromium.mojom.vsync.VSyncProvider;
import org.domokit.activity.ActivityImpl;
import org.domokit.editing.ClipboardImpl;
import org.domokit.media.MediaServiceImpl;
import org.domokit.platform.HapticFeedbackImpl;
import org.domokit.platform.PathProviderImpl;
import org.domokit.platform.SystemChromeImpl;
import org.domokit.platform.SystemSoundImpl;
import org.domokit.platform.UrlLauncherImpl;
import org.domokit.vsync.VSyncProviderImpl;
/**
* A class to intialize the Flutter engine.
*/
@JNINamespace("shell")
public class FlutterMain {
private static final String TAG = "FlutterMain";
// Must match values in sky::shell::switches
private static final String AOT_SNAPSHOT_PATH_KEY = "aot-snapshot-path";
private static final String AOT_ISOLATE_KEY = "isolate-snapshot";
private static final String AOT_VM_ISOLATE_KEY = "vm-isolate-snapshot";
private static final String AOT_INSTRUCTIONS_KEY = "instructions-blob";
private static final String AOT_RODATA_KEY = "rodata-blob";
private static final String FLX_KEY = "flx";
// XML Attribute keys supported in AndroidManifest.xml
public static final String PUBLIC_AOT_ISOLATE_KEY =
FlutterMain.class.getName() + '.' + AOT_ISOLATE_KEY;
public static final String PUBLIC_AOT_VM_ISOLATE_KEY =
FlutterMain.class.getName() + '.' + AOT_VM_ISOLATE_KEY;
public static final String PUBLIC_AOT_INSTRUCTIONS_KEY =
FlutterMain.class.getName() + '.' + AOT_INSTRUCTIONS_KEY;
public static final String PUBLIC_AOT_RODATA_KEY =
FlutterMain.class.getName() + '.' + AOT_RODATA_KEY;
public static final String PUBLIC_FLX_KEY =
FlutterMain.class.getName() + '.' + FLX_KEY;
// Resource names used for components of the precompiled snapshot.
private static final String DEFAULT_AOT_ISOLATE = "snapshot_aot_isolate";
private static final String DEFAULT_AOT_VM_ISOLATE = "snapshot_aot_vmisolate";
private static final String DEFAULT_AOT_INSTRUCTIONS = "snapshot_aot_instr";
private static final String DEFAULT_AOT_RODATA = "snapshot_aot_rodata";
private static final String DEFAULT_FLX = "app.flx";
private static final String MANIFEST = "flutter.yaml";
private static final String SERVICES = "services.json";
private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "sky_shell";
private static final Set<String> SKY_RESOURCES = ImmutableSetBuilder.<String>newInstance()
.add("icudtl.dat")
.add(MANIFEST)
.build();
// Mutable because default values can be overridden via config properties
private static String sAotIsolate = DEFAULT_AOT_ISOLATE;
private static String sAotVmIsolate = DEFAULT_AOT_VM_ISOLATE;
private static String sAotInstructions = DEFAULT_AOT_INSTRUCTIONS;
private static String sAotRodata = DEFAULT_AOT_RODATA;
private static String sFlx = DEFAULT_FLX;
private static boolean sInitialized = false;
private static ResourceExtractor sResourceExtractor;
private static boolean sIsPrecompiled;
private static final class ImmutableSetBuilder<T> {
static <T> ImmutableSetBuilder<T> newInstance() {
return new ImmutableSetBuilder<>();
}
HashSet<T> set = new HashSet<>();
private ImmutableSetBuilder() {}
ImmutableSetBuilder<T> add(T element) {
set.add(element);
return this;
}
@SafeVarargs
final ImmutableSetBuilder<T> add(T... elements) {
for (T element : elements) {
set.add(element);
}
return this;
}
Set<T> build() {
return Collections.unmodifiableSet(set);
}
}
/**
* Starts initialization of the native system.
*/
public static void startInitialization(Context applicationContext) {
long initStartTimestampMillis = SystemClock.uptimeMillis();
initConfig(applicationContext);
initJavaUtils(applicationContext);
initResources(applicationContext);
initNative(applicationContext);
initAot(applicationContext);
// We record the initialization time using SystemClock because at the start of the
// initialization we have not yet loaded the native library to call into dart_tools_api.h.
// To get Timeline timestamp of the start of initialization we simply subtract the delta
// from the Timeline timestamp at the current moment (the assumption is that the overhead
// of the JNI call is negligible).
long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
nativeRecordStartTimestamp(initTimeMillis);
onServiceRegistryAvailable(applicationContext, ServiceRegistry.SHARED);
}
/**
* Blocks until initialization of the native system has completed.
*/
public static void ensureInitializationComplete(Context applicationContext, String[] args) {
if (sInitialized) {
return;
}
try {
sResourceExtractor.waitForCompletion();
List<String> shellArgs = new ArrayList<>();
if (args != null) {
Collections.addAll(shellArgs, args);
}
if (sIsPrecompiled) {
shellArgs.add("--" + AOT_SNAPSHOT_PATH_KEY + "=" +
PathUtils.getDataDirectory(applicationContext));
shellArgs.add("--" + AOT_ISOLATE_KEY + "=" + sAotIsolate);
shellArgs.add("--" + AOT_VM_ISOLATE_KEY + "=" + sAotVmIsolate);
shellArgs.add("--" + AOT_INSTRUCTIONS_KEY + "=" + sAotInstructions);
shellArgs.add("--" + AOT_RODATA_KEY + "=" + sAotRodata);
} else {
shellArgs.add("--cache-dir-path=" +
PathUtils.getCacheDirectory(applicationContext));
}
nativeInit(applicationContext, shellArgs.toArray(new String[0]));
// Create the mojo run loop.
CoreImpl.getInstance().createDefaultRunLoop();
sInitialized = true;
} catch (Exception e) {
Log.e(TAG, "Flutter initialization failed.", e);
throw new RuntimeException(e);
}
}
private static native void nativeInit(Context context, String[] args);
private static native void nativeRecordStartTimestamp(long initTimeMillis);
private static void onServiceRegistryAvailable(final Context applicationContext, ServiceRegistry registry) {
parseServicesConfig(applicationContext, registry);
registry.register(Activity.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return Activity.MANAGER.bind(new ActivityImpl(), pipe);
}
});
registry.register(Clipboard.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return Clipboard.MANAGER.bind(new ClipboardImpl(view.getContext()), pipe);
}
});
registry.register(MediaService.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return MediaService.MANAGER.bind(new MediaServiceImpl(view.getContext(), core), pipe);
}
});
registry.register(SensorService.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return SensorService.MANAGER.bind(new SensorServiceImpl(view.getContext()), pipe);
}
});
registry.register(VSyncProvider.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return VSyncProvider.MANAGER.bind(new VSyncProviderImpl(pipe), pipe);
}
});
registry.register(HapticFeedback.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return HapticFeedback.MANAGER.bind(new HapticFeedbackImpl((android.app.Activity) view.getContext()), pipe);
}
});
registry.register(PathProvider.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return PathProvider.MANAGER.bind(new PathProviderImpl(view.getContext()), pipe);
}
});
registry.register(SystemChrome.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
SystemChromeImpl chrome = new SystemChromeImpl((android.app.Activity) view.getContext());
view.addActivityLifecycleListener(chrome);
return SystemChrome.MANAGER.bind(chrome, pipe);
}
});
registry.register(SystemSound.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return SystemSound.MANAGER.bind(new SystemSoundImpl((android.app.Activity) view.getContext()), pipe);
}
});
registry.register(UrlLauncher.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return UrlLauncher.MANAGER.bind(new UrlLauncherImpl((android.app.Activity) view.getContext()), pipe);
}
});
}
/**
* Parses the auto-generated services.json file, which contains additional services to register.
*/
private static void parseServicesConfig(Context applicationContext, ServiceRegistry registry) {
final AssetManager manager = applicationContext.getResources().getAssets();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(manager.open(SERVICES)))) {
StringBuffer json = new StringBuffer();
while (true) {
String line = reader.readLine();
if (line == null)
break;
json.append(line);
}
JSONObject object = (JSONObject) new JSONTokener(json.toString()).nextValue();
JSONArray services = object.getJSONArray("services");
for (int i = 0; i < services.length(); ++i) {
JSONObject service = services.getJSONObject(i);
String serviceName = service.getString("name");
String className = service.getString("class");
registerService(registry, serviceName, className);
}
} catch (FileNotFoundException e) {
// Not all apps will have a services.json file.
return;
} catch (Exception e) {
Log.e(TAG, "Failure parsing service configuration file", e);
return;
}
}
/**
* Registers a third-party service.
*/
private static void registerService(ServiceRegistry registry, final String serviceName, final String className) {
registry.register(serviceName, new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
try {
return (Binding) Class.forName(className)
.getMethod("connectToService", FlutterView.class, Core.class, MessagePipeHandle.class)
.invoke(null, view, core, pipe);
} catch(Exception e) {
Log.e(TAG, "Failed to register service '" + serviceName + "'", e);
throw new RuntimeException(e);
}
}
});
}
/**
* Initialize our Flutter config values by obtaining them from the
* manifest XML file, falling back to default values.
*/
private static void initConfig(Context applicationContext) {
try {
Bundle metadata = applicationContext.getPackageManager().getApplicationInfo(
applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData;
if (metadata != null) {
sAotIsolate = metadata.getString(PUBLIC_AOT_ISOLATE_KEY, DEFAULT_AOT_ISOLATE);
sAotVmIsolate = metadata.getString(PUBLIC_AOT_VM_ISOLATE_KEY,
DEFAULT_AOT_VM_ISOLATE);
sAotInstructions = metadata.getString(PUBLIC_AOT_INSTRUCTIONS_KEY,
DEFAULT_AOT_INSTRUCTIONS);
sAotRodata = metadata.getString(PUBLIC_AOT_RODATA_KEY, DEFAULT_AOT_RODATA);
sFlx = metadata.getString(PUBLIC_FLX_KEY, DEFAULT_FLX);
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
private static void initJavaUtils(Context applicationContext) {
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX,
applicationContext);
}
private static void initResources(Context applicationContext) {
Context context = applicationContext;
new ResourceCleaner(context).start();
sResourceExtractor = new ResourceExtractor(context)
.addResources(SKY_RESOURCES)
.addResource(sAotIsolate)
.addResource(sAotVmIsolate)
.addResource(sAotInstructions)
.addResource(sAotRodata)
.addResource(sFlx)
.start();
}
private static void initNative(Context applicationContext) {
try {
LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER)
.ensureInitialized(applicationContext);
} catch (ProcessInitException e) {
Log.e(TAG, "Unable to load Sky Engine binary.", e);
throw new RuntimeException(e);
}
}
/**
* Returns a list of the file names at the root of the application's asset
* path.
*/
private static Set<String> listRootAssets(Context applicationContext) {
AssetManager manager = applicationContext.getResources().getAssets();
try {
return ImmutableSetBuilder.<String>newInstance()
.add(manager.list(""))
.build();
} catch (IOException e) {
Log.e(TAG, "Unable to list assets", e);
throw new RuntimeException(e);
}
}
private static void initAot(Context applicationContext) {
Set<String> assets = listRootAssets(applicationContext);
sIsPrecompiled = assets.containsAll(Arrays.asList(
sAotIsolate,
sAotVmIsolate,
sAotInstructions,
sAotRodata
));
}
public static boolean isRunningPrecompiledCode() {
return sIsPrecompiled;
}
public static String findAppBundlePath(Context applicationContext) {
String dataDirectory = PathUtils.getDataDirectory(applicationContext);
File appBundle = new File(dataDirectory, sFlx);
return appBundle.exists() ? appBundle.getPath() : null;
}
}

View File

@@ -0,0 +1,747 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.opengl.Matrix;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowInsets;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import org.json.JSONException;
import org.json.JSONObject;
import org.chromium.base.JNINamespace;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojo.system.Pair;
import org.chromium.mojo.system.impl.CoreImpl;
import org.chromium.mojom.editing.Keyboard;
import org.chromium.mojom.flutter.platform.ApplicationMessages;
import org.chromium.mojom.mojo.ServiceProvider;
import org.chromium.mojom.pointer.Pointer;
import org.chromium.mojom.pointer.PointerKind;
import org.chromium.mojom.pointer.PointerPacket;
import org.chromium.mojom.pointer.PointerType;
import org.chromium.mojom.raw_keyboard.RawKeyboardService;
import org.chromium.mojom.semantics.SemanticsServer;
import org.chromium.mojom.sky.AppLifecycleState;
import org.chromium.mojom.sky.ServicesData;
import org.chromium.mojom.sky.SkyEngine;
import org.chromium.mojom.sky.ViewportMetrics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.domokit.common.ActivityLifecycleListener;
import org.domokit.activity.ActivityImpl;
import org.domokit.editing.KeyboardImpl;
import org.domokit.editing.KeyboardViewState;
import org.domokit.raw_keyboard.RawKeyboardServiceImpl;
import org.domokit.raw_keyboard.RawKeyboardServiceState;
/**
* An Android view containing a Flutter app.
*/
@JNINamespace("shell")
public class FlutterView extends SurfaceView
implements AccessibilityManager.AccessibilityStateChangeListener,
AccessibilityManager.TouchExplorationStateChangeListener {
private static final String TAG = "FlutterView";
private static final String ACTION_DISCOVER = "io.flutter.view.DISCOVER";
private long mNativePlatformView;
private SkyEngine.Proxy mSkyEngine;
private ServiceProviderImpl mPlatformServiceProvider;
private Binding mPlatformServiceProviderBinding;
private ServiceProviderImpl mViewServiceProvider;
private Binding mViewServiceProviderBinding;
private ServiceProvider.Proxy mDartServiceProvider;
private ApplicationMessages.Proxy mFlutterAppMessages;
private HashMap<String, OnMessageListener> mOnMessageListeners;
private HashMap<String, OnMessageListenerAsync> mAsyncOnMessageListeners;
private final SurfaceHolder.Callback mSurfaceCallback;
private final ViewportMetrics mMetrics;
private final KeyboardViewState mKeyboardState;
private final RawKeyboardServiceState mRawKeyboardState;
private final AccessibilityManager mAccessibilityManager;
private BroadcastReceiver discoveryReceiver;
private List<ActivityLifecycleListener> mActivityLifecycleListeners;
public FlutterView(Context context) {
this(context, null);
}
public FlutterView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO(abarth): Remove this static and instead make everything that
// depends on it into a view-associated service.
ActivityImpl.setCurrentActivity((Activity) context);
mMetrics = new ViewportMetrics();
mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
setFocusable(true);
setFocusableInTouchMode(true);
attach();
assert mNativePlatformView != 0;
int color = 0xFF000000;
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorBackground, typedValue, true);
if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT)
color = typedValue.data;
// TODO(abarth): Consider letting the developer override this color.
final int backgroundColor = color;
mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
assert mNativePlatformView != 0;
nativeSurfaceCreated(mNativePlatformView, holder.getSurface());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assert mNativePlatformView != 0;
nativeSurfaceChanged(mNativePlatformView, backgroundColor);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assert mNativePlatformView != 0;
nativeSurfaceDestroyed(mNativePlatformView);
}
};
getHolder().addCallback(mSurfaceCallback);
mKeyboardState = new KeyboardViewState(this);
mRawKeyboardState = new RawKeyboardServiceState();
Core core = CoreImpl.getInstance();
mPlatformServiceProvider = new ServiceProviderImpl(core, this, ServiceRegistry.SHARED);
ServiceRegistry localRegistry = new ServiceRegistry();
configureLocalServices(localRegistry);
mViewServiceProvider = new ServiceProviderImpl(core, this, localRegistry);
mAccessibilityManager = (AccessibilityManager)getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
mOnMessageListeners = new HashMap<String, OnMessageListener>();
mAsyncOnMessageListeners = new HashMap<String, OnMessageListenerAsync>();
mActivityLifecycleListeners = new ArrayList<ActivityLifecycleListener>();
setLocale(getResources().getConfiguration().locale);
if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
discoveryReceiver = new DiscoveryReceiver();
context.registerReceiver(discoveryReceiver, new IntentFilter(ACTION_DISCOVER));
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mRawKeyboardState.onKey(this, keyCode, event))
return true;
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mRawKeyboardState.onKey(this, keyCode, event))
return true;
return super.onKeyDown(keyCode, event);
}
SkyEngine getEngine() {
return mSkyEngine;
}
public void addActivityLifecycleListener(ActivityLifecycleListener listener) {
mActivityLifecycleListeners.add(listener);
}
public void onPause() {
mSkyEngine.onAppLifecycleStateChanged(AppLifecycleState.PAUSED);
}
public void onPostResume() {
for (ActivityLifecycleListener listener : mActivityLifecycleListeners)
listener.onPostResume();
mSkyEngine.onAppLifecycleStateChanged(AppLifecycleState.RESUMED);
}
public void pushRoute(String route) {
mSkyEngine.pushRoute(route);
}
public void popRoute() {
mSkyEngine.popRoute();
}
private void setLocale(Locale locale) {
mSkyEngine.onLocaleChanged(locale.getLanguage(), locale.getCountry());
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setLocale(newConfig.locale);
}
float getDevicePixelRatio() {
return mMetrics.devicePixelRatio;
}
public void destroy() {
if (discoveryReceiver != null) {
getContext().unregisterReceiver(discoveryReceiver);
}
if (mPlatformServiceProviderBinding != null) {
mPlatformServiceProviderBinding.unbind().close();
mPlatformServiceProvider.unbindServices();
}
if (mViewServiceProviderBinding != null) {
mViewServiceProviderBinding.unbind().close();
mViewServiceProvider.unbindServices();
}
getHolder().removeCallback(mSurfaceCallback);
nativeDetach(mNativePlatformView);
mNativePlatformView = 0;
mSkyEngine.close();
mDartServiceProvider.close();
mFlutterAppMessages.close();
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return mKeyboardState.createInputConnection(outAttrs);
}
private Integer getPointerTypeForAction(int maskedAction) {
// Primary pointer:
if (maskedAction == MotionEvent.ACTION_DOWN) {
return PointerType.DOWN;
}
if (maskedAction == MotionEvent.ACTION_UP) {
return PointerType.UP;
}
// Secondary pointer:
if (maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
return PointerType.DOWN;
}
if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
return PointerType.UP;
}
// All pointers:
if (maskedAction == MotionEvent.ACTION_MOVE) {
return PointerType.MOVE;
}
if (maskedAction == MotionEvent.ACTION_CANCEL) {
return PointerType.CANCEL;
}
return null;
}
private void addPointerForIndex(MotionEvent event, int pointerIndex,
List<Pointer> result) {
Integer pointerType = getPointerTypeForAction(event.getActionMasked());
if (pointerType == null) {
return;
}
Pointer pointer = new Pointer();
pointer.timeStamp = event.getEventTime() * 1000; // Convert from milliseconds to microseconds.
pointer.pointer = event.getPointerId(pointerIndex);
pointer.type = pointerType;
pointer.kind = PointerKind.TOUCH;
pointer.x = event.getX(pointerIndex);
pointer.y = event.getY(pointerIndex);
pointer.buttons = 0;
pointer.down = false;
pointer.primary = false;
pointer.obscured = false;
// TODO(eseidel): Could get the calibrated range if necessary:
// event.getDevice().getMotionRange(MotionEvent.AXIS_PRESSURE)
pointer.pressure = event.getPressure(pointerIndex);
pointer.pressureMin = 0.0f;
pointer.pressureMax = 1.0f;
pointer.distance = 0.0f;
pointer.distanceMin = 0.0f;
pointer.distanceMax = 0.0f;
pointer.radiusMajor = 0.0f;
pointer.radiusMinor = 0.0f;
pointer.radiusMin = 0.0f;
pointer.radiusMax = 0.0f;
pointer.orientation = 0.0f;
pointer.tilt = 0.0f;
result.add(pointer);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO(abarth): This version check might not be effective in some
// versions of Android that statically compile code and will be upset
// at the lack of |requestUnbufferedDispatch|. Instead, we should factor
// version-dependent code into separate classes for each supported
// version and dispatch dynamically.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
requestUnbufferedDispatch(event);
}
ArrayList<Pointer> pointers = new ArrayList<Pointer>();
// TODO(abarth): Rather than unpacking these events here, we should
// probably send them in one packet to the engine.
int maskedAction = event.getActionMasked();
// ACTION_UP, ACTION_POINTER_UP, ACTION_DOWN, and ACTION_POINTER_DOWN
// only apply to a single pointer, other events apply to all pointers.
if (maskedAction == MotionEvent.ACTION_UP
|| maskedAction == MotionEvent.ACTION_POINTER_UP
|| maskedAction == MotionEvent.ACTION_DOWN
|| maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
addPointerForIndex(event, event.getActionIndex(), pointers);
} else {
// ACTION_MOVE may not actually mean all pointers have moved
// but it's the responsibility of a later part of the system to
// ignore 0-deltas if desired.
for (int p = 0; p < event.getPointerCount(); p++) {
addPointerForIndex(event, p, pointers);
}
}
PointerPacket packet = new PointerPacket();
packet.pointers = pointers.toArray(new Pointer[0]);
mSkyEngine.onPointerPacket(packet);
return true;
}
@Override
public boolean onHoverEvent(MotionEvent event) {
boolean handled = handleAccessibilityHoverEvent(event);
if (!handled) {
// TODO(ianh): Expose hover events to the platform,
// implementing ADD, REMOVE, etc.
}
return handled;
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
mMetrics.physicalWidth = width;
mMetrics.physicalHeight = height;
mSkyEngine.onViewportMetricsChanged(mMetrics);
super.onSizeChanged(width, height, oldWidth, oldHeight);
}
@Override
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
mMetrics.physicalPaddingTop = insets.getSystemWindowInsetTop();
mMetrics.physicalPaddingRight = insets.getSystemWindowInsetRight();
mMetrics.physicalPaddingBottom = insets.getSystemWindowInsetBottom();
mMetrics.physicalPaddingLeft = insets.getSystemWindowInsetLeft();
mSkyEngine.onViewportMetricsChanged(mMetrics);
return super.onApplyWindowInsets(insets);
}
private void configureLocalServices(ServiceRegistry registry) {
registry.register(Keyboard.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return Keyboard.MANAGER.bind(new KeyboardImpl(view.getContext(), mKeyboardState), pipe);
}
});
registry.register(RawKeyboardService.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return RawKeyboardService.MANAGER.bind(new RawKeyboardServiceImpl(mRawKeyboardState), pipe);
}
});
registry.register(ApplicationMessages.MANAGER.getName(), new ServiceFactory() {
@Override
public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
return ApplicationMessages.MANAGER.bind(new ApplicationMessagesImpl(), pipe);
}
});
}
private void attach() {
Core core = CoreImpl.getInstance();
Pair<SkyEngine.Proxy, InterfaceRequest<SkyEngine>> engine =
SkyEngine.MANAGER.getInterfaceRequest(core);
mSkyEngine = engine.first;
mNativePlatformView =
nativeAttach(engine.second.passHandle().releaseNativeHandle(), this);
}
private void preRun() {
if (mPlatformServiceProviderBinding != null) {
mPlatformServiceProviderBinding.unbind().close();
mPlatformServiceProvider.unbindServices();
}
if (mViewServiceProviderBinding != null) {
mViewServiceProviderBinding.unbind().close();
mViewServiceProvider.unbindServices();
}
if (mDartServiceProvider != null) {
mDartServiceProvider.close();
}
Core core = CoreImpl.getInstance();
Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> dartServiceProvider =
ServiceProvider.MANAGER.getInterfaceRequest(core);
mDartServiceProvider = dartServiceProvider.first;
Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> platformServiceProvider =
ServiceProvider.MANAGER.getInterfaceRequest(core);
mPlatformServiceProviderBinding = ServiceProvider.MANAGER.bind(
mPlatformServiceProvider, platformServiceProvider.second);
Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> viewServiceProvider =
ServiceProvider.MANAGER.getInterfaceRequest(core);
mViewServiceProviderBinding = ServiceProvider.MANAGER.bind(
mViewServiceProvider, viewServiceProvider.second);
ServicesData services = new ServicesData();
services.incomingServices = platformServiceProvider.first;
services.outgoingServices = dartServiceProvider.second;
services.viewServices = viewServiceProvider.first;
mSkyEngine.setServices(services);
resetAccessibilityTree();
}
private void postRun() {
Core core = CoreImpl.getInstance();
// Connect to the ApplicationMessages service exported by the Flutter framework
Pair<ApplicationMessages.Proxy, InterfaceRequest<ApplicationMessages>> appMessages =
ApplicationMessages.MANAGER.getInterfaceRequest(core);
mDartServiceProvider.connectToService(ApplicationMessages.MANAGER.getName(),
appMessages.second.passHandle());
mFlutterAppMessages = appMessages.first;
}
public void runFromBundle(String bundlePath, String snapshotPath) {
preRun();
if (FlutterMain.isRunningPrecompiledCode()) {
mSkyEngine.runFromPrecompiledSnapshot(bundlePath);
} else {
String scriptUri = "file://" + bundlePath;
if (snapshotPath != null) {
mSkyEngine.runFromBundleAndSnapshot(scriptUri, bundlePath, snapshotPath);
} else {
mSkyEngine.runFromBundle(scriptUri, bundlePath);
}
}
postRun();
}
public void runFromSource(final String main,
final String packages,
final String assetsDirectory) {
Runnable runnable = new Runnable() {
public void run() {
preRun();
mSkyEngine.runFromFile(main,
packages,
assetsDirectory);
postRun();
synchronized (this) {
notify();
}
}
};
try {
synchronized (runnable) {
// Post to the Android UI thread and wait for the response.
post(runnable);
runnable.wait();
}
} catch (InterruptedException e) {
Log.e(TAG, "Thread got interrupted waiting for " +
"RunFromSourceRunnable to finish", e);
}
}
/** Return the most recent frame as a bitmap. */
public Bitmap getBitmap() {
return nativeGetBitmap(mNativePlatformView);
}
private static native long nativeAttach(int skyEngineHandle,
FlutterView view);
private static native int nativeGetObservatoryPort();
private static native void nativeDetach(long nativePlatformViewAndroid);
private static native void nativeSurfaceCreated(long nativePlatformViewAndroid,
Surface surface);
private static native void nativeSurfaceChanged(long nativePlatformViewAndroid, int backgroundColor);
private static native void nativeSurfaceDestroyed(long nativePlatformViewAndroid);
private static native Bitmap nativeGetBitmap(long nativePlatformViewAndroid);
// ACCESSIBILITY
private boolean mAccessibilityEnabled = false;
private boolean mTouchExplorationEnabled = false;
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mAccessibilityEnabled = mAccessibilityManager.isEnabled();
mTouchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled();
if (mAccessibilityEnabled || mTouchExplorationEnabled)
ensureAccessibilityEnabled();
resetWillNotDraw();
mAccessibilityManager.addAccessibilityStateChangeListener(this);
mAccessibilityManager.addTouchExplorationStateChangeListener(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAccessibilityManager.removeAccessibilityStateChangeListener(this);
mAccessibilityManager.removeTouchExplorationStateChangeListener(this);
}
private void resetWillNotDraw() {
setWillNotDraw(!(mAccessibilityEnabled || mTouchExplorationEnabled));
}
@Override
public void onAccessibilityStateChanged(boolean enabled) {
if (enabled) {
mAccessibilityEnabled = true;
ensureAccessibilityEnabled();
} else {
mAccessibilityEnabled = false;
}
if (mAccessibilityNodeProvider != null) {
mAccessibilityNodeProvider.setAccessibilityEnabled(mAccessibilityEnabled);
}
resetWillNotDraw();
}
@Override
public void onTouchExplorationStateChanged(boolean enabled) {
if (enabled) {
mTouchExplorationEnabled = true;
ensureAccessibilityEnabled();
} else {
mTouchExplorationEnabled = false;
if (mAccessibilityNodeProvider != null) {
mAccessibilityNodeProvider.handleTouchExplorationExit();
}
}
resetWillNotDraw();
}
@Override
public AccessibilityNodeProvider getAccessibilityNodeProvider() {
ensureAccessibilityEnabled();
return mAccessibilityNodeProvider;
}
private AccessibilityBridge mAccessibilityNodeProvider;
void ensureAccessibilityEnabled() {
if (mAccessibilityNodeProvider == null) {
mAccessibilityNodeProvider = new AccessibilityBridge(this, createSemanticsServer());
}
}
private SemanticsServer.Proxy createSemanticsServer() {
Core core = CoreImpl.getInstance();
Pair<SemanticsServer.Proxy, InterfaceRequest<SemanticsServer>> server =
SemanticsServer.MANAGER.getInterfaceRequest(core);
mDartServiceProvider.connectToService(SemanticsServer.MANAGER.getName(), server.second.passHandle());
return server.first;
}
void resetAccessibilityTree() {
if (mAccessibilityNodeProvider != null) {
mAccessibilityNodeProvider.reset(createSemanticsServer());
}
}
private boolean handleAccessibilityHoverEvent(MotionEvent event) {
if (!mTouchExplorationEnabled)
return false;
if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER ||
event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
mAccessibilityNodeProvider.handleTouchExploration(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
mAccessibilityNodeProvider.handleTouchExplorationExit();
} else {
Log.d("flutter", "unexpected accessibility hover event: " + event);
return false;
}
return true;
}
/**
* Send a message to the Flutter application. The Flutter Dart code can register a
* host message handler that will receive these messages.
*/
public void sendToFlutter(String messageName, String message,
final MessageReplyCallback callback) {
mFlutterAppMessages.sendString(messageName, message,
new ApplicationMessages.SendStringResponse() {
@Override
public void call(String reply) {
if (callback != null) {
callback.onReply(reply);
}
}
});
}
public void sendToFlutter(String messageName, String message) {
sendToFlutter(messageName, message, null);
}
/** Callback invoked when the app replies to a message sent with sendToFlutter. */
public interface MessageReplyCallback {
void onReply(String reply);
}
/**
* Register a callback to be invoked when the Flutter application sends a message
* to its host.
*/
public void addOnMessageListener(String messageName, OnMessageListener listener) {
mOnMessageListeners.put(messageName, listener);
}
/**
* Register a callback to be invoked when the Flutter application sends a message
* to its host. The reply to the message can be provided asynchronously.
*/
public void addOnMessageListenerAsync(String messageName, OnMessageListenerAsync listener) {
mAsyncOnMessageListeners.put(messageName, listener);
}
public interface OnMessageListener {
/**
* Called when a message is received from the Flutter app.
* @return the reply to the message (can be null)
*/
String onMessage(FlutterView view, String message);
};
public interface OnMessageListenerAsync {
/**
* Called when a message is received from the Flutter app.
* @param response Used to send a reply back to the app.
*/
void onMessage(FlutterView view, String message, MessageResponse response);
}
public interface MessageResponse {
void send(String reply);
}
private class ApplicationMessagesImpl implements ApplicationMessages {
@Override
public void close() {}
@Override
public void onConnectionError(MojoException e) {}
@Override
public void sendString(String messageName, String message, SendStringResponse callback) {
OnMessageListener listener = mOnMessageListeners.get(messageName);
if (listener != null) {
callback.call(listener.onMessage(FlutterView.this, message));
return;
}
OnMessageListenerAsync asyncListener = mAsyncOnMessageListeners.get(messageName);
if (asyncListener != null) {
asyncListener.onMessage(FlutterView.this, message, new MessageResponseAdapter(callback));
return;
}
callback.call(null);
}
}
/**
* This class wraps the raw Mojo callback object in an interface that is owned
* by Flutter and can be safely given to host apps.
*/
private static class MessageResponseAdapter implements MessageResponse {
private ApplicationMessages.SendStringResponse callback;
MessageResponseAdapter(ApplicationMessages.SendStringResponse callback) {
this.callback = callback;
}
@Override
public void send(String reply) {
callback.call(reply);
}
}
/** Broadcast receiver used to discover active Flutter instances. */
private class DiscoveryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
JSONObject discover = new JSONObject();
try {
discover.put("id", getContext().getPackageName());
discover.put("observatoryPort", nativeGetObservatoryPort());
Log.i(TAG, "DISCOVER: " + discover);
} catch (JSONException e) {}
}
}
}

View File

@@ -0,0 +1,88 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.domokit.common.ResourcePaths;
/**
* A class to clean up orphaned resource directories after unclean shutdowns.
**/
class ResourceCleaner {
private static final String TAG = "ResourceCleaner";
private static final long DELAY_MS = 5000;
private class CleanTask extends AsyncTask<Void, Void, Void> {
private final File[] mFilesToDelete;
CleanTask(File[] filesToDelete) {
mFilesToDelete = filesToDelete;
}
boolean hasFilesToDelete() {
return mFilesToDelete.length > 0;
}
@Override
protected Void doInBackground(Void... unused) {
Log.i(TAG, "Cleaning " + mFilesToDelete.length + " resources.");
for (File file : mFilesToDelete) {
if (file.exists()) {
deleteRecursively(file);
}
}
return null;
}
private void deleteRecursively(File parent) {
if (parent.isDirectory()) {
for (File child : parent.listFiles()) {
deleteRecursively(child);
}
}
parent.delete();
}
}
private final Context mContext;
ResourceCleaner(Context context) {
mContext = context;
}
void start() {
File cacheDir = mContext.getCacheDir();
if (cacheDir == null) {
return;
}
final CleanTask task = new CleanTask(cacheDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
boolean result = name.startsWith(ResourcePaths.TEMPORARY_RESOURCE_PREFIX);
return result;
}
}));
if (!task.hasFilesToDelete()) {
return;
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}, DELAY_MS);
}
}

View File

@@ -0,0 +1,192 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.util.Log;
import org.chromium.base.PathUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
/**
* A class to intialize the native code.
**/
class ResourceExtractor {
private static final String TAG = "ResourceExtractor";
private static final String TIMESTAMP_PREFIX = "res_timestamp-";
private class ExtractTask extends AsyncTask<Void, Void, Void> {
private static final int BUFFER_SIZE = 16 * 1024;
ExtractTask() { }
private void extractResources() {
final File dataDir = new File(PathUtils.getDataDirectory(mContext));
final String timestamp = checkTimestamp(dataDir);
if (timestamp != null) {
deleteFiles();
}
final AssetManager manager = mContext.getResources().getAssets();
try {
byte[] buffer = null;
final String[] assets = manager.list("");
for (String asset : assets) {
if (!mResources.contains(asset))
continue;
final File output = new File(dataDir, asset);
if (output.exists())
continue;
InputStream is = null;
OutputStream os = null;
try {
is = manager.open(asset);
os = new FileOutputStream(output);
if (buffer == null) {
buffer = new byte[BUFFER_SIZE];
}
int count = 0;
while ((count = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
os.write(buffer, 0, count);
}
os.flush();
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (os != null) {
os.close();
}
}
}
}
} catch (IOException e) {
Log.w(TAG, "Exception unpacking resources: " + e.getMessage());
deleteFiles();
return;
}
if (timestamp != null) {
try {
new File(dataDir, timestamp).createNewFile();
} catch (IOException e) {
Log.w(TAG, "Failed to write resource timestamp");
}
}
}
private String checkTimestamp(File dataDir) {
PackageManager packageManager = mContext.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
return TIMESTAMP_PREFIX;
}
if (packageInfo == null) {
return TIMESTAMP_PREFIX;
}
String expectedTimestamp =
TIMESTAMP_PREFIX + packageInfo.versionCode + "-" + packageInfo.lastUpdateTime;
final String[] existingTimestamps = getExistingTimestamps(dataDir);
if (existingTimestamps.length != 1
|| !expectedTimestamp.equals(existingTimestamps[0])) {
return expectedTimestamp;
}
return null;
}
@Override
protected Void doInBackground(Void... unused) {
extractResources();
return null;
}
}
private final Context mContext;
private final HashSet<String> mResources;
private ExtractTask mExtractTask;
ResourceExtractor(Context context) {
mContext = context;
mResources = new HashSet<String>();
}
ResourceExtractor addResource(String resource) {
mResources.add(resource);
return this;
}
ResourceExtractor addResources(Collection<String> resources) {
mResources.addAll(resources);
return this;
}
ResourceExtractor start() {
assert mExtractTask == null;
mExtractTask = new ExtractTask();
mExtractTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return this;
}
void waitForCompletion() {
assert mExtractTask != null;
try {
mExtractTask.get();
} catch (CancellationException e) {
deleteFiles();
} catch (ExecutionException e2) {
deleteFiles();
} catch (InterruptedException e3) {
deleteFiles();
}
}
private String[] getExistingTimestamps(File dataDir) {
return dataDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(TIMESTAMP_PREFIX);
}
});
}
private void deleteFiles() {
final File dataDir = new File(PathUtils.getDataDirectory(mContext));
for (String resource : mResources) {
final File file = new File(dataDir, resource);
if (file.exists()) {
file.delete();
}
}
for (String timestamp : getExistingTimestamps(dataDir)) {
new File(dataDir, timestamp).delete();
}
}
}

View File

@@ -0,0 +1,20 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.content.Context;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
/**
* An interface for creating services. Instances of this interface can be
* registered with ServiceRegistry and thereby made available to non-Java
* clients.
**/
interface ServiceFactory {
Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe);
}

View File

@@ -0,0 +1,68 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.content.Context;
import android.util.Log;
import java.util.HashSet;
import org.chromium.mojo.bindings.ConnectionErrorHandler;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojo.system.impl.CoreImpl;
import org.chromium.mojom.mojo.ServiceProvider;
/**
* A collection of services.
**/
class ServiceProviderImpl implements ServiceProvider {
private static final String TAG = "ServiceProviderImpl";
private Core mCore;
private FlutterView mView;
private ServiceRegistry mRegistry;
private HashSet<Binding> mBindings = new HashSet<Binding>();
ServiceProviderImpl(Core core, FlutterView view, ServiceRegistry registry) {
assert core != null;
assert view != null;
mCore = core;
mView = view;
mRegistry = registry;
}
@Override
public void close() {}
@Override
public void onConnectionError(MojoException e) {}
@Override
public void connectToService(String interfaceName, MessagePipeHandle pipe) {
ServiceFactory factory = mRegistry.get(interfaceName);
if (factory == null) {
pipe.close();
return;
}
final Binding binding = factory.connectToService(mView, mCore, pipe);
mBindings.add(binding);
binding.registerErrorHandler(new ConnectionErrorHandler() {
@Override
public void onConnectionError(MojoException e) {
Log.w(TAG, "Flutter service provider connection error", e);
mBindings.remove(binding);
}
});
}
public void unbindServices() {
for (Binding binding : mBindings) {
binding.unbind().close();
}
mBindings.clear();
}
}

View File

@@ -0,0 +1,39 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.view;
import android.util.Log;
import java.util.Map;
import java.util.TreeMap;
/**
* An registry for services.
**/
class ServiceRegistry {
private static final String TAG = "ServiceRegistry";
private Map<String, ServiceFactory> mRegistrations;
static final ServiceRegistry SHARED = new ServiceRegistry();
// In addition to the shared registry, there is a per-view registry
// maintained by the PlatformServiceProvider.
ServiceRegistry() {
mRegistrations = new TreeMap<String, ServiceFactory>();
}
void register(String interfaceName, ServiceFactory connector) {
assert !mRegistrations.containsKey(interfaceName);
assert connector != null;
mRegistrations.put(interfaceName, connector);
}
ServiceFactory get(String interfaceName) {
if (!mRegistrations.containsKey(interfaceName)) {
Log.e(TAG, "Unknown service " + interfaceName);
}
return mRegistrations.get(interfaceName);
}
}

View File

@@ -0,0 +1,55 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/base_jni_onload.h"
#include "base/android/base_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/android/library_loader/library_loader_hooks.h"
#include "base/bind.h"
#include "base/logging.h"
#include "flutter/lib/jni/dart_jni.h"
#include "mojo/android/system/base_run_loop.h"
#include "mojo/android/system/core_impl.h"
#include "flutter/shell/platform/android/flutter_main.h"
#include "flutter/shell/platform/android/platform_view_android.h"
namespace {
base::android::RegistrationMethod kSkyRegisteredMethods[] = {
{"CoreImpl", mojo::android::RegisterCoreImpl},
{"BaseRunLoop", mojo::android::RegisterBaseRunLoop},
{"FlutterView", shell::PlatformViewAndroid::Register},
{"FlutterMain", shell::RegisterFlutterMain},
};
bool RegisterJNI(JNIEnv* env) {
if (!base::android::RegisterJni(env))
return false;
return RegisterNativeMethods(env, kSkyRegisteredMethods,
arraysize(kSkyRegisteredMethods));
}
bool InitJNI() {
return blink::DartJni::InitJni();
}
} // namespace
// This is called by the VM when the shared library is first loaded.
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
std::vector<base::android::RegisterCallback> register_callbacks;
register_callbacks.push_back(base::Bind(&RegisterJNI));
std::vector<base::android::InitCallback> init_callbacks;
init_callbacks.push_back(base::Bind(&InitJNI));
if (!base::android::OnJNIOnLoadRegisterJNI(vm, register_callbacks) ||
!base::android::OnJNIOnLoadInit(init_callbacks)) {
return -1;
}
return JNI_VERSION_1_4;
}

View File

@@ -0,0 +1,146 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.shell;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import io.flutter.view.FlutterMain;
import io.flutter.view.FlutterView;
import org.chromium.base.PathUtils;
import org.chromium.base.TraceEvent;
import org.chromium.mojom.sky.EventType;
import org.chromium.mojom.sky.InputEvent;
import java.io.File;
import java.util.ArrayList;
/**
* Base class for activities that use Sky.
*/
public class SkyActivity extends Activity {
private FlutterView mView;
private String[] getArgsFromIntent(Intent intent) {
// Before adding more entries to this list, consider that arbitrary
// Android applications can generate intents with extra data and that
// there are many security-sensitive args in the binary.
ArrayList<String> args = new ArrayList<String>();
if (intent.getBooleanExtra("trace-startup", false)) {
args.add("--trace-startup");
}
if (intent.getBooleanExtra("start-paused", false)) {
args.add("--start-paused");
}
if (!args.isEmpty()) {
String[] argsArray = new String[args.size()];
return args.toArray(argsArray);
}
return null;
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(0x40000000);
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
String[] args = getArgsFromIntent(getIntent());
FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
mView = new FlutterView(this);
setContentView(mView);
onSkyReady();
}
/**
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mView != null) {
mView.destroy();
}
// Do we need to shut down Sky too?
super.onDestroy();
}
@Override
public void onBackPressed() {
if (mView != null) {
mView.popRoute();
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mView != null) {
mView.onPause();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mView != null) {
mView.onPostResume();
}
}
/**
* Override this function to customize startup behavior.
*/
protected void onSkyReady() {
TraceEvent.instant("SkyActivity.onSkyReady");
if (loadIntent(getIntent())) {
return;
}
String appBundlePath = FlutterMain.findAppBundlePath(getApplicationContext());
if (appBundlePath != null) {
mView.runFromBundle(appBundlePath, null);
return;
}
}
protected void onNewIntent(Intent intent) {
loadIntent(intent);
}
public boolean loadIntent(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_RUN.equals(action)) {
String route = intent.getStringExtra("route");
mView.runFromBundle(intent.getDataString(),
intent.getStringExtra("snapshot"));
if (route != null)
mView.pushRoute(route);
return true;
}
return false;
}
}

View File

@@ -0,0 +1,21 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.shell;
import android.app.Application;
import io.flutter.view.FlutterMain;
/**
* Sky implementation of {@link android.app.Application}, managing application-level global
* initializations.
*/
public class SkyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FlutterMain.startInitialization(this);
}
}

View File

@@ -0,0 +1,610 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/android/platform_view_android.h"
#include <android/input.h>
#include <android/native_window_jni.h>
#include <EGL/egl.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <utility>
#include "base/android/jni_android.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/trace_event/trace_event.h"
#include "flutter/common/threads.h"
#include "flutter/flow/compositor_context.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/shell/common/shell.h"
#include "jni/FlutterView_jni.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace shell {
namespace {
template <class T>
using EGLResult = std::pair<bool, T>;
EGLDisplay g_display = EGL_NO_DISPLAY;
EGLContext g_resource_context = EGL_NO_CONTEXT;
EGLSurface g_resource_surface = EGL_NO_SURFACE;
void LogLastEGLError() {
struct EGLNameErrorPair {
const char* name;
EGLint code;
};
#define _EGL_ERROR_DESC(a) \
{ #a, a }
const EGLNameErrorPair pairs[] = {
_EGL_ERROR_DESC(EGL_SUCCESS),
_EGL_ERROR_DESC(EGL_NOT_INITIALIZED),
_EGL_ERROR_DESC(EGL_BAD_ACCESS),
_EGL_ERROR_DESC(EGL_BAD_ALLOC),
_EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE),
_EGL_ERROR_DESC(EGL_BAD_CONTEXT),
_EGL_ERROR_DESC(EGL_BAD_CONFIG),
_EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_DISPLAY),
_EGL_ERROR_DESC(EGL_BAD_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_MATCH),
_EGL_ERROR_DESC(EGL_BAD_PARAMETER),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW),
_EGL_ERROR_DESC(EGL_CONTEXT_LOST),
};
#undef _EGL_ERROR_DESC
const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair);
EGLint last_error = eglGetError();
for (size_t i = 0; i < count; i++) {
if (last_error == pairs[i].code) {
DLOG(INFO) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code
<< ")";
return;
}
}
DLOG(WARNING) << "Unknown EGL Error";
}
EGLResult<EGLSurface> CreatePBufferSurface(EGLDisplay display,
EGLConfig config) {
// We only ever create pbuffer surfaces for background resource loading
// contexts. We never bind the pbuffer to anything.
const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
EGLSurface surface = eglCreatePbufferSurface(display, config, attribs);
return {surface != EGL_NO_SURFACE, surface};
}
EGLResult<EGLSurface> CreateContext(EGLDisplay display,
EGLConfig config,
EGLContext share = EGL_NO_CONTEXT) {
EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
EGLContext context = eglCreateContext(display, config, share, attributes);
return {context != EGL_NO_CONTEXT, context};
}
EGLResult<EGLConfig> ChooseEGLConfiguration(
EGLDisplay display,
PlatformView::SurfaceConfig config) {
EGLint attributes[] = {
// clang-format off
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, config.red_bits,
EGL_GREEN_SIZE, config.green_bits,
EGL_BLUE_SIZE, config.blue_bits,
EGL_ALPHA_SIZE, config.alpha_bits,
EGL_DEPTH_SIZE, config.depth_bits,
EGL_STENCIL_SIZE, config.stencil_bits,
EGL_NONE, // termination sentinel
// clang-format on
};
EGLint config_count = 0;
EGLConfig egl_config = nullptr;
if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) !=
EGL_TRUE) {
return {false, nullptr};
}
bool success = config_count > 0 && egl_config != nullptr;
return {success, success ? egl_config : nullptr};
}
void InitGlobal() {
// Get the display.
g_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (g_display == EGL_NO_DISPLAY)
return;
// Initialize the display connection.
if (eglInitialize(g_display, nullptr, nullptr) != EGL_TRUE)
return;
bool success;
// Choose a config for resource loading.
PlatformView::SurfaceConfig resource_config;
resource_config.stencil_bits = 0;
EGLConfig resource_egl_config;
std::tie(success, resource_egl_config) =
ChooseEGLConfiguration(g_display, resource_config);
if (!success) {
DLOG(INFO) << "Could not choose a resource configuration.";
LogLastEGLError();
return;
}
// Create a pbuffer surface for the configuration for resource loading.
std::tie(success, g_resource_surface) =
CreatePBufferSurface(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the pbuffer surface for resource loading.";
LogLastEGLError();
return;
}
// Create a resource context for the configuration.
std::tie(success, g_resource_context) =
CreateContext(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the resource context.";
LogLastEGLError();
return;
}
}
} // namespace
class AndroidNativeWindow {
public:
using Handle = ANativeWindow*;
explicit AndroidNativeWindow(Handle window) : window_(window) {
if (window_ != nullptr) {
ANativeWindow_acquire(window_);
}
}
~AndroidNativeWindow() {
if (window_ != nullptr) {
ANativeWindow_release(window_);
window_ = nullptr;
}
}
bool IsValid() const { return window_ != nullptr; }
Handle handle() const { return window_; }
private:
Handle window_;
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow);
};
class AndroidGLContext {
public:
explicit AndroidGLContext(AndroidNativeWindow::Handle window_handle,
PlatformView::SurfaceConfig config)
: window_(window_handle),
config_(nullptr),
surface_(EGL_NO_SURFACE),
context_(EGL_NO_CONTEXT),
valid_(false) {
if (!window_.IsValid()) {
// We always require a valid window since we are only going to deal
// with window surfaces.
return;
}
bool success = false;
// Choose a valid configuration.
std::tie(success, config_) = ChooseEGLConfiguration(g_display, config);
if (!success) {
DLOG(INFO) << "Could not choose a window configuration.";
LogLastEGLError();
return;
}
// Create a window surface for the configuration.
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
DLOG(INFO) << "Could not create the window surface.";
LogLastEGLError();
return;
}
// Create a context for the configuration.
std::tie(success, context_) =
CreateContext(g_display, config_, g_resource_context);
if (!success) {
DLOG(INFO) << "Could not create the main rendering context";
LogLastEGLError();
return;
}
// All done!
valid_ = true;
}
~AndroidGLContext() {
if (!TeardownContext(g_display, context_)) {
LOG(INFO)
<< "Could not tear down the EGL context. Possible resource leak.";
LogLastEGLError();
}
if (!TeardownSurface(g_display, surface_)) {
LOG(INFO)
<< "Could not tear down the EGL surface. Possible resource leak.";
LogLastEGLError();
}
}
bool IsValid() const { return valid_; }
bool ContextMakeCurrent() {
if (eglMakeCurrent(g_display, surface_, surface_, context_) != EGL_TRUE) {
LOG(INFO) << "Could not make the context current";
LogLastEGLError();
return false;
}
return true;
}
bool SwapBuffers() { return eglSwapBuffers(g_display, surface_); }
SkISize GetSize() {
EGLint width = 0;
EGLint height = 0;
if (!eglQuerySurface(g_display, surface_, EGL_WIDTH, &width) ||
!eglQuerySurface(g_display, surface_, EGL_HEIGHT, &height)) {
LOG(ERROR) << "Unable to query EGL surface size";
LogLastEGLError();
return SkISize::Make(0, 0);
}
return SkISize::Make(width, height);
}
void Resize(const SkISize& size) {
eglMakeCurrent(g_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
TeardownSurface(g_display, surface_);
bool success;
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
LOG(ERROR) << "Unable to create EGL window surface";
}
}
private:
AndroidNativeWindow window_;
EGLConfig config_;
EGLSurface surface_;
EGLContext context_;
bool valid_;
static bool TeardownContext(EGLDisplay display, EGLContext context) {
if (context != EGL_NO_CONTEXT) {
return eglDestroyContext(display, context) == EGL_TRUE;
}
return true;
}
static bool TeardownSurface(EGLDisplay display, EGLSurface surface) {
if (surface != EGL_NO_SURFACE) {
return eglDestroySurface(display, surface) == EGL_TRUE;
}
return true;
}
static EGLResult<EGLSurface> CreateWindowSurface(
EGLDisplay display,
EGLConfig config,
AndroidNativeWindow::Handle window_handle) {
// The configurations are only required when dealing with extensions or VG.
// We do neither.
EGLSurface surface = eglCreateWindowSurface(
display, config, reinterpret_cast<EGLNativeWindowType>(window_handle),
nullptr);
return {surface != EGL_NO_SURFACE, surface};
}
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidGLContext);
};
static jlong Attach(JNIEnv* env,
jclass clazz,
jint skyEngineHandle,
jobject flutterView) {
PlatformViewAndroid* view = new PlatformViewAndroid();
view->ConnectToEngine(mojo::InterfaceRequest<sky::SkyEngine>(
mojo::ScopedMessagePipeHandle(mojo::MessagePipeHandle(skyEngineHandle))));
// Create a weak reference to the flutterView Java object so that we can make
// calls into it later.
view->set_flutter_view(JavaObjectWeakGlobalRef(env, flutterView));
return reinterpret_cast<jlong>(view);
}
jint GetObservatoryPort(JNIEnv* env, jclass clazz) {
return blink::DartServiceIsolate::GetObservatoryPort();
}
// static
bool PlatformViewAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
PlatformViewAndroid::PlatformViewAndroid() : weak_factory_(this) {
// If this is the first PlatformView, then intiialize EGL and set up
// the resource context.
if (g_display == EGL_NO_DISPLAY)
InitGlobal();
}
PlatformViewAndroid::~PlatformViewAndroid() = default;
void PlatformViewAndroid::Detach(JNIEnv* env, jobject obj) {
ReleaseSurface();
delete this;
}
void PlatformViewAndroid::SurfaceCreated(JNIEnv* env,
jobject obj,
jobject jsurface) {
// Note: This ensures that any local references used by
// ANativeWindow_fromSurface are released immediately. This is needed as a
// workaround for https://code.google.com/p/android/issues/detail?id=68174
{
base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env);
ANativeWindow* window = ANativeWindow_fromSurface(env, jsurface);
std::unique_ptr<AndroidGLContext> context(
new AndroidGLContext(window, surface_config_));
if (context->IsValid()) {
context_ = std::move(context);
}
ANativeWindow_release(window);
}
}
void PlatformViewAndroid::SurfaceChanged(JNIEnv* env,
jobject obj,
jint backgroundColor) {
NotifyCreated(
[this, backgroundColor] { config_.rasterizer->Clear(backgroundColor); });
SetupResourceContextOnIOThread();
UpdateThreadPriorities();
}
void PlatformViewAndroid::UpdateThreadPriorities() {
blink::Threads::Gpu()->PostTask(
[]() { ::setpriority(PRIO_PROCESS, gettid(), -2); });
blink::Threads::UI()->PostTask(
[]() { ::setpriority(PRIO_PROCESS, gettid(), -1); });
}
void PlatformViewAndroid::SurfaceDestroyed(JNIEnv* env, jobject obj) {
ReleaseSurface();
}
void PlatformViewAndroid::ReleaseSurface() {
if (context_) {
NotifyDestroyed();
context_ = nullptr;
}
}
ftl::WeakPtr<shell::PlatformView> PlatformViewAndroid::GetWeakViewPtr() {
return weak_factory_.GetWeakPtr();
}
uint64_t PlatformViewAndroid::DefaultFramebuffer() const {
// FBO 0 is the default window bound framebuffer on Android.
return 0;
}
bool PlatformViewAndroid::ContextMakeCurrent() {
return context_ != nullptr ? context_->ContextMakeCurrent() : false;
}
bool PlatformViewAndroid::ResourceContextMakeCurrent() {
if (eglMakeCurrent(g_display, g_resource_surface, g_resource_surface,
g_resource_context) != EGL_TRUE) {
LOG(INFO) << "Could not make the resource context current";
LogLastEGLError();
return false;
}
return true;
}
bool PlatformViewAndroid::SwapBuffers() {
TRACE_EVENT0("flutter", "PlatformViewAndroid::SwapBuffers");
return context_ != nullptr ? context_->SwapBuffers() : false;
}
SkISize PlatformViewAndroid::GetSize() {
return context_->GetSize();
}
void PlatformViewAndroid::Resize(const SkISize& size) {
context_->Resize(size);
}
void PlatformViewAndroid::RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) {
FTL_CHECK(base::android::IsVMInitialized());
JNIEnv* env = base::android::AttachCurrentThread();
FTL_CHECK(env);
{
base::android::ScopedJavaLocalRef<jobject> local_flutter_view =
flutter_view_.get(env);
if (local_flutter_view.is_null()) {
// Collected.
return;
}
// Grab the class of the flutter view.
jclass flutter_view_class = env->GetObjectClass(local_flutter_view.obj());
FTL_CHECK(flutter_view_class);
// Grab the runFromSource method id.
jmethodID run_from_source_method_id = env->GetMethodID(
flutter_view_class, "runFromSource",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
FTL_CHECK(run_from_source_method_id);
// Invoke runFromSource on the Android UI thread.
jstring java_main = env->NewStringUTF(main.c_str());
FTL_CHECK(java_main);
jstring java_packages = env->NewStringUTF(packages.c_str());
FTL_CHECK(java_packages);
jstring java_assets_directory = env->NewStringUTF(assets_directory.c_str());
FTL_CHECK(java_assets_directory);
env->CallVoidMethod(local_flutter_view.obj(), run_from_source_method_id,
java_main, java_packages, java_assets_directory);
}
// Detaching from the VM deletes any stray local references.
base::android::DetachFromVM();
}
base::android::ScopedJavaLocalRef<jobject> PlatformViewAndroid::GetBitmap(
JNIEnv* env,
jobject obj) {
// Render the last frame to an array of pixels on the GPU thread.
// The pixels will be returned as a global JNI reference to an int array.
ftl::AutoResetWaitableEvent latch;
jobject pixels_ref = nullptr;
SkISize frame_size;
blink::Threads::Gpu()->PostTask([this, &latch, &pixels_ref, &frame_size]() {
GetBitmapGpuTask(&latch, &pixels_ref, &frame_size);
});
latch.Wait();
// Convert the pixel array to an Android bitmap.
if (pixels_ref == nullptr)
return base::android::ScopedJavaLocalRef<jobject>();
base::android::ScopedJavaGlobalRef<jobject> pixels(env, pixels_ref);
jclass bitmap_class = env->FindClass("android/graphics/Bitmap");
FTL_CHECK(bitmap_class);
jmethodID create_bitmap = env->GetStaticMethodID(
bitmap_class, "createBitmap",
"([IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
FTL_CHECK(create_bitmap);
jclass bitmap_config_class = env->FindClass("android/graphics/Bitmap$Config");
FTL_CHECK(bitmap_config_class);
jmethodID bitmap_config_value_of = env->GetStaticMethodID(
bitmap_config_class, "valueOf",
"(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
FTL_CHECK(bitmap_config_value_of);
jstring argb = env->NewStringUTF("ARGB_8888");
FTL_CHECK(argb);
jobject bitmap_config = env->CallStaticObjectMethod(
bitmap_config_class, bitmap_config_value_of, argb);
FTL_CHECK(bitmap_config);
jobject bitmap = env->CallStaticObjectMethod(
bitmap_class, create_bitmap, pixels.obj(), frame_size.width(),
frame_size.height(), bitmap_config);
return base::android::ScopedJavaLocalRef<jobject>(env, bitmap);
}
void PlatformViewAndroid::GetBitmapGpuTask(ftl::AutoResetWaitableEvent* latch,
jobject* pixels_out,
SkISize* size_out) {
flow::LayerTree* layer_tree = rasterizer_->GetLastLayerTree();
if (layer_tree == nullptr)
return;
JNIEnv* env = base::android::AttachCurrentThread();
FTL_CHECK(env);
const SkISize& frame_size = layer_tree->frame_size();
jsize pixels_size = frame_size.width() * frame_size.height();
jintArray pixels_array = env->NewIntArray(pixels_size);
FTL_CHECK(pixels_array);
jint* pixels = env->GetIntArrayElements(pixels_array, nullptr);
FTL_CHECK(pixels);
SkImageInfo image_info =
SkImageInfo::Make(frame_size.width(), frame_size.height(),
kRGBA_8888_SkColorType, kPremul_SkAlphaType);
sk_sp<SkSurface> surface = SkSurface::MakeRasterDirect(
image_info, pixels, frame_size.width() * sizeof(jint));
flow::CompositorContext compositor_context;
SkCanvas* canvas = surface->getCanvas();
flow::CompositorContext::ScopedFrame frame =
compositor_context.AcquireFrame(nullptr, *canvas, false);
canvas->clear(SK_ColorBLACK);
layer_tree->Raster(frame);
canvas->flush();
// Our configuration of Skia does not support rendering to the
// BitmapConfig.ARGB_8888 format expected by android.graphics.Bitmap.
// Convert from kRGBA_8888 to kBGRA_8888 (equivalent to ARGB_8888).
for (int i = 0; i < pixels_size; i++) {
uint8_t* bytes = reinterpret_cast<uint8_t*>(pixels + i);
std::swap(bytes[0], bytes[2]);
}
env->ReleaseIntArrayElements(pixels_array, pixels, 0);
*pixels_out = env->NewGlobalRef(pixels_array);
*size_out = frame_size;
base::android::DetachFromVM();
latch->Signal();
}
} // namespace shell

View File

@@ -0,0 +1,79 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_
#define SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_
#include <string>
#include "base/android/jni_android.h"
#include "base/android/jni_weak_ref.h"
#include "lib/ftl/memory/weak_ptr.h"
#include "lib/ftl/synchronization/waitable_event.h"
#include "flutter/shell/common/platform_view.h"
namespace shell {
class AndroidGLContext;
class PlatformViewAndroid : public PlatformView {
public:
static bool Register(JNIEnv* env);
PlatformViewAndroid();
~PlatformViewAndroid() override;
void Detach(JNIEnv* env, jobject obj);
void SurfaceCreated(JNIEnv* env, jobject obj, jobject jsurface);
void SurfaceChanged(JNIEnv* env, jobject obj, jint backgroundColor);
void SurfaceDestroyed(JNIEnv* env, jobject obj);
base::android::ScopedJavaLocalRef<jobject> GetBitmap(JNIEnv* env,
jobject obj);
ftl::WeakPtr<shell::PlatformView> GetWeakViewPtr() override;
uint64_t DefaultFramebuffer() const override;
bool ContextMakeCurrent() override;
bool ResourceContextMakeCurrent() override;
bool SwapBuffers() override;
virtual SkISize GetSize();
virtual void Resize(const SkISize& size);
virtual void RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory);
void set_flutter_view(const JavaObjectWeakGlobalRef& flutter_view) {
flutter_view_ = flutter_view;
}
private:
void ReleaseSurface();
void GetBitmapGpuTask(ftl::AutoResetWaitableEvent* latch,
jobject* pixels_out,
SkISize* size_out);
std::unique_ptr<AndroidGLContext> context_;
ftl::WeakPtrFactory<PlatformViewAndroid> weak_factory_;
JavaObjectWeakGlobalRef flutter_view_;
void UpdateThreadPriorities();
FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroid);
};
} // namespace shell
#endif // SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_

View File

@@ -0,0 +1,20 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_mac || is_ios)
group("darwin") {
if (is_mac) {
deps = [
"desktop:shell_application_bundle",
"desktop:shell_standalone",
]
} else if (is_ios) {
deps = [
"ios:flutter_framework",
]
} else {
assert(false, "Unknown darwin platform type.")
}
}

View File

@@ -0,0 +1,43 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
source_set("common") {
# Disable the assignment filter because the files will be used on iOS as well
# as Mac.
set_sources_assignment_filter([])
sources = [
"platform_mac.h",
"platform_mac.mm",
"platform_service_provider.cc",
"platform_service_provider.h",
"view_service_provider.cc",
"view_service_provider.h",
]
set_sources_assignment_filter(sources_assignment_filter)
deps = [
"//base",
"//base:i18n",
"//dart/runtime:libdart",
"//flutter/runtime",
"//flutter/services/activity",
"//flutter/services/editing",
"//flutter/services/engine:interfaces",
"//flutter/services/media",
"//flutter/services/platform",
"//flutter/services/pointer:interfaces",
"//flutter/services/vsync",
"//flutter/shell/common",
"//flutter/shell/gpu",
"//flutter/shell/testing",
"//flutter/skia",
"//flutter/sky/engine/wtf",
"//lib/ftl",
"//mojo/common",
"//mojo/edk/base_edk",
"//mojo/edk/system",
"//mojo/public/cpp/bindings:utility",
"//mojo/public/interfaces/application",
]
}

View File

@@ -0,0 +1,18 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_MAC_PLATFORM_MAC_H_
#define SHELL_PLATFORM_MAC_PLATFORM_MAC_H_
#include "flutter/services/engine/sky_engine.mojom.h"
namespace shell {
void PlatformMacMain(int argc, const char* argv[], std::string icu_data_path);
bool AttemptLaunchFromCommandLineSwitches(sky::SkyEnginePtr& engine);
} // namespace shell
#endif // SHELL_PLATFORM_MAC_PLATFORM_MAC_H_

View File

@@ -0,0 +1,210 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/platform_mac.h"
#include <Foundation/Foundation.h>
#include <asl.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/message_loop/message_loop.h"
#include "base/trace_event/trace_event.h"
#include "dart/runtime/include/dart_tools_api.h"
#include "flutter/runtime/start_up.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/tracing_controller.h"
#include "flutter/shell/common/ui_delegate.h"
#include "flutter/sky/engine/wtf/MakeUnique.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
namespace shell {
static void InitializeLogging() {
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
logging::InitLogging(settings);
logging::SetLogItems(false, // Process ID
false, // Thread ID
false, // Timestamp
false); // Tick count
}
static void RedirectIOConnectionsToSyslog() {
#if TARGET_OS_IPHONE
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
shell::switches::kNoRedirectToSyslog)) {
return;
}
asl_log_descriptor(NULL, NULL, ASL_LEVEL_INFO, STDOUT_FILENO,
ASL_LOG_DESCRIPTOR_WRITE);
asl_log_descriptor(NULL, NULL, ASL_LEVEL_NOTICE, STDERR_FILENO,
ASL_LOG_DESCRIPTOR_WRITE);
#endif
}
class EmbedderState {
public:
EmbedderState(int argc, const char* argv[], std::string icu_data_path) {
#if TARGET_OS_IPHONE
// This calls crashes on MacOS because we haven't run Dart_Initialize yet.
// See https://github.com/flutter/flutter/issues/4006
blink::engine_main_enter_ts = Dart_TimelineGetMicros();
#endif
CHECK([NSThread isMainThread])
<< "Embedder initialization must occur on the main platform thread";
base::CommandLine::Init(argc, argv);
RedirectIOConnectionsToSyslog();
InitializeLogging();
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(shell::switches::kTraceStartup)) {
// Usually, all tracing within flutter is managed via the tracing
// controller
// The tracing controller is accessed via the shell instance. This means
// that tracing can only be enabled once that instance is created. Traces
// early in startup are lost. This enables tracing only in base manually
// till the tracing controller takes over.
shell::TracingController::StartBaseTracing();
}
// This is about as early as tracing of any kind can start. Add an instant
// marker that can be used as a reference for startup.
TRACE_EVENT_INSTANT0("flutter", "main", TRACE_EVENT_SCOPE_PROCESS);
embedder_message_loop_ = WTF::MakeUnique<base::MessageLoopForUI>();
#if TARGET_OS_IPHONE
// One cannot start the message loop on the platform main thread. Instead,
// we attach to the CFRunLoop
embedder_message_loop_->Attach();
#endif
mojo::embedder::Init(mojo::embedder::CreateSimplePlatformSupport());
shell::Shell::InitStandalone(icu_data_path);
}
~EmbedderState() {
#if !TARGET_OS_IPHONE
embedder_message_loop_.release();
#endif
}
private:
base::AtExitManager exit_manager_;
std::unique_ptr<base::MessageLoopForUI> embedder_message_loop_;
FTL_DISALLOW_COPY_AND_ASSIGN(EmbedderState);
};
void PlatformMacMain(int argc, const char* argv[], std::string icu_data_path) {
static std::unique_ptr<EmbedderState> g_embedder;
static std::once_flag once_main;
std::call_once(once_main, [&]() {
g_embedder = WTF::MakeUnique<EmbedderState>(argc, argv, icu_data_path);
});
}
static bool FlagsValidForCommandLineLaunch(const std::string& dart_main,
const std::string& packages,
const std::string& bundle) {
if (dart_main.empty() || packages.empty() || bundle.empty()) {
return false;
}
// Ensure that the paths exists. This catches cases where the user has
// successfully launched the application from the tooling but has since moved
// the source files on disk and is launching again directly.
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:@(dart_main.c_str())]) {
return false;
}
if (![manager fileExistsAtPath:@(packages.c_str())]) {
return false;
}
if (![manager fileExistsAtPath:@(bundle.c_str())]) {
return false;
}
return true;
}
static std::string ResolveCommandLineLaunchFlag(const char* name) {
auto command_line = *base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(name)) {
return command_line.GetSwitchValueASCII(name);
}
const char* saved_default =
[[NSUserDefaults standardUserDefaults] stringForKey:@(name)].UTF8String;
if (saved_default != NULL) {
return saved_default;
}
return "";
}
bool AttemptLaunchFromCommandLineSwitches(sky::SkyEnginePtr& engine) {
base::mac::ScopedNSAutoreleasePool pool;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
auto command_line = *base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kMainDartFile) ||
command_line.HasSwitch(switches::kPackages) ||
command_line.HasSwitch(switches::kFLX)) {
// The main dart file, flx bundle and the package root must be specified in
// one go. We dont want to end up in a situation where we take one value
// from the command line and the others from user defaults. In case, any
// new flags are specified, forget about all the old ones.
[defaults removeObjectForKey:@(switches::kMainDartFile)];
[defaults removeObjectForKey:@(switches::kPackages)];
[defaults removeObjectForKey:@(switches::kFLX)];
[defaults synchronize];
}
std::string dart_main = ResolveCommandLineLaunchFlag(switches::kMainDartFile);
std::string packages = ResolveCommandLineLaunchFlag(switches::kPackages);
std::string bundle = ResolveCommandLineLaunchFlag(switches::kFLX);
if (!FlagsValidForCommandLineLaunch(dart_main, packages, bundle)) {
return false;
}
// Save the newly resolved dart main file and the package root to user
// defaults so that the next time the user launches the application in the
// simulator without the tooling, the application boots up.
[defaults setObject:@(dart_main.c_str()) forKey:@(switches::kMainDartFile)];
[defaults setObject:@(packages.c_str()) forKey:@(switches::kPackages)];
[defaults setObject:@(bundle.c_str()) forKey:@(switches::kFLX)];
[defaults synchronize];
// Finally launch with the newly resolved arguments.
engine->RunFromFile(dart_main, packages, bundle);
return true;
}
} // namespace shell

View File

@@ -0,0 +1,101 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/platform_service_provider.h"
#if TARGET_OS_IPHONE
#include "flutter/services/activity/ios/activity_impl.h"
#include "flutter/services/editing/ios/clipboard_impl.h"
#include "flutter/services/media/ios/media_player_impl.h"
#include "flutter/services/media/ios/media_service_impl.h"
#include "flutter/services/platform/ios/haptic_feedback_impl.h"
#include "flutter/services/platform/ios/path_provider_impl.h"
#include "flutter/services/platform/ios/system_chrome_impl.h"
#include "flutter/services/platform/ios/system_sound_impl.h"
#include "flutter/services/platform/ios/url_launcher_impl.h"
#include "flutter/services/vsync/ios/vsync_provider_ios_impl.h"
#else
#include "flutter/services/vsync/mac/vsync_provider_mac_impl.h"
#endif // TARGET_OS_IPHONE
namespace shell {
PlatformServiceProvider::PlatformServiceProvider(
mojo::InterfaceRequest<mojo::ServiceProvider> request,
DynamicServiceProviderCallback callback)
: dynamic_service_provider_(callback), binding_(this, request.Pass()) {}
PlatformServiceProvider::~PlatformServiceProvider() {}
void PlatformServiceProvider::ConnectToService(
const mojo::String& service_name,
mojo::ScopedMessagePipeHandle client_handle) {
#if TARGET_OS_IPHONE
if (service_name == ::media::MediaPlayer::Name_) {
new sky::services::media::MediaPlayerImpl(
mojo::InterfaceRequest<::media::MediaPlayer>(client_handle.Pass()));
return;
}
if (service_name == ::media::MediaService::Name_) {
new sky::services::media::MediaServiceImpl(
mojo::InterfaceRequest<::media::MediaService>(client_handle.Pass()));
return;
}
if (service_name == ::activity::Activity::Name_) {
new sky::services::activity::ActivityImpl(
mojo::InterfaceRequest<::activity::Activity>(client_handle.Pass()));
return;
}
if (service_name == ::editing::Clipboard::Name_) {
new sky::services::editing::ClipboardImpl(
mojo::InterfaceRequest<::editing::Clipboard>(client_handle.Pass()));
return;
}
if (service_name == flutter::platform::HapticFeedback::Name_) {
new flutter::platform::HapticFeedbackImpl(
mojo::InterfaceRequest<flutter::platform::HapticFeedback>(
client_handle.Pass()));
return;
}
if (service_name == flutter::platform::PathProvider::Name_) {
new flutter::platform::PathProviderImpl(
mojo::InterfaceRequest<flutter::platform::PathProvider>(
client_handle.Pass()));
return;
}
if (service_name == flutter::platform::SystemChrome::Name_) {
new flutter::platform::SystemChromeImpl(
mojo::InterfaceRequest<flutter::platform::SystemChrome>(
client_handle.Pass()));
return;
}
if (service_name == flutter::platform::SystemSound::Name_) {
new flutter::platform::SystemSoundImpl(
mojo::InterfaceRequest<flutter::platform::SystemSound>(
client_handle.Pass()));
return;
}
if (service_name == flutter::platform::URLLauncher::Name_) {
new flutter::platform::URLLauncherImpl(
mojo::InterfaceRequest<flutter::platform::URLLauncher>(
client_handle.Pass()));
return;
}
if (service_name == ::vsync::VSyncProvider::Name_) {
new sky::services::vsync::VsyncProviderIOSImpl(
mojo::InterfaceRequest<::vsync::VSyncProvider>(client_handle.Pass()));
return;
}
#else // TARGET_OS_IPHONE
if (service_name == ::vsync::VSyncProvider::Name_) {
new sky::services::vsync::VsyncProviderMacImpl(
mojo::InterfaceRequest<::vsync::VSyncProvider>(client_handle.Pass()));
return;
}
#endif // TARGET_OS_IPHONE
dynamic_service_provider_.Run(service_name, client_handle.Pass());
}
} // namespace shell

View File

@@ -0,0 +1,38 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_MAC_PLATFORM_SERVICE_PROVIDER_H_
#define SHELL_PLATFORM_MAC_PLATFORM_SERVICE_PROVIDER_H_
#include "base/callback.h"
#include "lib/ftl/macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"
namespace shell {
class PlatformServiceProvider : public mojo::ServiceProvider {
public:
using DynamicServiceProviderCallback =
base::Callback<void(const mojo::String& service_name,
mojo::ScopedMessagePipeHandle)>;
PlatformServiceProvider(mojo::InterfaceRequest<mojo::ServiceProvider> request,
DynamicServiceProviderCallback callback);
~PlatformServiceProvider() override;
void ConnectToService(const mojo::String& service_name,
mojo::ScopedMessagePipeHandle client_handle) override;
private:
DynamicServiceProviderCallback dynamic_service_provider_;
mojo::StrongBinding<mojo::ServiceProvider> binding_;
FTL_DISALLOW_COPY_AND_ASSIGN(PlatformServiceProvider);
};
} // namespace shell
#endif // SHELL_PLATFORM_MAC_PLATFORM_SERVICE_PROVIDER_H_

View File

@@ -0,0 +1,37 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/view_service_provider.h"
#include <utility>
namespace shell {
ViewServiceProvider::ViewServiceProvider(
AppMesssagesConnector connect_to_app_messages,
mojo::InterfaceRequest<mojo::ServiceProvider> request)
: binding_(this, request.Pass()),
connect_to_app_messages_(connect_to_app_messages) {}
ViewServiceProvider::~ViewServiceProvider() {}
void ViewServiceProvider::ConnectToService(
const mojo::String& service_name,
mojo::ScopedMessagePipeHandle client_handle) {
if (service_name == ::flutter::platform::ApplicationMessages::Name_) {
connect_to_app_messages_(
mojo::InterfaceRequest<::flutter::platform::ApplicationMessages>(
std::move(client_handle)));
return;
}
#if TARGET_OS_IPHONE
if (service_name == ::editing::Keyboard::Name_) {
new sky::services::editing::KeyboardImpl(
mojo::InterfaceRequest<::editing::Keyboard>(std::move(client_handle)));
return;
}
#endif
}
} // namespace shell

View File

@@ -0,0 +1,44 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_MAC_VIEW_SERVICE_PROVIDER_H_
#define SHELL_PLATFORM_MAC_VIEW_SERVICE_PROVIDER_H_
#include <functional>
#include "flutter/services/platform/app_messages.mojom.h"
#include "flutter/sky/engine/wtf/Assertions.h"
#include "lib/ftl/macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"
#if TARGET_OS_IPHONE
#include "flutter/services/editing/ios/keyboard_impl.h"
#endif
namespace shell {
typedef std::function<void(
mojo::InterfaceRequest<flutter::platform::ApplicationMessages>)>
AppMesssagesConnector;
class ViewServiceProvider : public mojo::ServiceProvider {
public:
ViewServiceProvider(AppMesssagesConnector connect_to_app_messages,
mojo::InterfaceRequest<mojo::ServiceProvider> request);
~ViewServiceProvider() override;
void ConnectToService(const mojo::String& service_name,
mojo::ScopedMessagePipeHandle client_handle) override;
private:
mojo::StrongBinding<mojo::ServiceProvider> binding_;
AppMesssagesConnector connect_to_app_messages_;
FTL_DISALLOW_COPY_AND_ASSIGN(ViewServiceProvider);
};
} // namespace shell
#endif // SHELL_PLATFORM_MAC_VIEW_SERVICE_PROVIDER_H_

View File

@@ -0,0 +1,60 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/config/mac/rules.gni")
assert(is_mac)
source_set("mac_desktop_platform") {
visibility = [ ":*" ]
sources = [
"main_mac.mm",
"platform_view_mac.h",
"platform_view_mac.mm",
"sky_app_delegate.h",
"sky_app_delegate.m",
"sky_application.h",
"sky_application.mm",
"sky_window.h",
"sky_window.mm",
]
deps = [
"//base",
"//flutter/services/pointer:interfaces",
"//flutter/shell/common",
"//flutter/shell/platform/darwin/common",
"//flutter/shell/testing",
"//flutter/skia",
"//flutter/synchronization",
"//lib/ftl",
]
}
executable("shell_standalone") {
output_name = "sky_shell"
deps = [
":mac_desktop_platform",
]
}
mac_app("shell_application_bundle") {
app_name = "SkyShell"
info_plist = "Info.plist"
xibs = [ "sky_mac.xib" ]
resource_copy_mac("mac_desktop_resources") {
resources = [
"//third_party/icu/android/icudtl.dat",
]
bundle_directory = "."
}
deps = [
":mac_desktop_platform",
":mac_desktop_resources",
]
}

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>SkyShell</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>org.domokit.sky</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Flutter</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>10.6</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright 2015 The Flutter Authors. All rights reserved.</string>
<key>NSMainNibFile</key>
<string>sky_mac</string>
<key>NSPrincipalClass</key>
<string>SkyApplication</string>
</dict>
</plist>

View File

@@ -0,0 +1,52 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#include <iostream>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
#include "flutter/shell/platform/darwin/desktop/sky_application.h"
#include "flutter/shell/testing/testing.h"
namespace shell {
namespace {
void AttachMessageLoopToMainRunLoop(void) {
// We want to call Run() on the MessageLoopForUI but after NSApplicationMain.
// If called before this point, the call is blocking and will prevent the
// NSApplicationMain invocation.
dispatch_async(dispatch_get_main_queue(), ^() {
base::MessageLoopForUI::current()->Run();
});
}
} // namespace
} // namespace shell
int main(int argc, const char* argv[]) {
[SkyApplication sharedApplication];
shell::PlatformMacMain(argc, argv, "");
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(shell::switches::kHelp)) {
shell::switches::PrintUsage("SkyShell");
return EXIT_SUCCESS;
}
if (command_line.HasSwitch(shell::switches::kNonInteractive)) {
if (!shell::InitForTesting())
return 1;
base::MessageLoop::current()->Run();
return EXIT_SUCCESS;
}
shell::AttachMessageLoopToMainRunLoop();
return NSApplicationMain(argc, argv);
}

View File

@@ -0,0 +1,60 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_MAC_PLATFORM_VIEW_MAC_H_
#define SHELL_PLATFORM_MAC_PLATFORM_VIEW_MAC_H_
#include "base/mac/scoped_nsobject.h"
#include "flutter/shell/common/platform_view.h"
#include "lib/ftl/memory/weak_ptr.h"
@class NSOpenGLView;
@class NSOpenGLContext;
namespace shell {
class PlatformViewMac : public PlatformView {
public:
PlatformViewMac(NSOpenGLView* gl_view);
~PlatformViewMac() override;
void SetupAndLoadDart();
sky::SkyEnginePtr& engineProxy();
ftl::WeakPtr<PlatformView> GetWeakViewPtr() override;
uint64_t DefaultFramebuffer() const override;
bool ContextMakeCurrent() override;
bool ResourceContextMakeCurrent() override;
bool SwapBuffers() override;
void RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) override;
private:
base::scoped_nsobject<NSOpenGLView> opengl_view_;
base::scoped_nsobject<NSOpenGLContext> resource_loading_context_;
sky::SkyEnginePtr sky_engine_;
ftl::WeakPtrFactory<PlatformViewMac> weak_factory_;
bool IsValid() const;
void ConnectToEngineAndSetupServices();
void SetupAndLoadFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory);
FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewMac);
};
} // namespace shell
#endif // SHELL_PLATFORM_MAC_PLATFORM_VIEW_MAC_H_

View File

@@ -0,0 +1,168 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/desktop/platform_view_mac.h"
#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
#include "base/command_line.h"
#include "base/trace_event/trace_event.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
#include "flutter/shell/platform/darwin/common/platform_service_provider.h"
#include "flutter/shell/platform/darwin/common/view_service_provider.h"
#include "lib/ftl/synchronization/waitable_event.h"
namespace shell {
PlatformViewMac::PlatformViewMac(NSOpenGLView* gl_view)
: opengl_view_([gl_view retain]),
resource_loading_context_([[NSOpenGLContext alloc]
initWithFormat:gl_view.pixelFormat
shareContext:gl_view.openGLContext]),
weak_factory_(this) {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if (paths.count > 0) {
shell::Shell::Shared().tracing_controller().set_traces_base_path(
[[paths objectAtIndex:0] UTF8String]);
}
}
PlatformViewMac::~PlatformViewMac() = default;
static void DynamicServiceResolve(const mojo::String& service_name,
mojo::ScopedMessagePipeHandle handle) {
// This platform does not support dynamic service loading.
}
static void IgnoreRequest(
mojo::InterfaceRequest<flutter::platform::ApplicationMessages>) {}
void PlatformViewMac::ConnectToEngineAndSetupServices() {
ConnectToEngine(mojo::GetProxy(&sky_engine_));
mojo::ServiceProviderPtr service_provider;
new PlatformServiceProvider(mojo::GetProxy(&service_provider),
base::Bind(DynamicServiceResolve));
mojo::ServiceProviderPtr view_service_provider;
new ViewServiceProvider(IgnoreRequest,
mojo::GetProxy(&view_service_provider));
sky::ServicesDataPtr services = sky::ServicesData::New();
services->incoming_services = service_provider.Pass();
services->view_services = view_service_provider.Pass();
sky_engine_->SetServices(services.Pass());
}
void PlatformViewMac::SetupAndLoadDart() {
ConnectToEngineAndSetupServices();
if (AttemptLaunchFromCommandLineSwitches(sky_engine_)) {
// This attempts launching from an FLX bundle that does not contain a
// dart snapshot.
return;
}
base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
std::string bundle_path = command_line.GetSwitchValueASCII(switches::kFLX);
if (!bundle_path.empty()) {
std::string script_uri = std::string("file://") + bundle_path;
sky_engine_->RunFromBundle(script_uri, bundle_path);
return;
}
auto args = command_line.GetArgs();
if (args.size() > 0) {
auto packages = command_line.GetSwitchValueASCII(switches::kPackages);
sky_engine_->RunFromFile(args[0], packages, "");
return;
}
}
void PlatformViewMac::SetupAndLoadFromSource(
const std::string& main,
const std::string& packages,
const std::string& assets_directory) {
ConnectToEngineAndSetupServices();
sky_engine_->RunFromFile(main, packages, assets_directory);
}
sky::SkyEnginePtr& PlatformViewMac::engineProxy() {
return sky_engine_;
}
ftl::WeakPtr<PlatformView> PlatformViewMac::GetWeakViewPtr() {
return weak_factory_.GetWeakPtr();
}
uint64_t PlatformViewMac::DefaultFramebuffer() const {
// Default window bound framebuffer FBO 0.
return 0;
}
bool PlatformViewMac::ContextMakeCurrent() {
if (!IsValid()) {
return false;
}
[opengl_view_.get().openGLContext makeCurrentContext];
return true;
}
bool PlatformViewMac::ResourceContextMakeCurrent() {
NSOpenGLContext* context = resource_loading_context_.get();
if (context == nullptr) {
return false;
}
[context makeCurrentContext];
return true;
}
bool PlatformViewMac::SwapBuffers() {
TRACE_EVENT0("flutter", "PlatformViewMac::SwapBuffers");
if (!IsValid()) {
return false;
}
[opengl_view_.get().openGLContext flushBuffer];
return true;
}
bool PlatformViewMac::IsValid() const {
if (opengl_view_ == nullptr) {
return false;
}
auto context = opengl_view_.get().openGLContext;
if (context == nullptr) {
return false;
}
return true;
}
void PlatformViewMac::RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) {
auto latch = new ftl::ManualResetWaitableEvent();
dispatch_async(dispatch_get_main_queue(), ^{
SetupAndLoadFromSource(main, packages, assets_directory);
latch->Signal();
});
latch->Wait();
delete latch;
}
} // namespace shell

View File

@@ -0,0 +1,9 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
@interface SkyAppDelegate : NSObject<NSApplicationDelegate>
@end

View File

@@ -0,0 +1,15 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "sky_app_delegate.h"
@interface SkyAppDelegate ()
@property(assign) IBOutlet NSWindow* window;
@end
@implementation SkyAppDelegate
@end

View File

@@ -0,0 +1,18 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef __SHELL_MAC_SKY_APPLICATION__
#define __SHELL_MAC_SKY_APPLICATION__
#import <AppKit/AppKit.h>
#include "base/mac/scoped_sending_event.h"
#include "base/message_loop/message_pump_mac.h"
// A specific subclass of NSApplication is necessary on Mac in order to
// interact correctly with the main runloop.
@interface SkyApplication : NSApplication<CrAppProtocol, CrAppControlProtocol>
@end
#endif /* defined(__SHELL_MAC_SKY_APPLICATION__) */

View File

@@ -0,0 +1,39 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/desktop/sky_application.h"
#include "base/auto_reset.h"
#include "base/logging.h"
@implementation SkyApplication {
BOOL handlingSendEvent_;
}
+ (void)initialize {
if (self == [SkyApplication class]) {
NSApplication* app = [SkyApplication sharedApplication];
DCHECK([app conformsToProtocol:@protocol(CrAppControlProtocol)])
<< "Existing NSApp (class " << [[app className] UTF8String]
<< ") does not conform to required protocol.";
DCHECK(base::MessagePumpMac::UsingCrApp())
<< "MessagePumpMac::Create() was called before "
<< "+[SkyApplication initialize]";
}
}
- (void)sendEvent:(NSEvent*)event {
base::AutoReset<BOOL> scoper(&handlingSendEvent_, YES);
[super sendEvent:event];
}
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent {
handlingSendEvent_ = handlingSendEvent;
}
- (BOOL)isHandlingSendEvent {
return handlingSendEvent_;
}
@end

View File

@@ -0,0 +1,695 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="7702" systemVersion="14E46" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="7702"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="SkyApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="SkyAppDelegate">
<connections>
<outlet property="window" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="Flutter" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Flutter" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About Flutter" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide Flutter" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit Flutter" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="dMs-cI-mzQ">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="File" id="bib-Uj-vzu">
<items>
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
<connections>
<action selector="newDocument:" target="-1" id="4Si-XN-c54"/>
</connections>
</menuItem>
<menuItem title="Open…" keyEquivalent="o" id="IAo-SY-fd9">
<connections>
<action selector="openDocument:" target="-1" id="bVn-NM-KNZ"/>
</connections>
</menuItem>
<menuItem title="Open Recent" id="tXI-mr-wws">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Open Recent" systemMenu="recentDocuments" id="oas-Oc-fiZ">
<items>
<menuItem title="Clear Menu" id="vNY-rz-j42">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="clearRecentDocuments:" target="-1" id="Daa-9d-B3U"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
<connections>
<action selector="performClose:" target="-1" id="HmO-Ls-i7Q"/>
</connections>
</menuItem>
<menuItem title="Save…" keyEquivalent="s" id="pxx-59-PXV">
<connections>
<action selector="saveDocument:" target="-1" id="teZ-XB-qJY"/>
</connections>
</menuItem>
<menuItem title="Save As…" keyEquivalent="S" id="Bw7-FT-i3A">
<connections>
<action selector="saveDocumentAs:" target="-1" id="mDf-zr-I0C"/>
</connections>
</menuItem>
<menuItem title="Revert to Saved" id="KaW-ft-85H">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="revertDocumentToSaved:" target="-1" id="iJ3-Pv-kwq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
<menuItem title="Page Setup…" keyEquivalent="P" id="qIS-W8-SiK">
<modifierMask key="keyEquivalentModifierMask" shift="YES" command="YES"/>
<connections>
<action selector="runPageLayout:" target="-1" id="Din-rz-gC5"/>
</connections>
</menuItem>
<menuItem title="Print…" keyEquivalent="p" id="aTl-1u-JFS">
<connections>
<action selector="print:" target="-1" id="qaZ-4w-aoO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Format" id="jxT-CU-nIS">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Format" id="GEO-Iw-cKr">
<items>
<menuItem title="Font" id="Gi5-1S-RQB">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Font" systemMenu="font" id="aXa-aM-Jaq">
<items>
<menuItem title="Show Fonts" keyEquivalent="t" id="Q5e-8K-NDq">
<connections>
<action selector="orderFrontFontPanel:" target="YLy-65-1bz" id="WHr-nq-2xA"/>
</connections>
</menuItem>
<menuItem title="Bold" tag="2" keyEquivalent="b" id="GB9-OM-e27">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="hqk-hr-sYV"/>
</connections>
</menuItem>
<menuItem title="Italic" tag="1" keyEquivalent="i" id="Vjx-xi-njq">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="IHV-OB-c03"/>
</connections>
</menuItem>
<menuItem title="Underline" keyEquivalent="u" id="WRG-CD-K1S">
<connections>
<action selector="underline:" target="-1" id="FYS-2b-JAY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="5gT-KC-WSO"/>
<menuItem title="Bigger" tag="3" keyEquivalent="+" id="Ptp-SP-VEL">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="Uc7-di-UnL"/>
</connections>
</menuItem>
<menuItem title="Smaller" tag="4" keyEquivalent="-" id="i1d-Er-qST">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="HcX-Lf-eNd"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kx3-Dk-x3B"/>
<menuItem title="Kern" id="jBQ-r6-VK2">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Kern" id="tlD-Oa-oAM">
<items>
<menuItem title="Use Default" id="GUa-eO-cwY">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardKerning:" target="-1" id="6dk-9l-Ckg"/>
</connections>
</menuItem>
<menuItem title="Use None" id="cDB-IK-hbR">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffKerning:" target="-1" id="U8a-gz-Maa"/>
</connections>
</menuItem>
<menuItem title="Tighten" id="46P-cB-AYj">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="tightenKerning:" target="-1" id="hr7-Nz-8ro"/>
</connections>
</menuItem>
<menuItem title="Loosen" id="ogc-rX-tC1">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="loosenKerning:" target="-1" id="8i4-f9-FKE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Ligatures" id="o6e-r0-MWq">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Ligatures" id="w0m-vy-SC9">
<items>
<menuItem title="Use Default" id="agt-UL-0e3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardLigatures:" target="-1" id="7uR-wd-Dx6"/>
</connections>
</menuItem>
<menuItem title="Use None" id="J7y-lM-qPV">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffLigatures:" target="-1" id="iX2-gA-Ilz"/>
</connections>
</menuItem>
<menuItem title="Use All" id="xQD-1f-W4t">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useAllLigatures:" target="-1" id="KcB-kA-TuK"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Baseline" id="OaQ-X3-Vso">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Baseline" id="ijk-EB-dga">
<items>
<menuItem title="Use Default" id="3Om-Ey-2VK">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unscript:" target="-1" id="0vZ-95-Ywn"/>
</connections>
</menuItem>
<menuItem title="Superscript" id="Rqc-34-cIF">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="superscript:" target="-1" id="3qV-fo-wpU"/>
</connections>
</menuItem>
<menuItem title="Subscript" id="I0S-gh-46l">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="subscript:" target="-1" id="Q6W-4W-IGz"/>
</connections>
</menuItem>
<menuItem title="Raise" id="2h7-ER-AoG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="raiseBaseline:" target="-1" id="4sk-31-7Q9"/>
</connections>
</menuItem>
<menuItem title="Lower" id="1tx-W0-xDw">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowerBaseline:" target="-1" id="OF1-bc-KW4"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="Ndw-q3-faq"/>
<menuItem title="Show Colors" keyEquivalent="C" id="bgn-CT-cEk">
<connections>
<action selector="orderFrontColorPanel:" target="-1" id="mSX-Xz-DV3"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="iMs-zA-UFJ"/>
<menuItem title="Copy Style" keyEquivalent="c" id="5Vv-lz-BsD">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="copyFont:" target="-1" id="GJO-xA-L4q"/>
</connections>
</menuItem>
<menuItem title="Paste Style" keyEquivalent="v" id="vKC-jM-MkH">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteFont:" target="-1" id="JfD-CL-leO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Text" id="Fal-I4-PZk">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Text" id="d9c-me-L2H">
<items>
<menuItem title="Align Left" keyEquivalent="{" id="ZM1-6Q-yy1">
<connections>
<action selector="alignLeft:" target="-1" id="zUv-R1-uAa"/>
</connections>
</menuItem>
<menuItem title="Center" keyEquivalent="|" id="VIY-Ag-zcb">
<connections>
<action selector="alignCenter:" target="-1" id="spX-mk-kcS"/>
</connections>
</menuItem>
<menuItem title="Justify" id="J5U-5w-g23">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="alignJustified:" target="-1" id="ljL-7U-jND"/>
</connections>
</menuItem>
<menuItem title="Align Right" keyEquivalent="}" id="wb2-vD-lq4">
<connections>
<action selector="alignRight:" target="-1" id="r48-bG-YeY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4s2-GY-VfK"/>
<menuItem title="Writing Direction" id="H1b-Si-o9J">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Writing Direction" id="8mr-sm-Yjd">
<items>
<menuItem title="Paragraph" enabled="NO" id="ZvO-Gk-QUH">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="YGs-j5-SAR">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionNatural:" target="-1" id="qtV-5e-UBP"/>
</connections>
</menuItem>
<menuItem id="Lbh-J2-qVU">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionLeftToRight:" target="-1" id="S0X-9S-QSf"/>
</connections>
</menuItem>
<menuItem id="jFq-tB-4Kx">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionRightToLeft:" target="-1" id="5fk-qB-AqJ"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="swp-gr-a21"/>
<menuItem title="Selection" enabled="NO" id="cqv-fj-IhA">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="Nop-cj-93Q">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionNatural:" target="-1" id="lPI-Se-ZHp"/>
</connections>
</menuItem>
<menuItem id="BgM-ve-c93">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionLeftToRight:" target="-1" id="caW-Bv-w94"/>
</connections>
</menuItem>
<menuItem id="RB4-Sm-HuC">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionRightToLeft:" target="-1" id="EXD-6r-ZUu"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="fKy-g9-1gm"/>
<menuItem title="Show Ruler" id="vLm-3I-IUL">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleRuler:" target="-1" id="FOx-HJ-KwY"/>
</connections>
</menuItem>
<menuItem title="Copy Ruler" keyEquivalent="c" id="MkV-Pr-PK5">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="copyRuler:" target="-1" id="71i-fW-3W2"/>
</connections>
</menuItem>
<menuItem title="Paste Ruler" keyEquivalent="v" id="LVM-kO-fVI">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="pasteRuler:" target="-1" id="cSh-wd-qM2"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="toggleToolbarShown:" target="-1" id="BXY-wc-z0C"/>
</connections>
</menuItem>
<menuItem title="Customize Toolbar…" id="1UK-8n-QPP">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="runToolbarCustomizationPalette:" target="-1" id="pQI-g3-MTW"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="wpr-3q-Mcd">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
<items>
<menuItem title="Flutter Help" keyEquivalent="?" id="FKE-Sm-Kum">
<connections>
<action selector="showHelp:" target="-1" id="y7X-2Q-9no"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<window title="Flutter" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="SkyWindow">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="335" y="390" width="480" height="360"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1177"/>
<view key="contentView" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<openGLView autoresizesSubviews="NO" useAuxiliaryDepthBufferStencil="NO" useDoubleBufferingEnabled="YES" allowOffline="YES" translatesAutoresizingMaskIntoConstraints="NO" id="AUD-Hu-um3">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
</openGLView>
</subviews>
<constraints>
<constraint firstAttribute="trailing" secondItem="AUD-Hu-um3" secondAttribute="trailing" id="9W1-4Z-nsQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="top" secondItem="EiT-Mj-1SZ" secondAttribute="top" id="KpO-qK-Zhv"/>
<constraint firstAttribute="bottom" secondItem="AUD-Hu-um3" secondAttribute="bottom" id="Myy-UN-4eQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" id="gf3-3r-c0N"/>
</constraints>
</view>
<connections>
<outlet property="renderSurface" destination="AUD-Hu-um3" id="0jv-sx-91g"/>
</connections>
<point key="canvasLocation" x="128" y="455"/>
</window>
</objects>
</document>

View File

@@ -0,0 +1,9 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
@interface SkyWindow : NSWindow
@end

View File

@@ -0,0 +1,155 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "sky_window.h"
#include "base/time/time.h"
#include "flutter/services/pointer/pointer.mojom.h"
#include "flutter/shell/platform/darwin/desktop/platform_view_mac.h"
@interface SkyWindow ()<NSWindowDelegate>
@property(assign) IBOutlet NSOpenGLView* renderSurface;
@property(getter=isSurfaceSetup) BOOL surfaceSetup;
@end
static inline pointer::PointerType EventTypeFromNSEventPhase(
NSEventPhase phase) {
switch (phase) {
case NSEventPhaseNone:
return pointer::PointerType::CANCEL;
case NSEventPhaseBegan:
return pointer::PointerType::DOWN;
case NSEventPhaseStationary:
// There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
// with the same coordinates
case NSEventPhaseChanged:
return pointer::PointerType::MOVE;
case NSEventPhaseEnded:
return pointer::PointerType::UP;
case NSEventPhaseCancelled:
return pointer::PointerType::CANCEL;
case NSEventPhaseMayBegin:
return pointer::PointerType::CANCEL;
}
return pointer::PointerType::CANCEL;
}
@implementation SkyWindow {
std::unique_ptr<shell::PlatformViewMac> _platform_view;
}
@synthesize renderSurface = _renderSurface;
@synthesize surfaceSetup = _surfaceSetup;
- (void)awakeFromNib {
[super awakeFromNib];
self.delegate = self;
[self updateWindowSize];
}
- (void)setupPlatformView {
DCHECK(_platform_view == nullptr)
<< "The platform view must not already be set.";
_platform_view.reset(new shell::PlatformViewMac(self.renderSurface));
_platform_view->SetupResourceContextOnIOThread();
_platform_view->NotifyCreated();
}
// TODO(eseidel): This does not belong in sky_window!
// Probably belongs in NSApplicationDelegate didFinishLaunching.
- (void)setupAndLoadDart {
_platform_view->SetupAndLoadDart();
}
- (void)windowDidResize:(NSNotification*)notification {
[self updateWindowSize];
}
- (void)updateWindowSize {
[self setupSurfaceIfNecessary];
auto metrics = sky::ViewportMetrics::New();
auto size = self.renderSurface.frame.size;
metrics->physical_width = size.width;
metrics->physical_height = size.height;
metrics->device_pixel_ratio = 1.0;
_platform_view->engineProxy()->OnViewportMetricsChanged(metrics.Pass());
}
- (void)setupSurfaceIfNecessary {
if (self.isSurfaceSetup) {
return;
}
self.surfaceSetup = YES;
[self setupPlatformView];
[self setupAndLoadDart];
}
#pragma mark - Responder overrides
- (void)dispatchEvent:(NSEvent*)event phase:(NSEventPhase)phase {
NSPoint location =
[_renderSurface convertPoint:event.locationInWindow fromView:nil];
location.y = _renderSurface.frame.size.height - location.y;
auto pointer_data = pointer::Pointer::New();
pointer_data->time_stamp =
base::TimeDelta::FromSecondsD(event.timestamp).InMicroseconds();
pointer_data->type = EventTypeFromNSEventPhase(phase);
pointer_data->kind = pointer::PointerKind::TOUCH;
pointer_data->pointer = 0;
pointer_data->x = location.x;
pointer_data->y = location.y;
pointer_data->buttons = 0;
pointer_data->down = false;
pointer_data->primary = false;
pointer_data->obscured = false;
pointer_data->pressure = 1.0;
pointer_data->pressure_min = 0.0;
pointer_data->pressure_max = 1.0;
pointer_data->distance = 0.0;
pointer_data->distance_min = 0.0;
pointer_data->distance_max = 0.0;
pointer_data->radius_major = 0.0;
pointer_data->radius_minor = 0.0;
pointer_data->radius_min = 0.0;
pointer_data->radius_max = 0.0;
pointer_data->orientation = 0.0;
pointer_data->tilt = 0.0;
auto pointer_packet = pointer::PointerPacket::New();
pointer_packet->pointers.push_back(pointer_data.Pass());
_platform_view->engineProxy()->OnPointerPacket(pointer_packet.Pass());
}
- (void)mouseDown:(NSEvent*)event {
[self dispatchEvent:event phase:NSEventPhaseBegan];
}
- (void)mouseDragged:(NSEvent*)event {
[self dispatchEvent:event phase:NSEventPhaseChanged];
}
- (void)mouseUp:(NSEvent*)event {
[self dispatchEvent:event phase:NSEventPhaseEnded];
}
- (void)dealloc {
if (_platform_view) {
_platform_view->NotifyDestroyed();
}
[super dealloc];
}
@end

View File

@@ -0,0 +1,161 @@
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_ios)
import("//build/config/ios/rules.gni")
import("//build/config/ios/ios_sdk.gni")
shared_library("flutter_framework_dylib") {
visibility = [ ":*" ]
output_name = "Flutter"
sources = [
"framework/Headers/Flutter.h",
"framework/Headers/FlutterAppDelegate.h",
"framework/Headers/FlutterAsyncMessageListener.h",
"framework/Headers/FlutterDartProject.h",
"framework/Headers/FlutterMacros.h",
"framework/Headers/FlutterMessageListener.h",
"framework/Headers/FlutterViewController.h",
"framework/Source/accessibility_bridge.h",
"framework/Source/accessibility_bridge.mm",
"framework/Source/application_messages_impl.h",
"framework/Source/application_messages_impl.mm",
"framework/Source/flutter_touch_mapper.h",
"framework/Source/flutter_touch_mapper.mm",
"framework/Source/FlutterAppDelegate.mm",
"framework/Source/FlutterDartProject.mm",
"framework/Source/FlutterDartProject_Internal.h",
"framework/Source/FlutterDartSource.h",
"framework/Source/FlutterDartSource.mm",
"framework/Source/FlutterDynamicServiceLoader.h",
"framework/Source/FlutterDynamicServiceLoader.mm",
"framework/Source/FlutterView.h",
"framework/Source/FlutterView.mm",
"framework/Source/FlutterViewController.mm",
"platform_view_ios.h",
"platform_view_ios.mm",
]
deps = [
"//base:base",
"//dart/runtime:libdart",
"//flutter/services/activity",
"//flutter/services/dynamic:embedder",
"//flutter/services/editing",
"//flutter/services/engine:interfaces",
"//flutter/services/media",
"//flutter/services/platform",
"//flutter/services/semantics",
"//flutter/services/vsync",
"//flutter/shell/common",
"//flutter/shell/gpu",
"//flutter/shell/platform/darwin/common",
"//flutter/skia",
"//flutter/sky/engine/platform",
"//flutter/sky/engine/wtf",
"//lib/ftl",
"//mojo/edk/base_edk",
"//mojo/edk/system",
"//mojo/public/cpp/application",
"//mojo/public/cpp/bindings",
"//mojo/public/interfaces/application",
]
defines = [
"FLUTTER_FRAMEWORK"
]
libs = [
"UIKit.framework",
"OpenGLES.framework",
"AVFoundation.framework",
"AudioToolbox.framework",
"QuartzCore.framework",
]
}
group("flutter_framework") {
framework_dir = "$root_out_dir/Flutter.framework"
copy("framework_dylib") {
visibility = [ ":*" ]
sources = [ "$root_out_dir/libFlutter.dylib" ]
outputs = [ "$framework_dir/Flutter" ]
deps = [
":flutter_framework_dylib",
]
}
action("framework_install_name") {
visibility = [ ":*" ]
stamp_file = "$root_out_dir/flutter_install_name_stamp"
script = "//flutter/sky/tools/change_install_name.py"
inputs = [ "$framework_dir/Flutter" ]
outputs = [ stamp_file ]
args = [
"--dylib",
rebase_path("$framework_dir/Flutter"),
"--install_name",
"@rpath/Flutter.framework/Flutter",
"--stamp",
rebase_path(stamp_file),
]
deps = [
":framework_dylib"
]
}
copy("framework_info_plist") {
visibility = [ ":*" ]
sources = [ "framework/Info.plist" ]
outputs = [ "$framework_dir/Info.plist" ]
}
copy("framework_module_map") {
visibility = [ ":*" ]
sources = [ "framework/module.modulemap" ]
outputs = [ "$framework_dir/Modules/module.modulemap" ]
}
copy("framework_headers") {
visibility = [ ":*" ]
sources = [
"framework/Headers/Flutter.h",
"framework/Headers/FlutterAppDelegate.h",
"framework/Headers/FlutterAsyncMessageListener.h",
"framework/Headers/FlutterDartProject.h",
"framework/Headers/FlutterMacros.h",
"framework/Headers/FlutterMessageListener.h",
"framework/Headers/FlutterViewController.h",
]
outputs = [ "$framework_dir/Headers/{{source_file_part}}" ]
}
copy("framework_icu") {
visibility = [ ":*" ]
set_sources_assignment_filter([])
sources = [
"//third_party/icu/android/icudtl.dat",
]
set_sources_assignment_filter(sources_assignment_filter)
outputs = [ "$framework_dir/{{source_file_part}}" ]
}
public_deps = [
":framework_dylib",
":framework_headers",
":framework_icu",
":framework_info_plist",
":framework_install_name",
":framework_module_map",
]
}

View File

@@ -0,0 +1,15 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTER_H_
#define FLUTTER_FLUTTER_H_
#include "FlutterAppDelegate.h"
#include "FlutterAsyncMessageListener.h"
#include "FlutterDartProject.h"
#include "FlutterMacros.h"
#include "FlutterMessageListener.h"
#include "FlutterViewController.h"
#endif // FLUTTER_FLUTTER_H_

View File

@@ -0,0 +1,21 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERAPPDELEGATE_H_
#define FLUTTER_FLUTTERAPPDELEGATE_H_
#import <UIKit/UIKit.h>
#include "FlutterMacros.h"
// Empty implementation of UIApplicationDelegate, for simple apps
// that don't need to customize the application delegate.
FLUTTER_EXPORT
@interface FlutterAppDelegate : UIResponder<UIApplicationDelegate>
@property(strong, nonatomic) UIWindow* window;
@end
#endif // FLUTTER_FLUTTERDARTPROJECT_H_

View File

@@ -0,0 +1,22 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERASYNCMESSAGELISTENER_H_
#define FLUTTER_FLUTTERASYNCMESSAGELISTENER_H_
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
FLUTTER_EXPORT
@protocol FlutterAsyncMessageListener<NSObject>
- (void)didReceiveString:(NSString*)message
callback:(void(^)(NSString*))sendResponse;
@property(readonly, strong, nonatomic) NSString* messageName;
@end
#endif // FLUTTER_FLUTTERASYNCMESSAGELISTENER_H_

View File

@@ -0,0 +1,30 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERDARTPROJECT_H_
#define FLUTTER_FLUTTERDARTPROJECT_H_
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
FLUTTER_EXPORT
@interface FlutterDartProject : NSObject
- (instancetype)initWithPrecompiledDartBundle:(NSBundle*)bundle
NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithFLXArchive:(NSURL*)archiveURL
dartMain:(NSURL*)dartMainURL
packages:(NSURL*)dartPackages
NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithFLXArchiveWithScriptSnapshot:(NSURL*)archiveURL
NS_DESIGNATED_INITIALIZER;
- (instancetype)initFromDefaultSourceForConfiguration;
@end
#endif // FLUTTER_FLUTTERDARTPROJECT_H_

View File

@@ -0,0 +1,18 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERMACROS_H_
#define FLUTTER_FLUTTERMACROS_H_
#if defined(FLUTTER_FRAMEWORK)
#define FLUTTER_EXPORT __attribute__((visibility("default")))
#else // defined(FLUTTER_SDK)
#define FLUTTER_EXPORT
#endif // defined(FLUTTER_SDK)
#endif // FLUTTER_FLUTTERMACROS_H_

View File

@@ -0,0 +1,21 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERMESSAGELISTENER_H_
#define FLUTTER_FLUTTERMESSAGELISTENER_H_
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
FLUTTER_EXPORT
@protocol FlutterMessageListener<NSObject>
- (NSString*)didReceiveString:(NSString*)message;
@property(readonly, strong, nonatomic) NSString* messageName;
@end
#endif // FLUTTER_FLUTTERMESSAGELISTENER_H_

View File

@@ -0,0 +1,47 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERVIEWCONTROLLER_H_
#define FLUTTER_FLUTTERVIEWCONTROLLER_H_
#include <sys/cdefs.h>
#import <UIKit/UIKit.h>
#include "FlutterAsyncMessageListener.h"
#include "FlutterDartProject.h"
#include "FlutterMacros.h"
#include "FlutterMessageListener.h"
FLUTTER_EXPORT
@interface FlutterViewController : UIViewController
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibNameOrNil
bundle:(NSBundle*)nibBundleOrNil
NS_DESIGNATED_INITIALIZER;
- (void)sendString:(NSString*)message withMessageName:(NSString*)messageName;
- (void)sendString:(NSString*)message
withMessageName:(NSString*)messageName
callback:(void (^)(NSString*))callback;
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener;
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener;
- (void)addAsyncMessageListener:(NSObject<FlutterAsyncMessageListener>*)listener;
- (void)removeAsyncMessageListener:(NSObject<FlutterAsyncMessageListener>*)listener;
@end
__BEGIN_DECLS
// Initializes Flutter for this process. Need only be called once per process.
FLUTTER_EXPORT void FlutterInit(int argc, const char* argv[]);
__END_DECLS
#endif // FLUTTER_FLUTTERVIEWCONTROLLER_H_

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>Flutter</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Flutter</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>

View File

@@ -0,0 +1,9 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h"
@implementation FlutterAppDelegate
@end

View File

@@ -0,0 +1,251 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include "base/command_line.h"
#include "dart/runtime/include/dart_api.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h"
#include "flutter/shell/common/switches.h"
static NSURL* URLForSwitch(const char* name) {
auto cmd = *base::CommandLine::ForCurrentProcess();
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (cmd.HasSwitch(name)) {
auto url = [NSURL fileURLWithPath:@(cmd.GetSwitchValueASCII(name).c_str())];
[defaults setURL:url forKey:@(name)];
[defaults synchronize];
return url;
}
return [defaults URLForKey:@(name)];
}
@implementation FlutterDartProject {
NSBundle* _precompiledDartBundle;
FlutterDartSource* _dartSource;
VMType _vmTypeRequirement;
}
#pragma mark - Override base class designated initializers
- (instancetype)init {
return [self initWithFLXArchive:nil dartMain:nil packages:nil];
}
#pragma mark - Designated initializers
- (instancetype)initWithPrecompiledDartBundle:(NSBundle*)bundle {
self = [super init];
if (self) {
_precompiledDartBundle = [bundle retain];
[self checkReadiness];
}
return self;
}
- (instancetype)initWithFLXArchive:(NSURL*)archiveURL
dartMain:(NSURL*)dartMainURL
packages:(NSURL*)dartPackages {
self = [super init];
if (self) {
_dartSource = [[FlutterDartSource alloc] initWithDartMain:dartMainURL
packages:dartPackages
flxArchive:archiveURL];
[self checkReadiness];
}
return self;
}
- (instancetype)initWithFLXArchiveWithScriptSnapshot:(NSURL*)archiveURL {
self = [super init];
if (self) {
_dartSource = [[FlutterDartSource alloc]
initWithFLXArchiveWithScriptSnapshot:archiveURL];
[self checkReadiness];
}
return self;
}
#pragma mark - Convenience initializers
- (instancetype)initFromDefaultSourceForConfiguration {
NSBundle* bundle = [NSBundle mainBundle];
if (Dart_IsPrecompiledRuntime()) {
// Load from an AOTC snapshot.
return [self initWithPrecompiledDartBundle:bundle];
} else {
// Load directly from sources if the appropriate command line flags are
// specified. If not, try loading from a script snapshot in the framework
// bundle.
NSURL* flxURL = URLForSwitch(shell::switches::kFLX);
if (flxURL == nil) {
// If the URL was not specified on the command line, look inside the
// FlutterApplication bundle.
flxURL =
[NSURL fileURLWithPath:[bundle pathForResource:@"app" ofType:@"flx"]
isDirectory:NO];
}
NSURL* dartMainURL = URLForSwitch(shell::switches::kMainDartFile);
NSURL* dartPackagesURL = URLForSwitch(shell::switches::kPackages);
return [self initWithFLXArchive:flxURL
dartMain:dartMainURL
packages:dartPackagesURL];
}
NSAssert(NO, @"Unreachable");
[self release];
return nil;
}
#pragma mark - Common initialization tasks
- (void)checkReadiness {
if (_precompiledDartBundle != nil) {
_vmTypeRequirement = VMTypePrecompilation;
return;
}
if (_dartSource != nil) {
_vmTypeRequirement = VMTypeInterpreter;
return;
}
}
#pragma mark - Launching the project in a preconfigured engine.
static NSString* NSStringFromVMType(VMType type) {
switch (type) {
case VMTypeInvalid:
return @"Invalid";
case VMTypeInterpreter:
return @"Interpreter";
case VMTypePrecompilation:
return @"Precompilation";
}
return @"Unknown";
}
- (void)launchInEngine:(sky::SkyEnginePtr&)engine
embedderVMType:(VMType)embedderVMType
result:(LaunchResult)result {
if (_vmTypeRequirement == VMTypeInvalid) {
result(NO, @"The Dart project is invalid and cannot be loaded by any VM.");
return;
}
if (embedderVMType == VMTypeInvalid) {
result(NO, @"The embedder is invalid.");
return;
}
if (_vmTypeRequirement != embedderVMType) {
NSString* message = [NSString
stringWithFormat:
@"Could not load the project because of differing project type. "
@"The project can run in '%@' but the embedder is configured as "
@"'%@'",
NSStringFromVMType(_vmTypeRequirement),
NSStringFromVMType(embedderVMType)];
result(NO, message);
return;
}
switch (_vmTypeRequirement) {
case VMTypeInterpreter:
[self runFromSourceInEngine:engine result:result];
return;
case VMTypePrecompilation:
[self runFromPrecompiledSourceInEngine:engine result:result];
return;
case VMTypeInvalid:
break;
}
return result(NO, @"Internal error");
}
#pragma mark - Running from precompiled application bundles
- (void)runFromPrecompiledSourceInEngine:(sky::SkyEnginePtr&)engine
result:(LaunchResult)result {
if (![_precompiledDartBundle load]) {
NSString* message = [NSString
stringWithFormat:
@"Could not load the framework ('%@') containing precompiled code.",
_precompiledDartBundle.bundleIdentifier];
result(NO, message);
return;
}
NSString* path =
[_precompiledDartBundle pathForResource:@"app" ofType:@"flx"];
if (path.length == 0) {
NSString* message =
[NSString stringWithFormat:@"Could not find the 'app.flx' archive in "
@"the precompiled Dart bundle with ID '%@'",
_precompiledDartBundle.bundleIdentifier];
result(NO, message);
return;
}
engine->RunFromPrecompiledSnapshot(path.UTF8String);
result(YES, @"Success");
}
#pragma mark - Running from source
- (void)runFromSourceInEngine:(sky::SkyEnginePtr&)engine
result:(LaunchResult)result {
if (_dartSource == nil) {
result(NO, @"Dart source not specified.");
return;
}
[_dartSource validate:^(BOOL success, NSString* message) {
if (!success) {
return result(NO, message);
}
if (_dartSource.archiveContainsScriptSnapshot) {
engine->RunFromBundle("file://script_snapshot",
_dartSource.flxArchive.absoluteURL.path.UTF8String);
} else {
engine->RunFromFile(_dartSource.dartMain.absoluteURL.path.UTF8String,
_dartSource.packages.absoluteURL.path.UTF8String,
_dartSource.flxArchive.absoluteURL.path.UTF8String);
}
result(YES, @"Success");
}];
}
#pragma mark - Misc.
- (void)dealloc {
[_precompiledDartBundle unload];
[_precompiledDartBundle release];
[_dartSource release];
[super dealloc];
}
@end

View File

@@ -0,0 +1,31 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterDartProject.h"
#include "flutter/services/engine/sky_engine.mojom.h"
enum VMType {
// An invalid VM configuration.
VMTypeInvalid = 0,
// VM can execute Dart code as an interpreter.
VMTypeInterpreter,
// VM can execute precompiled Dart code.
VMTypePrecompilation,
};
typedef void (^LaunchResult)(BOOL success, NSString* message);
@interface FlutterDartProject ()
- (void)launchInEngine:(sky::SkyEnginePtr&)engine
embedderVMType:(VMType)type
result:(LaunchResult)result;
@end
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_

View File

@@ -0,0 +1,30 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTSOURCE_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTSOURCE_H_
#import <Foundation/Foundation.h>
typedef void (^ValidationResult)(BOOL result, NSString* message);
@interface FlutterDartSource : NSObject
@property(nonatomic, readonly) NSURL* dartMain;
@property(nonatomic, readonly) NSURL* packages;
@property(nonatomic, readonly) NSURL* flxArchive;
@property(nonatomic, readonly) BOOL archiveContainsScriptSnapshot;
- (instancetype)initWithDartMain:(NSURL*)dartMain
packages:(NSURL*)packages
flxArchive:(NSURL*)flxArchive NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithFLXArchiveWithScriptSnapshot:(NSURL*)flxArchive
NS_DESIGNATED_INITIALIZER;
- (void)validate:(ValidationResult)result;
@end
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERDARTSOURCE_H_

View File

@@ -0,0 +1,105 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h"
@implementation FlutterDartSource
@synthesize dartMain = _dartMain;
@synthesize packages = _packages;
@synthesize flxArchive = _flxArchive;
@synthesize archiveContainsScriptSnapshot = _archiveContainsScriptSnapshot;
#pragma mark - Convenience Initializers
- (instancetype)init {
return [self initWithDartMain:nil packages:nil flxArchive:nil];
}
#pragma mark - Designated Initializers
- (instancetype)initWithDartMain:(NSURL*)dartMain
packages:(NSURL*)packages
flxArchive:(NSURL*)flxArchive {
self = [super init];
if (self) {
_dartMain = [dartMain copy];
_packages = [packages copy];
_flxArchive = [flxArchive copy];
NSFileManager* fileManager = [NSFileManager defaultManager];
const BOOL dartMainExists =
[fileManager fileExistsAtPath:dartMain.absoluteURL.path];
const BOOL packagesExists =
[fileManager fileExistsAtPath:packages.absoluteURL.path];
if (!dartMainExists || !packagesExists) {
// We cannot actually verify this without opening up the archive. This is
// just an assumption.
_archiveContainsScriptSnapshot = YES;
}
}
return self;
}
- (instancetype)initWithFLXArchiveWithScriptSnapshot:(NSURL*)flxArchive {
self = [super init];
if (self) {
_flxArchive = [flxArchive copy];
_archiveContainsScriptSnapshot = YES;
}
return self;
}
static BOOL CheckDartProjectURL(NSMutableString* log,
NSURL* url,
NSString* logLabel) {
if (url == nil) {
[log appendFormat:@"The %@ was not specified.\n", logLabel];
return false;
}
if (!url.isFileURL) {
[log appendFormat:@"The %@ must be a file URL.\n", logLabel];
return false;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:url.absoluteURL.path]) {
[log appendFormat:@"No file found at '%@' when looking for the %@.\n", url,
logLabel];
return false;
}
return true;
}
- (void)validate:(ValidationResult)result {
NSMutableString* log = [[[NSMutableString alloc] init] autorelease];
BOOL isValid = YES;
isValid &= CheckDartProjectURL(log, _flxArchive, @"FLX archive");
if (!_archiveContainsScriptSnapshot) {
isValid &= CheckDartProjectURL(log, _dartMain, @"Dart main");
isValid &= CheckDartProjectURL(log, _packages, @"Dart packages");
}
result(isValid, log);
}
- (void)dealloc {
[_dartMain release];
[_packages release];
[_flxArchive release];
[super dealloc];
}
@end

View File

@@ -0,0 +1,18 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_DYNAMIC_SERVICE_LOADER_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_DYNAMIC_SERVICE_LOADER_H_
#import <Foundation/Foundation.h>
#include "flutter/shell/platform/darwin/common/platform_service_provider.h"
@interface FlutterDynamicServiceLoader : NSObject
- (void)resolveService:(NSString*)name
handle:(mojo::ScopedMessagePipeHandle)handle;
@end
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_DYNAMIC_SERVICE_LOADER_H_

View File

@@ -0,0 +1,178 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h"
#include "base/logging.h"
#include "flutter/services/dynamic/dynamic_service_embedder.h"
#include "flutter/services/dynamic/dynamic_service_definition.h"
#include <Foundation/Foundation.h>
#include <dlfcn.h>
@interface FlutterServiceDefinition : NSObject
@property(nonatomic, readonly) NSString* serviceName;
@property(nonatomic, readonly) NSString* containerFramework;
- (instancetype)initWithName:(NSString*)name framework:(NSString*)framework;
- (void)invokeService:(NSString*)serviceName
handle:(mojo::ScopedMessagePipeHandle)handle;
@end
@implementation FlutterServiceDefinition {
std::unique_ptr<sky::services::DynamicServiceDefinition> _definition;
BOOL _initializationAttempted;
}
- (instancetype)initWithName:(NSString*)name framework:(NSString*)framework {
self = [super init];
if (self) {
if (name.length == 0 || framework.length == 0) {
[self release];
return nil;
}
_serviceName = [name copy];
_containerFramework = [framework copy];
}
return self;
}
- (void)openIfNecessary {
if (_definition || _initializationAttempted) {
return;
}
mojo::String dylib_path([[NSBundle mainBundle]
pathForResource:_containerFramework
ofType:@"dylib"
inDirectory:@"Frameworks"]
.UTF8String);
_definition = sky::services::DynamicServiceDefinition::Initialize(dylib_path);
if (!_definition) {
LOG(ERROR) << "Could not load dynamic service for '"
<< _serviceName.UTF8String << "'";
}
// All known services are in the application bundle. If the service cannot
// be initialized once, dont attempt any more loads.
_initializationAttempted = YES;
}
- (void)invokeService:(NSString*)serviceName
handle:(mojo::ScopedMessagePipeHandle)handle {
[self openIfNecessary];
if (_definition) {
_definition->InvokeServiceHandler(handle.Pass(), serviceName.UTF8String);
}
}
- (void)closeIfNecessary {
_definition = nullptr;
_initializationAttempted = NO;
}
- (void)dealloc {
[self closeIfNecessary];
[_serviceName release];
[_containerFramework release];
[super dealloc];
};
@end
@implementation FlutterDynamicServiceLoader {
NSMutableDictionary* _services;
}
- (instancetype)init {
self = [super init];
if (self) {
_services = [[NSMutableDictionary alloc] init];
[self populateServiceDefinitions];
}
return self;
}
- (void)resolveService:(NSString*)serviceName
handle:(mojo::ScopedMessagePipeHandle)handle {
if (serviceName.length == 0) {
LOG(INFO) << "Invalid service name";
return;
}
[_services[serviceName] invokeService:serviceName handle:handle.Pass()];
}
- (void)populateServiceDefinitions {
NSString* definitionsPath =
[[NSBundle mainBundle] pathForResource:@"ServiceDefinitions"
ofType:@"json"];
if (definitionsPath.length == 0) {
return;
}
NSData* data = [NSData dataWithContentsOfFile:definitionsPath];
if (data.length == 0) {
LOG(INFO) << "The service definitions manifest could not be read. No "
"custom services will be available.";
return;
}
NSError* error = nil;
NSDictionary* servicesData =
[NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error != nil || ![servicesData isKindOfClass:[NSDictionary class]]) {
LOG(INFO) << "Corrupt service definitions manifest. No custom services "
"will be available";
return;
}
NSArray* services = servicesData[@"services"];
if (![services isKindOfClass:[NSArray class]]) {
return;
}
for (NSDictionary* service in services) {
if (![service isKindOfClass:[NSDictionary class]]) {
continue;
}
NSString* serviceName = service[@"name"];
FlutterServiceDefinition* definition =
[[FlutterServiceDefinition alloc] initWithName:serviceName
framework:service[@"framework"]];
if (definition != nil) {
_services[serviceName] = definition;
}
[definition release];
}
}
- (void)dealloc {
[_services release];
[super dealloc];
}
@end

View File

@@ -0,0 +1,14 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_VIEW_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_VIEW_H_
#include <UIKit/UIKit.h>
@interface FlutterView : UIView
@end
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_VIEW_H_

View File

@@ -0,0 +1,33 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
@interface FlutterView ()<UIInputViewAudioFeedback>
@end
@implementation FlutterView
- (void)layoutSubviews {
CGFloat screenScale = [UIScreen mainScreen].scale;
CAEAGLLayer* layer = reinterpret_cast<CAEAGLLayer*>(self.layer);
layer.allowsGroupOpacity = YES;
layer.opaque = YES;
layer.contentsScale = screenScale;
layer.rasterizationScale = screenScale;
[super layoutSubviews];
}
+ (Class)layerClass {
return [CAEAGLLayer class];
}
- (BOOL)enableInputClicksWhenVisible {
return YES;
}
@end

View File

@@ -0,0 +1,501 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
#include "base/mac/scoped_block.h"
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
#include "flutter/services/platform/ios/system_chrome_impl.h"
#include "flutter/sky/engine/wtf/MakeUnique.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
@interface FlutterViewController ()<UIAlertViewDelegate>
@end
void FlutterInit(int argc, const char* argv[]) {
NSBundle* bundle = [NSBundle bundleForClass:[FlutterViewController class]];
NSString* icuDataPath = [bundle pathForResource:@"icudtl" ofType:@"dat"];
shell::PlatformMacMain(argc, argv, icuDataPath.UTF8String);
}
@implementation FlutterViewController {
base::scoped_nsprotocol<FlutterDartProject*> _dartProject;
UIInterfaceOrientationMask _orientationPreferences;
UIStatusBarStyle _statusBarStyle;
sky::ViewportMetricsPtr _viewportMetrics;
shell::TouchMapper _touchMapper;
std::unique_ptr<shell::PlatformViewIOS> _platformView;
BOOL _initialized;
}
#pragma mark - Manage and override all designated initializers
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibNameOrNil
bundle:(NSBundle*)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
if (project == nil)
_dartProject.reset(
[[FlutterDartProject alloc] initFromDefaultSourceForConfiguration]);
else
_dartProject.reset([project retain]);
[self performCommonViewControllerInitialization];
}
return self;
}
- (instancetype)initWithNibName:(NSString*)nibNameOrNil
bundle:(NSBundle*)nibBundleOrNil {
return [self initWithProject:nil nibName:nil bundle:nil];
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
return [self initWithProject:nil nibName:nil bundle:nil];
}
#pragma mark - Common view controller initialization tasks
- (void)performCommonViewControllerInitialization {
if (_initialized)
return;
_initialized = YES;
_orientationPreferences = UIInterfaceOrientationMaskAll;
_statusBarStyle = UIStatusBarStyleDefault;
_viewportMetrics = sky::ViewportMetrics::New();
_platformView = WTF::MakeUnique<shell::PlatformViewIOS>(
reinterpret_cast<CAEAGLLayer*>(self.view.layer));
_platformView->SetupResourceContextOnIOThread();
[self setupNotificationCenterObservers];
[self connectToEngineAndLoad];
}
- (void)setupNotificationCenterObservers {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(onOrientationPreferencesUpdated:)
name:@(flutter::platform::kOrientationUpdateNotificationName)
object:nil];
[center addObserver:self
selector:@selector(onPreferredStatusBarStyleUpdated:)
name:@(flutter::platform::kOverlayStyleUpdateNotificationName)
object:nil];
[center addObserver:self
selector:@selector(applicationBecameActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification
object:nil];
[center addObserver:self
selector:@selector(onLocaleUpdated:)
name:NSCurrentLocaleDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onVoiceOverChanged:)
name:UIAccessibilityVoiceOverStatusChanged
object:nil];
}
#pragma mark - Initializing the engine
- (void)alertView:(UIAlertView*)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
exit(0);
}
- (void)connectToEngineAndLoad {
TRACE_EVENT0("flutter", "connectToEngineAndLoad");
_platformView->ConnectToEngineAndSetupServices();
// We ask the VM to check what it supports.
const enum VMType type =
Dart_IsPrecompiledRuntime() ? VMTypePrecompilation : VMTypeInterpreter;
[_dartProject launchInEngine:_platformView->engineProxy()
embedderVMType:type
result:^(BOOL success, NSString* message) {
if (!success) {
UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:@"Launch Error"
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}];
}
#pragma mark - Loading the view
- (void)loadView {
FlutterView* surface = [[FlutterView alloc] init];
self.view = surface;
self.view.multipleTouchEnabled = YES;
self.view.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[surface release];
}
#pragma mark - Application lifecycle notifications
- (void)applicationBecameActive:(NSNotification*)notification {
auto& engine = _platformView->engineProxy();
if (engine) {
engine->OnAppLifecycleStateChanged(sky::AppLifecycleState::RESUMED);
}
}
- (void)applicationWillResignActive:(NSNotification*)notification {
auto& engine = _platformView->engineProxy();
if (engine) {
engine->OnAppLifecycleStateChanged(sky::AppLifecycleState::PAUSED);
}
}
#pragma mark - Touch event handling
enum MapperPhase {
Accessed,
Added,
Removed,
};
using PointerTypeMapperPhase = std::pair<pointer::PointerType, MapperPhase>;
static inline PointerTypeMapperPhase PointerTypePhaseFromUITouchPhase(
UITouchPhase phase) {
switch (phase) {
case UITouchPhaseBegan:
return PointerTypeMapperPhase(pointer::PointerType::DOWN,
MapperPhase::Added);
case UITouchPhaseMoved:
case UITouchPhaseStationary:
// There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
// with the same coordinates
return PointerTypeMapperPhase(pointer::PointerType::MOVE,
MapperPhase::Accessed);
case UITouchPhaseEnded:
return PointerTypeMapperPhase(pointer::PointerType::UP,
MapperPhase::Removed);
case UITouchPhaseCancelled:
return PointerTypeMapperPhase(pointer::PointerType::CANCEL,
MapperPhase::Removed);
}
return PointerTypeMapperPhase(pointer::PointerType::CANCEL,
MapperPhase::Accessed);
}
- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
auto eventTypePhase = PointerTypePhaseFromUITouchPhase(phase);
const CGFloat scale = [UIScreen mainScreen].scale;
auto pointer_packet = pointer::PointerPacket::New();
for (UITouch* touch in touches) {
int touch_identifier = 0;
switch (eventTypePhase.second) {
case Accessed:
touch_identifier = _touchMapper.identifierOf(touch);
break;
case Added:
touch_identifier = _touchMapper.registerTouch(touch);
break;
case Removed:
touch_identifier = _touchMapper.unregisterTouch(touch);
break;
}
DCHECK(touch_identifier != 0);
CGPoint windowCoordinates = [touch locationInView:nil];
auto pointer_time =
base::TimeDelta::FromSecondsD(touch.timestamp).InMicroseconds();
auto pointer_data = pointer::Pointer::New();
pointer_data->time_stamp = pointer_time;
pointer_data->type = eventTypePhase.first;
pointer_data->kind = pointer::PointerKind::TOUCH;
pointer_data->pointer = touch_identifier;
pointer_data->x = windowCoordinates.x * scale;
pointer_data->y = windowCoordinates.y * scale;
pointer_data->buttons = 0;
pointer_data->down = false;
pointer_data->primary = false;
pointer_data->obscured = false;
pointer_data->pressure = 1.0;
pointer_data->pressure_min = 0.0;
pointer_data->pressure_max = 1.0;
pointer_data->distance = 0.0;
pointer_data->distance_min = 0.0;
pointer_data->distance_max = 0.0;
pointer_data->radius_major = 0.0;
pointer_data->radius_minor = 0.0;
pointer_data->radius_min = 0.0;
pointer_data->radius_max = 0.0;
pointer_data->orientation = 0.0;
pointer_data->tilt = 0.0;
pointer_packet->pointers.push_back(pointer_data.Pass());
}
_platformView->engineProxy()->OnPointerPacket(pointer_packet.Pass());
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches phase:UITouchPhaseBegan];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches phase:UITouchPhaseMoved];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches phase:UITouchPhaseEnded];
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches phase:UITouchPhaseCancelled];
}
#pragma mark - Handle view resizing
- (void)viewDidLayoutSubviews {
CGSize size = self.view.bounds.size;
CGFloat scale = [UIScreen mainScreen].scale;
_viewportMetrics->device_pixel_ratio = scale;
_viewportMetrics->physical_width = size.width * scale;
_viewportMetrics->physical_height = size.height * scale;
_viewportMetrics->physical_padding_top =
[UIApplication sharedApplication].statusBarFrame.size.height * scale;
_platformView->engineProxy()->OnViewportMetricsChanged(
_viewportMetrics.Clone());
}
#pragma mark - Keyboard events
- (void)keyboardWasShown:(NSNotification*)notification {
NSDictionary* info = [notification userInfo];
CGFloat bottom = CGRectGetHeight(
[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]);
CGFloat scale = [UIScreen mainScreen].scale;
_viewportMetrics->physical_padding_bottom = bottom * scale;
_platformView->engineProxy()->OnViewportMetricsChanged(
_viewportMetrics.Clone());
}
- (void)keyboardWillBeHidden:(NSNotification*)notification {
_viewportMetrics->physical_padding_bottom = 0.0;
_platformView->engineProxy()->OnViewportMetricsChanged(
_viewportMetrics.Clone());
}
#pragma mark - Orientation updates
- (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
// Notifications may not be on the iOS UI thread
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary* info = notification.userInfo;
NSNumber* update =
info[@(flutter::platform::kOrientationUpdateNotificationKey)];
if (update == nil) {
return;
}
NSUInteger new_preferences = update.unsignedIntegerValue;
if (new_preferences != _orientationPreferences) {
_orientationPreferences = new_preferences;
[UIViewController attemptRotationToDeviceOrientation];
}
});
}
- (BOOL)shouldAutorotate {
return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
return _orientationPreferences;
}
#pragma mark - Accessibility
- (void)onVoiceOverChanged:(NSNotification*)notification {
#if TARGET_OS_SIMULATOR
// There doesn't appear to be any way to determine whether the accessibility
// inspector is enabled on the simulator. We conservatively always turn on the
// accessibility bridge in the simulator.
bool enable = true;
#else
bool enable = UIAccessibilityIsVoiceOverRunning();
#endif
_platformView->ToggleAccessibility(self.view, enable);
}
#pragma mark - Locale updates
- (void)onLocaleUpdated:(NSNotification*)notification {
NSLocale* currentLocale = [NSLocale currentLocale];
NSString* languageCode = [currentLocale objectForKey:NSLocaleLanguageCode];
NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
_platformView->engineProxy()->OnLocaleChanged(languageCode.UTF8String,
countryCode.UTF8String);
}
#pragma mark - Surface creation and teardown updates
- (void)surfaceUpdated:(BOOL)appeared {
CHECK(_platformView != nullptr);
if (appeared) {
_platformView->NotifyCreated();
} else {
_platformView->NotifyDestroyed();
}
}
- (void)viewDidAppear:(BOOL)animated {
[self surfaceUpdated:YES];
[self onLocaleUpdated:nil];
[self onVoiceOverChanged:nil];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[self surfaceUpdated:NO];
[super viewWillDisappear:animated];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark - Status bar style
- (UIStatusBarStyle)preferredStatusBarStyle {
return _statusBarStyle;
}
- (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
// Notifications may not be on the iOS UI thread
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary* info = notification.userInfo;
NSNumber* update =
info[@(flutter::platform::kOverlayStyleUpdateNotificationKey)];
if (update == nil) {
return;
}
NSInteger style = update.integerValue;
if (style != _statusBarStyle) {
_statusBarStyle = static_cast<UIStatusBarStyle>(style);
[self setNeedsStatusBarAppearanceUpdate];
}
});
}
#pragma mark - Application Messages
- (void)sendString:(NSString*)message withMessageName:(NSString*)messageName {
NSAssert(message, @"The message must not be null");
NSAssert(messageName, @"The messageName must not be null");
_platformView->AppMessageSender()->SendString(
messageName.UTF8String, message.UTF8String,
[](const mojo::String& response) {});
}
- (void)sendString:(NSString*)message
withMessageName:(NSString*)messageName
callback:(void (^)(NSString*))callback {
NSAssert(message, @"The message must not be null");
NSAssert(messageName, @"The messageName must not be null");
NSAssert(callback, @"The callback must not be null");
base::mac::ScopedBlock<void (^)(NSString*)> callback_ptr(
callback, base::scoped_policy::RETAIN);
_platformView->AppMessageSender()->SendString(
messageName.UTF8String, message.UTF8String,
[callback_ptr](const mojo::String& response) {
callback_ptr.get()(base::SysUTF8ToNSString(response));
});
}
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->AppMessageReceiver().SetMessageListener(messageName.UTF8String,
listener);
}
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->AppMessageReceiver().SetMessageListener(messageName.UTF8String,
nil);
}
- (void)addAsyncMessageListener:
(NSObject<FlutterAsyncMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->AppMessageReceiver().SetAsyncMessageListener(
messageName.UTF8String, listener);
}
- (void)removeAsyncMessageListener:
(NSObject<FlutterAsyncMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->AppMessageReceiver().SetAsyncMessageListener(
messageName.UTF8String, nil);
}
@end

View File

@@ -0,0 +1,76 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
#include <memory>
#include <set>
#include <unordered_map>
#include "flutter/services/semantics/semantics.mojom.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#include "flutter/sky/engine/platform/geometry/FloatRect.h"
#include "lib/ftl/macros.h"
#include "mojo/public/cpp/bindings/array.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"
#include "third_party/skia/include/core/SkMatrix44.h"
#include "third_party/skia/include/core/SkRect.h"
namespace shell {
class AccessibilityBridge;
} // namespace shell
@interface SemanticObject : NSObject
/**
* The globally unique identifier for this node.
*/
@property(nonatomic, readonly) uint32_t uid;
/**
* The parent of this node in the node tree. Will be nil for the root node and
* during transient state changes.
*/
@property(nonatomic, assign) SemanticObject* parent;
- (instancetype)init __attribute__((unavailable("Use initWithBridge instead")));
- (instancetype)initWithBridge:(shell::AccessibilityBridge*)bridge
uid:(uint32_t)uid NS_DESIGNATED_INITIALIZER;
@end
namespace shell {
class AccessibilityBridge final : public semantics::SemanticsListener {
public:
AccessibilityBridge(UIView*, mojo::ServiceProvider*);
~AccessibilityBridge() override;
void UpdateSemanticsTree(mojo::Array<semantics::SemanticsNodePtr>) override;
UIView* view() { return view_; }
semantics::SemanticsServer* server() { return semantics_server_.get(); }
private:
SemanticObject* UpdateSemanticObject(
const semantics::SemanticsNodePtr& node,
std::set<SemanticObject*>* updated_objects,
std::set<SemanticObject*>* removed_objects);
void RemoveSemanticObject(SemanticObject* node,
std::set<SemanticObject*>* updated_objects);
UIView* view_;
semantics::SemanticsServerPtr semantics_server_;
std::unordered_map<int, SemanticObject*> objects_;
mojo::Binding<semantics::SemanticsListener> binding_;
FTL_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge);
};
} // namespace shell
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_

View File

@@ -0,0 +1,375 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h"
#import <UIKit/UIKit.h>
#include <vector>
#include "base/logging.h"
#include "mojo/public/cpp/application/connect.h"
namespace {
constexpr uint32_t kRootNodeId = 0;
// Contains better abstractions than the raw Mojo data structure
struct Geometry {
Geometry& operator=(const semantics::SemanticGeometryPtr& other) {
if (!other->transform.is_null()) {
transform.setColMajorf(other->transform.data());
}
rect.setXYWH(other->left, other->top, other->width, other->height);
return *this;
}
SkMatrix44 transform = SkMatrix44(SkMatrix44::kIdentity_Constructor);
SkRect rect;
};
} // namespace
@implementation SemanticObject {
shell::AccessibilityBridge* _bridge;
semantics::SemanticFlagsPtr _flags;
semantics::SemanticStringsPtr _strings;
Geometry _geometry;
bool _canBeTapped;
bool _canBeLongPressed;
bool _canBeScrolledHorizontally;
bool _canBeScrolledVertically;
bool _canBeAdjusted;
std::vector<SemanticObject*> _children;
}
#pragma mark - Override base class designated initializers
// Method declared as unavailable in the interface
- (instancetype)init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
#pragma mark - Designated initializers
- (instancetype)initWithBridge:(shell::AccessibilityBridge*)bridge
uid:(uint32_t)uid {
DCHECK(bridge != nil) << "bridge must be set";
DCHECK(uid >= kRootNodeId);
self = [super init];
if (self) {
_bridge = bridge;
_uid = uid;
}
return self;
}
#pragma mark - Semantic object methods
- (void)updateWith:(const semantics::SemanticsNodePtr&)node {
DCHECK(_uid == node->id);
if (!node->flags.is_null()) {
_flags = node->flags.Pass();
}
if (!node->strings.is_null()) {
_strings = node->strings.Pass();
}
if (!node->geometry.is_null()) {
_geometry = node->geometry;
}
if (!node->actions.is_null()) {
_canBeTapped = false;
_canBeLongPressed = false;
_canBeScrolledHorizontally = false;
_canBeScrolledVertically = false;
for (int action : node->actions) {
switch (static_cast<semantics::SemanticAction>(action)) {
case semantics::SemanticAction::TAP:
_canBeTapped = true;
break;
case semantics::SemanticAction::LONG_PRESS:
_canBeLongPressed = true;
break;
case semantics::SemanticAction::SCROLL_LEFT:
case semantics::SemanticAction::SCROLL_RIGHT:
_canBeScrolledHorizontally = true;
break;
case semantics::SemanticAction::SCROLL_UP:
case semantics::SemanticAction::SCROLL_DOWN:
_canBeScrolledVertically = true;
break;
case semantics::SemanticAction::INCREASE:
case semantics::SemanticAction::DECREASE:
_canBeAdjusted = true;
break;
}
}
}
}
- (std::vector<SemanticObject*>*)children {
return &_children;
}
- (void)neuter {
_bridge = nullptr;
_children.clear();
self.parent = nil;
}
#pragma mark - UIAccessibility overrides
- (BOOL)isAccessibilityElement {
// Note: hit detection will only apply to elements that report
// -isAccessibilityElement of YES. The framework will continue scanning the
// entire element tree looking for such a hit.
return _canBeTapped || _children.empty();
}
- (NSString*)accessibilityLabel {
if (_strings.is_null() || _strings->label.get().empty()) {
return nil;
}
return @(_strings->label.data());
}
- (UIAccessibilityTraits)accessibilityTraits {
UIAccessibilityTraits traits = UIAccessibilityTraitNone;
if (_canBeTapped) {
traits |= UIAccessibilityTraitButton;
}
if (_canBeAdjusted) {
traits |= UIAccessibilityTraitAdjustable;
}
return traits;
}
- (CGRect)accessibilityFrame {
SkMatrix44 globalTransform = _geometry.transform;
for (SemanticObject* parent = _parent; parent; parent = parent.parent) {
globalTransform = globalTransform * parent->_geometry.transform;
}
SkPoint quad[4];
_geometry.rect.toQuad(quad);
for (auto& point : quad) {
SkScalar vector[4] = {point.x(), point.y(), 0, 1};
globalTransform.mapScalars(vector);
point.set(vector[0], vector[1]);
}
SkRect rect;
rect.set(quad, 4);
auto result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
return UIAccessibilityConvertFrameToScreenCoordinates(result,
_bridge->view());
}
#pragma mark - UIAccessibilityElement protocol
- (id)accessibilityContainer {
return (_uid == kRootNodeId) ? _bridge->view() : _parent;
}
#pragma mark - UIAccessibilityContainer overrides
- (NSInteger)accessibilityElementCount {
return (NSInteger)_children.size();
}
- (nullable id)accessibilityElementAtIndex:(NSInteger)index {
if (index < 0 || index >= (NSInteger)_children.size()) {
return nil;
}
return _children[index];
}
- (NSInteger)indexOfAccessibilityElement:(id)element {
auto it = std::find(_children.begin(), _children.end(), element);
if (it == _children.end()) {
return NSNotFound;
}
return it - _children.begin();
}
#pragma mark - UIAccessibilityAction overrides
- (BOOL)accessibilityActivate {
// TODO(tvolkert): Implement
return NO;
}
- (void)accessibilityIncrement {
if (_canBeAdjusted) {
_bridge->server()->PerformAction(_uid, semantics::SemanticAction::INCREASE);
}
}
- (void)accessibilityDecrement {
if (_canBeAdjusted) {
_bridge->server()->PerformAction(_uid, semantics::SemanticAction::DECREASE);
}
}
- (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction {
BOOL canBeScrolled = NO;
switch (direction) {
case UIAccessibilityScrollDirectionRight:
case UIAccessibilityScrollDirectionLeft:
canBeScrolled = _canBeScrolledHorizontally;
break;
case UIAccessibilityScrollDirectionUp:
case UIAccessibilityScrollDirectionDown:
canBeScrolled = _canBeScrolledVertically;
break;
default:
// Note: page turning of reading content is not currently supported
// (UIAccessibilityScrollDirectionNext,
// UIAccessibilityScrollDirectionPrevious)
canBeScrolled = NO;
break;
}
if (!canBeScrolled) {
return NO;
}
switch (direction) {
case UIAccessibilityScrollDirectionRight:
_bridge->server()->PerformAction(_uid,
semantics::SemanticAction::SCROLL_RIGHT);
break;
case UIAccessibilityScrollDirectionLeft:
_bridge->server()->PerformAction(_uid,
semantics::SemanticAction::SCROLL_LEFT);
break;
case UIAccessibilityScrollDirectionUp:
_bridge->server()->PerformAction(_uid,
semantics::SemanticAction::SCROLL_UP);
break;
case UIAccessibilityScrollDirectionDown:
_bridge->server()->PerformAction(_uid,
semantics::SemanticAction::SCROLL_DOWN);
break;
default:
DCHECK(false) << "Unsupported scroll direction: " << direction;
}
// TODO(tvolkert): provide meaningful string (e.g. "page 2 of 5")
UIAccessibilityPostNotification(UIAccessibilityPageScrolledNotification, nil);
return YES;
}
- (BOOL)accessibilityPerformEscape {
// TODO(tvolkert): Implement
return NO;
}
- (BOOL)accessibilityPerformMagicTap {
// TODO(tvolkert): Implement
return NO;
}
@end
#pragma mark - AccessibilityBridge impl
namespace shell {
AccessibilityBridge::AccessibilityBridge(UIView* view,
mojo::ServiceProvider* serviceProvider)
: view_(view), binding_(this) {
mojo::ConnectToService(serviceProvider, mojo::GetProxy(&semantics_server_));
mojo::InterfaceHandle<semantics::SemanticsListener> listener;
binding_.Bind(&listener);
semantics_server_->AddSemanticsListener(listener.Pass());
}
AccessibilityBridge::~AccessibilityBridge() {
for (const auto& entry : objects_) {
SemanticObject* object = entry.second;
[object neuter];
[object release];
}
}
void AccessibilityBridge::UpdateSemanticsTree(
mojo::Array<semantics::SemanticsNodePtr> nodes) {
std::set<SemanticObject*> updated_objects;
std::set<SemanticObject*> removed_objects;
for (const semantics::SemanticsNodePtr& node : nodes) {
UpdateSemanticObject(node, &updated_objects, &removed_objects);
}
for (SemanticObject* object : removed_objects) {
if (!updated_objects.count(object)) {
RemoveSemanticObject(object, &updated_objects);
}
}
SemanticObject* root = objects_[kRootNodeId];
if (root) {
if (!view_.accessibilityElements) {
view_.accessibilityElements = @[ root ];
}
} else {
view_.accessibilityElements = nil;
}
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,
nil);
}
SemanticObject* AccessibilityBridge::UpdateSemanticObject(
const semantics::SemanticsNodePtr& node,
std::set<SemanticObject*>* updated_objects,
std::set<SemanticObject*>* removed_objects) {
SemanticObject* object = objects_[node->id];
if (!object) {
object = [[SemanticObject alloc] initWithBridge:this uid:node->id];
objects_[node->id] = object;
}
[object updateWith:node];
updated_objects->insert(object);
if (!node->children.is_null()) {
std::vector<SemanticObject*>* children = [object children];
removed_objects->insert(children->begin(), children->end());
children->clear();
children->reserve(node->children.size());
for (const auto& child_node : node->children) {
SemanticObject* child_object =
UpdateSemanticObject(child_node, updated_objects, removed_objects);
child_object.parent = object;
children->push_back(child_object);
}
}
return object;
}
void AccessibilityBridge::RemoveSemanticObject(
SemanticObject* object,
std::set<SemanticObject*>* updated_objects) {
DCHECK(objects_[object.uid] == object);
objects_.erase(object.uid);
for (SemanticObject* child : *[object children]) {
if (!updated_objects->count(child)) {
DCHECK(child.parent == object);
child.parent = nil;
RemoveSemanticObject(child, updated_objects);
}
}
[object neuter];
[object release];
}
} // namespace shell

View File

@@ -0,0 +1,48 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_APPLICATION_MESSAGES_IMPL_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_APPLICATION_MESSAGES_IMPL_H_
#include <unordered_map>
#include "lib/ftl/memory/weak_ptr.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "flutter/services/platform/app_messages.mojom.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h"
namespace shell {
class ApplicationMessagesImpl : public flutter::platform::ApplicationMessages {
public:
ApplicationMessagesImpl();
~ApplicationMessagesImpl() override;
ftl::WeakPtr<ApplicationMessagesImpl> GetWeakPtr();
void AddBinding(
mojo::InterfaceRequest<flutter::platform::ApplicationMessages> request);
void SetMessageListener(const std::string& message_name,
NSObject<FlutterMessageListener>* listener);
void SetAsyncMessageListener(const std::string& message_name,
NSObject<FlutterAsyncMessageListener>* listener);
private:
void SendString(const mojo::String& message_name,
const mojo::String& message,
const SendStringCallback& callback) override;
mojo::BindingSet<flutter::platform::ApplicationMessages> binding_;
std::unordered_map<std::string, NSObject<FlutterMessageListener>*> listeners_;
std::unordered_map<std::string, NSObject<FlutterAsyncMessageListener>*>
async_listeners_;
ftl::WeakPtrFactory<ApplicationMessagesImpl> weak_factory_;
};
} // namespace shell
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_

Some files were not shown because too many files have changed in this diff Show More