From b2e97acdb85a030739b61eacce5075e3b45d649d Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Fri, 23 Sep 2016 15:33:25 -0700 Subject: [PATCH] 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. --- DEPS | 2 +- engine/src/flutter/BUILD.gn | 1 - engine/src/flutter/shell/BUILD.gn | 7 + engine/src/flutter/shell/common/BUILD.gn | 70 ++ engine/src/flutter/shell/common/animator.cc | 145 ++++ engine/src/flutter/shell/common/animator.h | 60 ++ .../common/diagnostic/diagnostic_server.cc | 150 ++++ .../common/diagnostic/diagnostic_server.dart | 59 ++ .../common/diagnostic/diagnostic_server.h | 23 + engine/src/flutter/shell/common/engine.cc | 336 ++++++++ engine/src/flutter/shell/common/engine.h | 125 +++ .../shell/common/picture_serializer.cc | 36 + .../flutter/shell/common/picture_serializer.h | 25 + .../src/flutter/shell/common/platform_view.cc | 140 ++++ .../src/flutter/shell/common/platform_view.h | 95 +++ .../common/platform_view_service_protocol.cc | 216 +++++ .../common/platform_view_service_protocol.h | 39 + engine/src/flutter/shell/common/rasterizer.cc | 11 + engine/src/flutter/shell/common/rasterizer.h | 47 ++ engine/src/flutter/shell/common/shell.cc | 327 ++++++++ engine/src/flutter/shell/common/shell.h | 105 +++ engine/src/flutter/shell/common/switches.cc | 45 ++ engine/src/flutter/shell/common/switches.h | 37 + .../flutter/shell/common/systrace_logger.cc | 55 ++ .../flutter/shell/common/systrace_logger.h | 35 + .../shell/common/tracing_controller.cc | 212 +++++ .../flutter/shell/common/tracing_controller.h | 60 ++ .../src/flutter/shell/common/ui_delegate.cc | 11 + engine/src/flutter/shell/common/ui_delegate.h | 30 + engine/src/flutter/shell/gpu/BUILD.gn | 28 + engine/src/flutter/shell/gpu/ganesh_canvas.cc | 89 +++ engine/src/flutter/shell/gpu/ganesh_canvas.h | 41 + engine/src/flutter/shell/gpu/gpu_canvas.cc | 11 + engine/src/flutter/shell/gpu/gpu_canvas.h | 16 + engine/src/flutter/shell/gpu/gpu_canvas_gl.cc | 11 + engine/src/flutter/shell/gpu/gpu_canvas_gl.h | 16 + .../flutter/shell/gpu/gpu_canvas_vulkan.cc | 11 + .../src/flutter/shell/gpu/gpu_canvas_vulkan.h | 16 + .../src/flutter/shell/gpu/gpu_rasterizer.cc | 184 +++++ engine/src/flutter/shell/gpu/gpu_rasterizer.h | 51 ++ engine/src/flutter/shell/platform/BUILD.gn | 15 + .../platform/android/AndroidManifest.xml | 26 + .../flutter/shell/platform/android/BUILD.gn | 127 +++ .../shell/platform/android/flutter_main.cc | 99 +++ .../shell/platform/android/flutter_main.h | 16 + .../io/flutter/view/AccessibilityBridge.java | 502 ++++++++++++ .../android/io/flutter/view/FlutterMain.java | 412 ++++++++++ .../android/io/flutter/view/FlutterView.java | 747 ++++++++++++++++++ .../io/flutter/view/ResourceCleaner.java | 88 +++ .../io/flutter/view/ResourceExtractor.java | 192 +++++ .../io/flutter/view/ServiceFactory.java | 20 + .../io/flutter/view/ServiceProviderImpl.java | 68 ++ .../io/flutter/view/ServiceRegistry.java | 39 + .../shell/platform/android/library_loader.cc | 55 ++ .../org/domokit/sky/shell/SkyActivity.java | 146 ++++ .../org/domokit/sky/shell/SkyApplication.java | 21 + .../platform/android/platform_view_android.cc | 610 ++++++++++++++ .../platform/android/platform_view_android.h | 79 ++ .../flutter/shell/platform/darwin/BUILD.gn | 20 + .../shell/platform/darwin/common/BUILD.gn | 43 + .../platform/darwin/common/platform_mac.h | 18 + .../platform/darwin/common/platform_mac.mm | 210 +++++ .../common/platform_service_provider.cc | 101 +++ .../darwin/common/platform_service_provider.h | 38 + .../darwin/common/view_service_provider.cc | 37 + .../darwin/common/view_service_provider.h | 44 ++ .../shell/platform/darwin/desktop/BUILD.gn | 60 ++ .../shell/platform/darwin/desktop/Info.plist | 34 + .../shell/platform/darwin/desktop/main_mac.mm | 52 ++ .../darwin/desktop/platform_view_mac.h | 60 ++ .../darwin/desktop/platform_view_mac.mm | 168 ++++ .../darwin/desktop/sky_app_delegate.h | 9 + .../darwin/desktop/sky_app_delegate.m | 15 + .../platform/darwin/desktop/sky_application.h | 18 + .../darwin/desktop/sky_application.mm | 39 + .../shell/platform/darwin/desktop/sky_mac.xib | 695 ++++++++++++++++ .../platform/darwin/desktop/sky_window.h | 9 + .../platform/darwin/desktop/sky_window.mm | 155 ++++ .../shell/platform/darwin/ios/BUILD.gn | 161 ++++ .../darwin/ios/framework/Headers/Flutter.h | 15 + .../framework/Headers/FlutterAppDelegate.h | 21 + .../Headers/FlutterAsyncMessageListener.h | 22 + .../framework/Headers/FlutterDartProject.h | 30 + .../ios/framework/Headers/FlutterMacros.h | 18 + .../Headers/FlutterMessageListener.h | 21 + .../framework/Headers/FlutterViewController.h | 47 ++ .../platform/darwin/ios/framework/Info.plist | 24 + .../framework/Source/FlutterAppDelegate.mm | 9 + .../framework/Source/FlutterDartProject.mm | 251 ++++++ .../Source/FlutterDartProject_Internal.h | 31 + .../ios/framework/Source/FlutterDartSource.h | 30 + .../ios/framework/Source/FlutterDartSource.mm | 105 +++ .../Source/FlutterDynamicServiceLoader.h | 18 + .../Source/FlutterDynamicServiceLoader.mm | 178 +++++ .../darwin/ios/framework/Source/FlutterView.h | 14 + .../ios/framework/Source/FlutterView.mm | 33 + .../framework/Source/FlutterViewController.mm | 501 ++++++++++++ .../framework/Source/accessibility_bridge.h | 76 ++ .../framework/Source/accessibility_bridge.mm | 375 +++++++++ .../Source/application_messages_impl.h | 48 ++ .../Source/application_messages_impl.mm | 70 ++ .../framework/Source/flutter_touch_mapper.h | 40 + .../framework/Source/flutter_touch_mapper.mm | 31 + .../darwin/ios/framework/module.modulemap | 6 + .../platform/darwin/ios/platform_view_ios.h | 75 ++ .../platform/darwin/ios/platform_view_ios.mm | 398 ++++++++++ .../src/flutter/shell/platform/linux/BUILD.gn | 38 + .../platform/linux/glfw_service_provider.cc | 19 + .../platform/linux/glfw_service_provider.h | 31 + .../shell/platform/linux/main_linux.cc | 108 +++ .../shell/platform/linux/message_pump_glfw.cc | 82 ++ .../shell/platform/linux/message_pump_glfw.h | 41 + .../platform/linux/platform_view_glfw.cc | 182 +++++ .../shell/platform/linux/platform_view_glfw.h | 63 ++ engine/src/flutter/shell/testing/BUILD.gn | 23 + .../shell/testing/observatory/empty_main.dart | 6 + .../shell/testing/observatory/launcher.dart | 74 ++ .../testing/observatory/service_client.dart | 63 ++ .../shell/testing/observatory/test.dart | 192 +++++ .../shell/testing/platform_view_test.cc | 39 + .../shell/testing/platform_view_test.h | 44 ++ .../src/flutter/shell/testing/test_runner.cc | 42 + .../src/flutter/shell/testing/test_runner.h | 44 ++ engine/src/flutter/shell/testing/testing.cc | 27 + engine/src/flutter/shell/testing/testing.h | 14 + engine/src/flutter/sky/BUILD.gn | 2 +- 126 files changed, 11844 insertions(+), 3 deletions(-) create mode 100644 engine/src/flutter/shell/BUILD.gn create mode 100644 engine/src/flutter/shell/common/BUILD.gn create mode 100644 engine/src/flutter/shell/common/animator.cc create mode 100644 engine/src/flutter/shell/common/animator.h create mode 100644 engine/src/flutter/shell/common/diagnostic/diagnostic_server.cc create mode 100644 engine/src/flutter/shell/common/diagnostic/diagnostic_server.dart create mode 100644 engine/src/flutter/shell/common/diagnostic/diagnostic_server.h create mode 100644 engine/src/flutter/shell/common/engine.cc create mode 100644 engine/src/flutter/shell/common/engine.h create mode 100644 engine/src/flutter/shell/common/picture_serializer.cc create mode 100644 engine/src/flutter/shell/common/picture_serializer.h create mode 100644 engine/src/flutter/shell/common/platform_view.cc create mode 100644 engine/src/flutter/shell/common/platform_view.h create mode 100644 engine/src/flutter/shell/common/platform_view_service_protocol.cc create mode 100644 engine/src/flutter/shell/common/platform_view_service_protocol.h create mode 100644 engine/src/flutter/shell/common/rasterizer.cc create mode 100644 engine/src/flutter/shell/common/rasterizer.h create mode 100644 engine/src/flutter/shell/common/shell.cc create mode 100644 engine/src/flutter/shell/common/shell.h create mode 100644 engine/src/flutter/shell/common/switches.cc create mode 100644 engine/src/flutter/shell/common/switches.h create mode 100644 engine/src/flutter/shell/common/systrace_logger.cc create mode 100644 engine/src/flutter/shell/common/systrace_logger.h create mode 100644 engine/src/flutter/shell/common/tracing_controller.cc create mode 100644 engine/src/flutter/shell/common/tracing_controller.h create mode 100644 engine/src/flutter/shell/common/ui_delegate.cc create mode 100644 engine/src/flutter/shell/common/ui_delegate.h create mode 100644 engine/src/flutter/shell/gpu/BUILD.gn create mode 100644 engine/src/flutter/shell/gpu/ganesh_canvas.cc create mode 100644 engine/src/flutter/shell/gpu/ganesh_canvas.h create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas.cc create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas.h create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas_gl.cc create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas_gl.h create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas_vulkan.cc create mode 100644 engine/src/flutter/shell/gpu/gpu_canvas_vulkan.h create mode 100644 engine/src/flutter/shell/gpu/gpu_rasterizer.cc create mode 100644 engine/src/flutter/shell/gpu/gpu_rasterizer.h create mode 100644 engine/src/flutter/shell/platform/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/android/AndroidManifest.xml create mode 100644 engine/src/flutter/shell/platform/android/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/android/flutter_main.cc create mode 100644 engine/src/flutter/shell/platform/android/flutter_main.h create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/FlutterMain.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/ResourceCleaner.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/ResourceExtractor.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/ServiceFactory.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/ServiceProviderImpl.java create mode 100644 engine/src/flutter/shell/platform/android/io/flutter/view/ServiceRegistry.java create mode 100644 engine/src/flutter/shell/platform/android/library_loader.cc create mode 100644 engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyActivity.java create mode 100644 engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyApplication.java create mode 100644 engine/src/flutter/shell/platform/android/platform_view_android.cc create mode 100644 engine/src/flutter/shell/platform/android/platform_view_android.h create mode 100644 engine/src/flutter/shell/platform/darwin/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/darwin/common/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/darwin/common/platform_mac.h create mode 100644 engine/src/flutter/shell/platform/darwin/common/platform_mac.mm create mode 100644 engine/src/flutter/shell/platform/darwin/common/platform_service_provider.cc create mode 100644 engine/src/flutter/shell/platform/darwin/common/platform_service_provider.h create mode 100644 engine/src/flutter/shell/platform/darwin/common/view_service_provider.cc create mode 100644 engine/src/flutter/shell/platform/darwin/common/view_service_provider.h create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/Info.plist create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/main_mac.mm create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.h create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.mm create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.h create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.m create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_application.h create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_application.mm create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_mac.xib create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_window.h create mode 100644 engine/src/flutter/shell/platform/darwin/desktop/sky_window.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterDartProject.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMacros.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap create mode 100644 engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm create mode 100644 engine/src/flutter/shell/platform/linux/BUILD.gn create mode 100644 engine/src/flutter/shell/platform/linux/glfw_service_provider.cc create mode 100644 engine/src/flutter/shell/platform/linux/glfw_service_provider.h create mode 100644 engine/src/flutter/shell/platform/linux/main_linux.cc create mode 100644 engine/src/flutter/shell/platform/linux/message_pump_glfw.cc create mode 100644 engine/src/flutter/shell/platform/linux/message_pump_glfw.h create mode 100644 engine/src/flutter/shell/platform/linux/platform_view_glfw.cc create mode 100644 engine/src/flutter/shell/platform/linux/platform_view_glfw.h create mode 100644 engine/src/flutter/shell/testing/BUILD.gn create mode 100644 engine/src/flutter/shell/testing/observatory/empty_main.dart create mode 100644 engine/src/flutter/shell/testing/observatory/launcher.dart create mode 100644 engine/src/flutter/shell/testing/observatory/service_client.dart create mode 100644 engine/src/flutter/shell/testing/observatory/test.dart create mode 100644 engine/src/flutter/shell/testing/platform_view_test.cc create mode 100644 engine/src/flutter/shell/testing/platform_view_test.h create mode 100644 engine/src/flutter/shell/testing/test_runner.cc create mode 100644 engine/src/flutter/shell/testing/test_runner.h create mode 100644 engine/src/flutter/shell/testing/testing.cc create mode 100644 engine/src/flutter/shell/testing/testing.h diff --git a/DEPS b/DEPS index c40f9aeded..c1c02830c3 100644 --- a/DEPS +++ b/DEPS @@ -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 # diff --git a/engine/src/flutter/BUILD.gn b/engine/src/flutter/BUILD.gn index c478f43d46..fdf35daae9 100644 --- a/engine/src/flutter/BUILD.gn +++ b/engine/src/flutter/BUILD.gn @@ -24,7 +24,6 @@ group("flutter") { if (is_ios) { deps += [ "//flutter/services/dynamic:sdk_lib_archive", - "//flutter/sky/shell:flutter_framework", ] } } diff --git a/engine/src/flutter/shell/BUILD.gn b/engine/src/flutter/shell/BUILD.gn new file mode 100644 index 0000000000..dfaacd545f --- /dev/null +++ b/engine/src/flutter/shell/BUILD.gn @@ -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" ] +} diff --git a/engine/src/flutter/shell/common/BUILD.gn b/engine/src/flutter/shell/common/BUILD.gn new file mode 100644 index 0000000000..ad283f39af --- /dev/null +++ b/engine/src/flutter/shell/common/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/common/animator.cc b/engine/src/flutter/shell/common/animator.cc new file mode 100644 index 0000000000..d7f419ed18 --- /dev/null +++ b/engine/src/flutter/shell/common/animator.cc @@ -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(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 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 diff --git a/engine/src/flutter/shell/common/animator.h b/engine/src/flutter/shell/common/animator.h new file mode 100644 index 0000000000..2f95c5927d --- /dev/null +++ b/engine/src/flutter/shell/common/animator.h @@ -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 layer_tree); + + void Start(); + + void Stop(); + + void set_vsync_provider(vsync::VSyncProviderPtr vsync_provider); + + private: + using LayerTreePipeline = flutter::Pipeline; + + void BeginFrame(int64_t time_stamp); + + void AwaitVSync(const vsync::VSyncProvider::AwaitVSyncCallback& callback); + + ftl::WeakPtr rasterizer_; + Engine* engine_; + vsync::VSyncProviderPtr vsync_provider_; + vsync::VSyncProviderPtr fallback_vsync_provider_; + ftl::TimePoint last_begin_frame_time_; + ftl::RefPtr layer_tree_pipeline_; + flutter::Semaphore pending_frame_semaphore_; + LayerTreePipeline::ProducerContinuation producer_continuation_; + bool paused_; + + base::WeakPtrFactory weak_factory_; + + FTL_DISALLOW_COPY_AND_ASSIGN(Animator); +}; + +} // namespace shell + +#endif // SHELL_COMMON_ANIMATOR_H_ diff --git a/engine/src/flutter/shell/common/diagnostic/diagnostic_server.cc b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.cc new file mode 100644 index 0000000000..296a655691 --- /dev/null +++ b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.cc @@ -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(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> 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 picture = recorder.finishRecordingAsPicture(); + + SkDynamicMemoryWStream stream; + PngPixelSerializer serializer; + picture->serialize(&stream, &serializer); + SkAutoTUnref 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(picture_data->bytes()); + c_object.value.as_typed_data.length = picture_data->size(); + + Dart_PostCObject(port_id, &c_object); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/common/diagnostic/diagnostic_server.dart b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.dart new file mode 100644 index 0000000000..cc7aeaec72 --- /dev/null +++ b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.dart @@ -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(); +} diff --git a/engine/src/flutter/shell/common/diagnostic/diagnostic_server.h b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.h new file mode 100644 index 0000000000..00553ca2e3 --- /dev/null +++ b/engine/src/flutter/shell/common/diagnostic/diagnostic_server.h @@ -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_ diff --git a/engine/src/flutter/shell/common/engine.cc b/engine/src/flutter/shell/common/engine.cc new file mode 100644 index 0000000000..1e8dc278fc --- /dev/null +++ b/engine/src/flutter/shell/common/engine.cc @@ -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 +#include +#include + +#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::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 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 snapshot) { + FTL_DCHECK(runtime_); + FTL_DCHECK(runtime_->dart_controller()); + runtime_->dart_controller()->RunFromSnapshot( + reinterpret_cast(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::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 = 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 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 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 diff --git a/engine/src/flutter/shell/common/engine.h b/engine/src/flutter/shell/common/engine.h new file mode 100644 index 0000000000..f0601a04df --- /dev/null +++ b/engine/src/flutter/shell/common/engine.h @@ -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 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 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 layer_tree) override; + void DidCreateMainIsolate(Dart_Isolate isolate) override; + void DidCreateSecondaryIsolate(Dart_Isolate isolate) override; + + void BindToServiceProvider( + mojo::InterfaceRequest 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_; + + sky::ServicesDataPtr services_; + mojo::ServiceProviderImpl service_provider_impl_; + mojo::ServiceProviderPtr incoming_services_; + mojo::BindingSet service_provider_bindings_; + + mojo::asset_bundle::AssetBundlePtr root_bundle_; + std::unique_ptr runtime_; + + std::unique_ptr snapshot_drainer_; + + std::string initial_route_; + sky::ViewportMetricsPtr viewport_metrics_; + std::string language_code_; + std::string country_code_; + mojo::Binding binding_; + ftl::RefPtr asset_store_; + + // TODO(eseidel): This should move into an AnimatorStateMachine. + bool activity_running_; + bool have_surface_; + + ftl::WeakPtrFactory weak_factory_; + + FTL_DISALLOW_COPY_AND_ASSIGN(Engine); +}; + +} // namespace shell + +#endif // SHELL_COMMON_ENGINE_H_ diff --git a/engine/src/flutter/shell/common/picture_serializer.cc b/engine/src/flutter/shell/common/picture_serializer.cc new file mode 100644 index 0000000000..b925cf2948 --- /dev/null +++ b/engine/src/flutter/shell/common/picture_serializer.cc @@ -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 diff --git a/engine/src/flutter/shell/common/picture_serializer.h b/engine/src/flutter/shell/common/picture_serializer.h new file mode 100644 index 0000000000..9c7d5dd148 --- /dev/null +++ b/engine/src/flutter/shell/common/picture_serializer.h @@ -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 + +#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_ diff --git a/engine/src/flutter/shell/common/platform_view.cc b/engine/src/flutter/shell/common/platform_view.cc new file mode 100644 index 0000000000..7f16ad9924 --- /dev/null +++ b/engine/src/flutter/shell/common/platform_view.cc @@ -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 + +#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 request) { + ftl::WeakPtr 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 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(GrGLCreateNativeInterface()))); + + latch->Signal(); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/common/platform_view.h b/engine/src/flutter/shell/common/platform_view.h new file mode 100644 index 0000000000..543bcca927 --- /dev/null +++ b/engine/src/flutter/shell/common/platform_view.h @@ -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 + +#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 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 request); + + void NotifyCreated(); + + void NotifyCreated(ftl::Closure continuation); + + void NotifyDestroyed(); + + virtual ftl::WeakPtr 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_; + std::unique_ptr engine_; + + SkISize size_; + + explicit PlatformView(); + + void SetupResourceContextOnIOThreadPerform( + ftl::AutoResetWaitableEvent* event); + + private: + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformView); +}; + +} // namespace shell + +#endif // COMMON_PLATFORM_VIEW_H_ diff --git a/engine/src/flutter/shell/common/platform_view_service_protocol.cc b/engine/src/flutter/shell/common/platform_view_service_protocol.cc new file mode 100644 index 0000000000..3b0a53fe74 --- /dev/null +++ b/engine/src/flutter/shell/common/platform_view_service_protocol.cc @@ -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 + +#include + +#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 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 diff --git a/engine/src/flutter/shell/common/platform_view_service_protocol.h b/engine/src/flutter/shell/common/platform_view_service_protocol.h new file mode 100644 index 0000000000..599ea2aa28 --- /dev/null +++ b/engine/src/flutter/shell/common/platform_view_service_protocol.h @@ -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 + +#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_ diff --git a/engine/src/flutter/shell/common/rasterizer.cc b/engine/src/flutter/shell/common/rasterizer.cc new file mode 100644 index 0000000000..0c32386b10 --- /dev/null +++ b/engine/src/flutter/shell/common/rasterizer.cc @@ -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 diff --git a/engine/src/flutter/shell/common/rasterizer.h b/engine/src/flutter/shell/common/rasterizer.h new file mode 100644 index 0000000000..4c5619ccb2 --- /dev/null +++ b/engine/src/flutter/shell/common/rasterizer.h @@ -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 + +#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 GetWeakRasterizerPtr() = 0; + + virtual flow::LayerTree* GetLastLayerTree() = 0; + + virtual void Draw( + ftl::RefPtr> pipeline) = 0; + + // Implemented by each GPU backend. + static std::unique_ptr Create(); +}; + +} // namespace shell + +#endif // SHELL_COMMON_RASTERIZER_H_ diff --git a/engine/src/flutter/shell/common/shell.cc b/engine/src/flutter/shell/common/shell.cc new file mode 100644 index 0000000000..ee6e53fbe8 --- /dev/null +++ b/engine/src/flutter/shell/common/shell.cc @@ -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 +#include +#include + +#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 CreateMessagePumpMojo() { + return make_scoped_ptr(new mojo::common::MessagePumpMojo); +} + +bool IsInvalid(const ftl::WeakPtr& rasterizer) { + return !rasterizer; +} + +bool IsViewInvalid(const ftl::WeakPtr& 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 data_; +}; + +class NonDiscardableMemoryAllocator : public base::DiscardableMemoryAllocator { + public: + scoped_ptr AllocateLockedDiscardableMemory( + size_t size) override { + return make_scoped_ptr(new NonDiscardableMemory(size)); + } +}; + +base::LazyInstance 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( + gpu_thread_->message_loop()->task_runner()), + ftl::MakeRefCounted( + ui_thread_->message_loop()->task_runner()), + ftl::MakeRefCounted( + 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 end; + for (std::istream_iterator 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) { + 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>* rasterizers) { + FTL_DCHECK(gpu_thread_checker_ && gpu_thread_checker_->CalledOnValidThread()); + *rasterizers = rasterizers_; +} + +void Shell::AddPlatformView(const ftl::WeakPtr& 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>* platform_views) { + FTL_DCHECK(ui_thread_checker_ && ui_thread_checker_->CalledOnValidThread()); + *platform_views = platform_views_; +} + +void Shell::WaitForPlatformViewIds( + std::vector* 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* platform_view_ids, + ftl::AutoResetWaitableEvent* latch) { + std::vector> 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(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(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 diff --git a/engine/src/flutter/shell/common/shell.h b/engine/src/flutter/shell/common/shell.h new file mode 100644 index 0000000000..cdab8dc8d7 --- /dev/null +++ b/engine/src/flutter/shell/common/shell.h @@ -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); + void PurgeRasterizers(); + void GetRasterizers(std::vector>* rasterizer); + + // List of PlatformViews. + + // These APIs must only be accessed on UI thread. + void AddPlatformView(const ftl::WeakPtr& platform_view); + void PurgePlatformViews(); + void GetPlatformViews( + std::vector>* 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* 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* 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 gpu_thread_; + std::unique_ptr ui_thread_; + std::unique_ptr io_thread_; + + std::unique_ptr gpu_thread_checker_; + std::unique_ptr ui_thread_checker_; + + TracingController tracing_controller_; + + std::vector> rasterizers_; + std::vector> platform_views_; + + FTL_DISALLOW_COPY_AND_ASSIGN(Shell); +}; + +} // namespace shell + +#endif // SHELL_COMMON_SHELL_H_ diff --git a/engine/src/flutter/shell/common/switches.cc b/engine/src/flutter/shell/common/switches.cc new file mode 100644 index 0000000000..7e1e207f90 --- /dev/null +++ b/engine/src/flutter/shell/common/switches.cc @@ -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 + +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 diff --git a/engine/src/flutter/shell/common/switches.h b/engine/src/flutter/shell/common/switches.h new file mode 100644 index 0000000000..0f7c15a0cb --- /dev/null +++ b/engine/src/flutter/shell/common/switches.h @@ -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 + +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_ diff --git a/engine/src/flutter/shell/common/systrace_logger.cc b/engine/src/flutter/shell/common/systrace_logger.cc new file mode 100644 index 0000000000..1e13ecfb35 --- /dev/null +++ b/engine/src/flutter/shell/common/systrace_logger.cc @@ -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 +#include +#include +#include + +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 diff --git a/engine/src/flutter/shell/common/systrace_logger.h b/engine/src/flutter/shell/common/systrace_logger.h new file mode 100644 index 0000000000..6677c02ba0 --- /dev/null +++ b/engine/src/flutter/shell/common/systrace_logger.h @@ -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 + +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_ diff --git a/engine/src/flutter/shell/common/tracing_controller.cc b/engine/src/flutter/shell/common/tracing_controller.cc new file mode 100644 index 0000000000..355b0d9361 --- /dev/null +++ b/engine/src/flutter/shell/common/tracing_controller.cc @@ -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 + +#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( + new blink::EmbedderTracingCallbacks([this]() { StartTracing(); }, + [this]() { StopTracing(); }))); +} + +TracingController::~TracingController() { + blink::SetEmbedderTracingCallbacks(nullptr); +} + +static const char* WARN_UNUSED_RESULT +ConstructDartTimelineValue(std::vector& 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 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(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 diff --git a/engine/src/flutter/shell/common/tracing_controller.h b/engine/src/flutter/shell/common/tracing_controller.h new file mode 100644 index 0000000000..2c2e6d00e2 --- /dev/null +++ b/engine/src/flutter/shell/common/tracing_controller.h @@ -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 + +#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_ diff --git a/engine/src/flutter/shell/common/ui_delegate.cc b/engine/src/flutter/shell/common/ui_delegate.cc new file mode 100644 index 0000000000..e08ab8c08c --- /dev/null +++ b/engine/src/flutter/shell/common/ui_delegate.cc @@ -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 diff --git a/engine/src/flutter/shell/common/ui_delegate.h b/engine/src/flutter/shell/common/ui_delegate.h new file mode 100644 index 0000000000..993bfb2937 --- /dev/null +++ b/engine/src/flutter/shell/common/ui_delegate.h @@ -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 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_ diff --git a/engine/src/flutter/shell/gpu/BUILD.gn b/engine/src/flutter/shell/gpu/BUILD.gn new file mode 100644 index 0000000000..d0cc0cbd40 --- /dev/null +++ b/engine/src/flutter/shell/gpu/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/gpu/ganesh_canvas.cc b/engine/src/flutter/shell/gpu/ganesh_canvas.cc new file mode 100644 index 0000000000..a5ae1fa7d6 --- /dev/null +++ b/engine/src/flutter/shell/gpu/ganesh_canvas.cc @@ -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::Create( + kOpenGL_GrBackend, + reinterpret_cast(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 diff --git a/engine/src/flutter/shell/gpu/ganesh_canvas.h b/engine/src/flutter/shell/gpu/ganesh_canvas.h new file mode 100644 index 0000000000..c81fe65c6f --- /dev/null +++ b/engine/src/flutter/shell/gpu/ganesh_canvas.h @@ -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 gr_context_; + sk_sp sk_surface_; + + FTL_DISALLOW_COPY_AND_ASSIGN(GaneshCanvas); +}; + +} // namespace shell + +#endif // SHELL_GPU_DIRECT_GANESH_CANVAS_H_ diff --git a/engine/src/flutter/shell/gpu/gpu_canvas.cc b/engine/src/flutter/shell/gpu/gpu_canvas.cc new file mode 100644 index 0000000000..693a7e78e4 --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas.cc @@ -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 diff --git a/engine/src/flutter/shell/gpu/gpu_canvas.h b/engine/src/flutter/shell/gpu/gpu_canvas.h new file mode 100644 index 0000000000..972033d96f --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas.h @@ -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_ diff --git a/engine/src/flutter/shell/gpu/gpu_canvas_gl.cc b/engine/src/flutter/shell/gpu/gpu_canvas_gl.cc new file mode 100644 index 0000000000..088af3e528 --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas_gl.cc @@ -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 diff --git a/engine/src/flutter/shell/gpu/gpu_canvas_gl.h b/engine/src/flutter/shell/gpu/gpu_canvas_gl.h new file mode 100644 index 0000000000..b67772cccb --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas_gl.h @@ -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_ diff --git a/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.cc b/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.cc new file mode 100644 index 0000000000..87a8230a41 --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.cc @@ -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 diff --git a/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.h b/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.h new file mode 100644 index 0000000000..0bcd3983b2 --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_canvas_vulkan.h @@ -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_ diff --git a/engine/src/flutter/shell/gpu/gpu_rasterizer.cc b/engine/src/flutter/shell/gpu/gpu_rasterizer.cc new file mode 100644 index 0000000000..c7f7fa236c --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_rasterizer.cc @@ -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 +#include + +#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::Create() { + return std::unique_ptr(new GPURasterizer()); +} + +ftl::WeakPtr 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> pipeline) { + TRACE_EVENT0("flutter", "GPURasterizer::Draw"); + + if (!platform_view_) + return; + + flutter::Pipeline::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 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 picture = recorder.finishRecordingAsPicture(); + SerializePicture(path, picture.get()); + } + + last_layer_tree_ = std::move(layer_tree); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/gpu/gpu_rasterizer.h b/engine/src/flutter/shell/gpu/gpu_rasterizer.h new file mode 100644 index 0000000000..ca6cc84ef8 --- /dev/null +++ b/engine/src/flutter/shell/gpu/gpu_rasterizer.h @@ -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 GetWeakRasterizerPtr() override; + + flow::LayerTree* GetLastLayerTree() override; + + void Draw(ftl::RefPtr> pipeline) override; + + private: + GaneshCanvas ganesh_canvas_; + flow::CompositorContext compositor_context_; + std::unique_ptr last_layer_tree_; + PlatformView* platform_view_; + ftl::WeakPtrFactory weak_factory_; + + void DoDraw(std::unique_ptr tree); + + FTL_DISALLOW_COPY_AND_ASSIGN(GPURasterizer); +}; + +} // namespace shell + +#endif // SHELL_GPU_DIRECT_GPU_RASTERIZER_H_ diff --git a/engine/src/flutter/shell/platform/BUILD.gn b/engine/src/flutter/shell/platform/BUILD.gn new file mode 100644 index 0000000000..49cedfa78a --- /dev/null +++ b/engine/src/flutter/shell/platform/BUILD.gn @@ -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.") + } +} diff --git a/engine/src/flutter/shell/platform/android/AndroidManifest.xml b/engine/src/flutter/shell/platform/android/AndroidManifest.xml new file mode 100644 index 0000000000..3381f7272f --- /dev/null +++ b/engine/src/flutter/shell/platform/android/AndroidManifest.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + diff --git a/engine/src/flutter/shell/platform/android/BUILD.gn b/engine/src/flutter/shell/platform/android/BUILD.gn new file mode 100644 index 0000000000..fb3b775d7e --- /dev/null +++ b/engine/src/flutter/shell/platform/android/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/platform/android/flutter_main.cc b/engine/src/flutter/shell/platform/android/flutter_main.cc new file mode 100644 index 0000000000..49bed1ae86 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/flutter_main.cc @@ -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 + +#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> 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 scoped_context(env, context); + base::android::InitApplicationContext(env, scoped_context); + + std::vector 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(initTimeMillis) * static_cast(1000); + blink::engine_main_enter_ts = Dart_TimelineGetMicros() - initTimeMicros; +} + +bool RegisterFlutterMain(JNIEnv* env) { + return RegisterNativesImpl(env); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/android/flutter_main.h b/engine/src/flutter/shell/platform/android/flutter_main.h new file mode 100644 index 0000000000..f4f65c499f --- /dev/null +++ b/engine/src/flutter/shell/platform/android/flutter_main.h @@ -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 + +namespace shell { + +bool RegisterFlutterMain(JNIEnv* env); + +} // namespace shell + +#endif // SHELL_PLATFORM_ANDROID_FLUTTER_MAIN_H_ diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java b/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java new file mode 100644 index 0000000000..73b08ccb5f --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java @@ -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 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(); + 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 updatedObjects = new HashSet(); + Set removedObjects = new HashSet(); + 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 updatedObjects, + Set 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(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 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 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) {} + +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterMain.java b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterMain.java new file mode 100644 index 0000000000..1e29f2117a --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterMain.java @@ -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 SKY_RESOURCES = ImmutableSetBuilder.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 { + static ImmutableSetBuilder newInstance() { + return new ImmutableSetBuilder<>(); + } + + HashSet set = new HashSet<>(); + + private ImmutableSetBuilder() {} + + ImmutableSetBuilder add(T element) { + set.add(element); + return this; + } + + @SafeVarargs + final ImmutableSetBuilder add(T... elements) { + for (T element : elements) { + set.add(element); + } + return this; + } + + Set 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 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 listRootAssets(Context applicationContext) { + AssetManager manager = applicationContext.getResources().getAssets(); + try { + return ImmutableSetBuilder.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 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; + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java new file mode 100644 index 0000000000..7e7b1e9b43 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java @@ -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 mOnMessageListeners; + private HashMap 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 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(); + mAsyncOnMessageListeners = new HashMap(); + mActivityLifecycleListeners = new ArrayList(); + + 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 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 pointers = new ArrayList(); + + // 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> 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> dartServiceProvider = + ServiceProvider.MANAGER.getInterfaceRequest(core); + mDartServiceProvider = dartServiceProvider.first; + + Pair> platformServiceProvider = + ServiceProvider.MANAGER.getInterfaceRequest(core); + mPlatformServiceProviderBinding = ServiceProvider.MANAGER.bind( + mPlatformServiceProvider, platformServiceProvider.second); + + Pair> 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> 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> 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) {} + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceCleaner.java b/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceCleaner.java new file mode 100644 index 0000000000..5f203d1b2b --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceCleaner.java @@ -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 { + 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); + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceExtractor.java b/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceExtractor.java new file mode 100644 index 0000000000..4947bfb0d0 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/ResourceExtractor.java @@ -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 { + 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 mResources; + private ExtractTask mExtractTask; + + ResourceExtractor(Context context) { + mContext = context; + mResources = new HashSet(); + } + + ResourceExtractor addResource(String resource) { + mResources.add(resource); + return this; + } + + ResourceExtractor addResources(Collection 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(); + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceFactory.java b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceFactory.java new file mode 100644 index 0000000000..684775e07d --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceFactory.java @@ -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); +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceProviderImpl.java b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceProviderImpl.java new file mode 100644 index 0000000000..3497306be3 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceProviderImpl.java @@ -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 mBindings = new HashSet(); + + 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(); + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceRegistry.java b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceRegistry.java new file mode 100644 index 0000000000..0973a6087a --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/ServiceRegistry.java @@ -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 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(); + } + + 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); + } +} diff --git a/engine/src/flutter/shell/platform/android/library_loader.cc b/engine/src/flutter/shell/platform/android/library_loader.cc new file mode 100644 index 0000000000..a50d132e05 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/library_loader.cc @@ -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 register_callbacks; + register_callbacks.push_back(base::Bind(&RegisterJNI)); + + std::vector 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; +} diff --git a/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyActivity.java b/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyActivity.java new file mode 100644 index 0000000000..312083514d --- /dev/null +++ b/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyActivity.java @@ -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 args = new ArrayList(); + 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; + } +} diff --git a/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyApplication.java b/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyApplication.java new file mode 100644 index 0000000000..3078c82a61 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/org/domokit/sky/shell/SkyApplication.java @@ -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); + } +} diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.cc b/engine/src/flutter/shell/platform/android/platform_view_android.cc new file mode 100644 index 0000000000..10e81ebff0 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -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 +#include +#include +#include +#include +#include + +#include + +#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 +using EGLResult = std::pair; + +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 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 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 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 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(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( + 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(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 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 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 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 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(); + + base::android::ScopedJavaGlobalRef 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(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 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(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 diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.h b/engine/src/flutter/shell/platform/android/platform_view_android.h new file mode 100644 index 0000000000..6732523991 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -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 + +#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 GetBitmap(JNIEnv* env, + jobject obj); + + ftl::WeakPtr 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 context_; + ftl::WeakPtrFactory weak_factory_; + JavaObjectWeakGlobalRef flutter_view_; + + void UpdateThreadPriorities(); + + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewAndroid); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_ANDROID_PLATFORM_VIEW_ANDROID_H_ diff --git a/engine/src/flutter/shell/platform/darwin/BUILD.gn b/engine/src/flutter/shell/platform/darwin/BUILD.gn new file mode 100644 index 0000000000..509d906fc1 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/BUILD.gn @@ -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.") + } +} diff --git a/engine/src/flutter/shell/platform/darwin/common/BUILD.gn b/engine/src/flutter/shell/platform/darwin/common/BUILD.gn new file mode 100644 index 0000000000..fad4168c8f --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/platform/darwin/common/platform_mac.h b/engine/src/flutter/shell/platform/darwin/common/platform_mac.h new file mode 100644 index 0000000000..d443cb079a --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/platform_mac.h @@ -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_ diff --git a/engine/src/flutter/shell/platform/darwin/common/platform_mac.mm b/engine/src/flutter/shell/platform/darwin/common/platform_mac.mm new file mode 100644 index 0000000000..f8f41dbb0c --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/platform_mac.mm @@ -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 + +#include + +#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(); + +#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 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 g_embedder; + static std::once_flag once_main; + + std::call_once(once_main, [&]() { + g_embedder = WTF::MakeUnique(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 diff --git a/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.cc b/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.cc new file mode 100644 index 0000000000..77d331a5c4 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.cc @@ -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 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( + client_handle.Pass())); + return; + } + if (service_name == flutter::platform::PathProvider::Name_) { + new flutter::platform::PathProviderImpl( + mojo::InterfaceRequest( + client_handle.Pass())); + return; + } + if (service_name == flutter::platform::SystemChrome::Name_) { + new flutter::platform::SystemChromeImpl( + mojo::InterfaceRequest( + client_handle.Pass())); + return; + } + if (service_name == flutter::platform::SystemSound::Name_) { + new flutter::platform::SystemSoundImpl( + mojo::InterfaceRequest( + client_handle.Pass())); + return; + } + if (service_name == flutter::platform::URLLauncher::Name_) { + new flutter::platform::URLLauncherImpl( + mojo::InterfaceRequest( + 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 diff --git a/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.h b/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.h new file mode 100644 index 0000000000..662dfb7aef --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/platform_service_provider.h @@ -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; + + PlatformServiceProvider(mojo::InterfaceRequest request, + DynamicServiceProviderCallback callback); + + ~PlatformServiceProvider() override; + + void ConnectToService(const mojo::String& service_name, + mojo::ScopedMessagePipeHandle client_handle) override; + + private: + DynamicServiceProviderCallback dynamic_service_provider_; + mojo::StrongBinding binding_; + + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformServiceProvider); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_MAC_PLATFORM_SERVICE_PROVIDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/common/view_service_provider.cc b/engine/src/flutter/shell/platform/darwin/common/view_service_provider.cc new file mode 100644 index 0000000000..b982dc0e95 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/view_service_provider.cc @@ -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 + +namespace shell { + +ViewServiceProvider::ViewServiceProvider( + AppMesssagesConnector connect_to_app_messages, + mojo::InterfaceRequest 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 diff --git a/engine/src/flutter/shell/platform/darwin/common/view_service_provider.h b/engine/src/flutter/shell/platform/darwin/common/view_service_provider.h new file mode 100644 index 0000000000..357b3c5fda --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/common/view_service_provider.h @@ -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 + +#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)> + AppMesssagesConnector; + +class ViewServiceProvider : public mojo::ServiceProvider { + public: + ViewServiceProvider(AppMesssagesConnector connect_to_app_messages, + mojo::InterfaceRequest request); + ~ViewServiceProvider() override; + + void ConnectToService(const mojo::String& service_name, + mojo::ScopedMessagePipeHandle client_handle) override; + + private: + mojo::StrongBinding binding_; + AppMesssagesConnector connect_to_app_messages_; + + FTL_DISALLOW_COPY_AND_ASSIGN(ViewServiceProvider); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_MAC_VIEW_SERVICE_PROVIDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/desktop/BUILD.gn b/engine/src/flutter/shell/platform/darwin/desktop/BUILD.gn new file mode 100644 index 0000000000..cf2e8974fe --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/platform/darwin/desktop/Info.plist b/engine/src/flutter/shell/platform/darwin/desktop/Info.plist new file mode 100644 index 0000000000..76ee583303 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/Info.plist @@ -0,0 +1,34 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + SkyShell + CFBundleIconFile + + CFBundleIdentifier + org.domokit.sky + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Flutter + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSMinimumSystemVersion + 10.6 + NSHumanReadableCopyright + Copyright 2015 The Flutter Authors. All rights reserved. + NSMainNibFile + sky_mac + NSPrincipalClass + SkyApplication + + diff --git a/engine/src/flutter/shell/platform/darwin/desktop/main_mac.mm b/engine/src/flutter/shell/platform/darwin/desktop/main_mac.mm new file mode 100644 index 0000000000..ebce906623 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/main_mac.mm @@ -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 + +#include + +#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); +} diff --git a/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.h b/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.h new file mode 100644 index 0000000000..de666905af --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.h @@ -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 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 opengl_view_; + base::scoped_nsobject resource_loading_context_; + sky::SkyEnginePtr sky_engine_; + ftl::WeakPtrFactory 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_ diff --git a/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.mm b/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.mm new file mode 100644 index 0000000000..153092a5ab --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/platform_view_mac.mm @@ -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 +#include + +#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) {} + +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 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 diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.h b/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.h new file mode 100644 index 0000000000..dbe422b293 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.h @@ -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 + +@interface SkyAppDelegate : NSObject + +@end diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.m b/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.m new file mode 100644 index 0000000000..c6ba6c5696 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_app_delegate.m @@ -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 diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_application.h b/engine/src/flutter/shell/platform/darwin/desktop/sky_application.h new file mode 100644 index 0000000000..77d4ead943 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_application.h @@ -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 + +#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 +@end + +#endif /* defined(__SHELL_MAC_SKY_APPLICATION__) */ diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_application.mm b/engine/src/flutter/shell/platform/darwin/desktop/sky_application.mm new file mode 100644 index 0000000000..e295517503 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_application.mm @@ -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 scoper(&handlingSendEvent_, YES); + [super sendEvent:event]; +} + +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { + handlingSendEvent_ = handlingSendEvent; +} + +- (BOOL)isHandlingSendEvent { + return handlingSendEvent_; +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_mac.xib b/engine/src/flutter/shell/platform/darwin/desktop/sky_mac.xib new file mode 100644 index 0000000000..88f0843c56 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_mac.xib @@ -0,0 +1,695 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_window.h b/engine/src/flutter/shell/platform/darwin/desktop/sky_window.h new file mode 100644 index 0000000000..07540aba16 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_window.h @@ -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 + +@interface SkyWindow : NSWindow + +@end diff --git a/engine/src/flutter/shell/platform/darwin/desktop/sky_window.mm b/engine/src/flutter/shell/platform/darwin/desktop/sky_window.mm new file mode 100644 index 0000000000..d6192e22a2 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/desktop/sky_window.mm @@ -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 () + +@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 _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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn new file mode 100644 index 0000000000..595d00562e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -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", + ] +} diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h new file mode 100644 index 0000000000..a01fe9b3cb --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/Flutter.h @@ -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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h new file mode 100644 index 0000000000..693185e66e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h @@ -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 + +#include "FlutterMacros.h" + +// Empty implementation of UIApplicationDelegate, for simple apps +// that don't need to customize the application delegate. +FLUTTER_EXPORT +@interface FlutterAppDelegate : UIResponder + +@property(strong, nonatomic) UIWindow* window; + +@end + +#endif // FLUTTER_FLUTTERDARTPROJECT_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h new file mode 100644 index 0000000000..dd3cc14662 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h @@ -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 + +#include "FlutterMacros.h" + +FLUTTER_EXPORT +@protocol FlutterAsyncMessageListener + +- (void)didReceiveString:(NSString*)message + callback:(void(^)(NSString*))sendResponse; + +@property(readonly, strong, nonatomic) NSString* messageName; + +@end + +#endif // FLUTTER_FLUTTERASYNCMESSAGELISTENER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterDartProject.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterDartProject.h new file mode 100644 index 0000000000..2e1d6eba13 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterDartProject.h @@ -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 + +#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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMacros.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMacros.h new file mode 100644 index 0000000000..06da54a873 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMacros.h @@ -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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h new file mode 100644 index 0000000000..bbf344f229 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h @@ -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 + +#include "FlutterMacros.h" + +FLUTTER_EXPORT +@protocol FlutterMessageListener + +- (NSString*)didReceiveString:(NSString*)message; + +@property(readonly, strong, nonatomic) NSString* messageName; + +@end + +#endif // FLUTTER_FLUTTERMESSAGELISTENER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h new file mode 100644 index 0000000000..574cea93e4 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h @@ -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 +#import + +#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*)listener; + +- (void)removeMessageListener:(NSObject*)listener; + +- (void)addAsyncMessageListener:(NSObject*)listener; + +- (void)removeAsyncMessageListener:(NSObject*)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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist b/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist new file mode 100644 index 0000000000..f4bcd10f8e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + Flutter + CFBundleIdentifier + io.flutter.flutter + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Flutter + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm new file mode 100644 index 0000000000..b69ee92637 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm @@ -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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm new file mode 100644 index 0000000000..8b96296c9b --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm @@ -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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h new file mode 100644 index 0000000000..31c1c28e73 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h @@ -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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h new file mode 100644 index 0000000000..ebf869bae8 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.h @@ -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 + +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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.mm new file mode 100644 index 0000000000..dc4b1ed19d --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDartSource.mm @@ -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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h new file mode 100644 index 0000000000..9c05fce0df --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h @@ -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 +#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_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.mm new file mode 100644 index 0000000000..79300a39b5 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.mm @@ -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 + +#include + +@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 _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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h new file mode 100644 index 0000000000..661940620c --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h @@ -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 + +@interface FlutterView : UIView + +@end + +#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTER_VIEW_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm new file mode 100644 index 0000000000..0bab07bf1d --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm @@ -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 () + +@end + +@implementation FlutterView + +- (void)layoutSubviews { + CGFloat screenScale = [UIScreen mainScreen].scale; + CAEAGLLayer* layer = reinterpret_cast(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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm new file mode 100644 index 0000000000..2dd00a5f43 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -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 () +@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 _dartProject; + UIInterfaceOrientationMask _orientationPreferences; + UIStatusBarStyle _statusBarStyle; + sky::ViewportMetricsPtr _viewportMetrics; + shell::TouchMapper _touchMapper; + std::unique_ptr _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( + reinterpret_cast(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; +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(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 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*)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*)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*)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*)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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h new file mode 100644 index 0000000000..0f8be847db --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h @@ -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 +#include +#include + +#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) override; + + UIView* view() { return view_; } + semantics::SemanticsServer* server() { return semantics_server_.get(); } + + private: + SemanticObject* UpdateSemanticObject( + const semantics::SemanticsNodePtr& node, + std::set* updated_objects, + std::set* removed_objects); + void RemoveSemanticObject(SemanticObject* node, + std::set* updated_objects); + + UIView* view_; + semantics::SemanticsServerPtr semantics_server_; + std::unordered_map objects_; + + mojo::Binding binding_; + + FTL_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm new file mode 100644 index 0000000000..771b0dbd3d --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.mm @@ -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 +#include + +#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 _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(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*)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 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 nodes) { + std::set updated_objects; + std::set 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* updated_objects, + std::set* 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* 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* 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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h new file mode 100644 index 0000000000..d473ce3ca5 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h @@ -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 + +#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 GetWeakPtr(); + void AddBinding( + mojo::InterfaceRequest request); + + void SetMessageListener(const std::string& message_name, + NSObject* listener); + + void SetAsyncMessageListener(const std::string& message_name, + NSObject* listener); + + private: + void SendString(const mojo::String& message_name, + const mojo::String& message, + const SendStringCallback& callback) override; + + mojo::BindingSet binding_; + std::unordered_map*> listeners_; + std::unordered_map*> + async_listeners_; + + ftl::WeakPtrFactory weak_factory_; +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.mm new file mode 100644 index 0000000000..b6d4de6832 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.mm @@ -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. + +#include "flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h" + +#include "base/strings/sys_string_conversions.h" + +namespace shell { + +ApplicationMessagesImpl::ApplicationMessagesImpl() : weak_factory_(this) {} + +ApplicationMessagesImpl::~ApplicationMessagesImpl() {} + +ftl::WeakPtr ApplicationMessagesImpl::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +void ApplicationMessagesImpl::AddBinding( + mojo::InterfaceRequest request) { + binding_.AddBinding(this, request.Pass()); +} + +void ApplicationMessagesImpl::SetMessageListener( + const std::string& message_name, + NSObject* listener) { + if (listener) + listeners_[message_name] = listener; + else + listeners_.erase(message_name); +} + +void ApplicationMessagesImpl::SetAsyncMessageListener( + const std::string& message_name, + NSObject* listener) { + if (listener) + async_listeners_[message_name] = listener; + else + async_listeners_.erase(message_name); +} + +void ApplicationMessagesImpl::SendString(const mojo::String& message_name, + const mojo::String& message, + const SendStringCallback& callback) { + std::string message_name_str = message_name; + NSString* ns_message = base::SysUTF8ToNSString(message); + + { + auto it = listeners_.find(message_name_str); + if (it != listeners_.end()) { + NSString* response = [it->second didReceiveString:ns_message]; + callback.Run(base::SysNSStringToUTF8(response)); + return; + } + } + + { + auto it = async_listeners_.find(message_name_str); + if (it != async_listeners_.end()) { + SendStringCallback local_callback = callback; + [it->second + didReceiveString:ns_message + callback:^(NSString* response) { + local_callback.Run(base::SysNSStringToUTF8(response)); + }]; + } + } +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h new file mode 100644 index 0000000000..1fa6b420d8 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h @@ -0,0 +1,40 @@ +// 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_TOUCH_MAPPER_H_ +#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_TOUCH_MAPPER_H_ + +#include + +#include "lib/ftl/macros.h" + +#include + +namespace shell { + +/// UITouch pointers cannot be used as touch ids (even though they remain +/// constant throughout the multitouch sequence) because internal components +/// assume that ids are < 16. This class maps touch pointers to ids +class TouchMapper { + public: + TouchMapper(); + ~TouchMapper(); + + int registerTouch(UITouch* touch); + + int unregisterTouch(UITouch* touch); + + int identifierOf(UITouch* touch) const; + + private: + using BitSet = long long int; + BitSet free_spots_; + std::map touch_map_; + + FTL_DISALLOW_COPY_AND_ASSIGN(TouchMapper); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_TOUCH_MAPPER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.mm new file mode 100644 index 0000000000..b0a69b03ac --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.mm @@ -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. + +#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h" + +namespace shell { + +TouchMapper::TouchMapper() : free_spots_(~0) {} + +TouchMapper::~TouchMapper() = default; + +int TouchMapper::registerTouch(UITouch* touch) { + int freeSpot = ffsll(free_spots_); + touch_map_[touch] = freeSpot; + free_spots_ &= ~(1 << (freeSpot - 1)); + return freeSpot; +} + +int TouchMapper::unregisterTouch(UITouch* touch) { + auto index = touch_map_[touch]; + free_spots_ |= 1 << (index - 1); + touch_map_.erase(touch); + return index; +} + +int TouchMapper::identifierOf(UITouch* touch) const { + return touch_map_.at(touch); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap b/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap new file mode 100644 index 0000000000..bf81c8a865 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/module.modulemap @@ -0,0 +1,6 @@ +framework module Flutter { + umbrella header "Flutter.h" + + export * + module * { export * } +} diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h new file mode 100644 index 0000000000..a086321e5a --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h @@ -0,0 +1,75 @@ +// 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_PLATFORM_VIEW_IOS_H_ +#define SHELL_PLATFORM_IOS_PLATFORM_VIEW_IOS_H_ + +#include + +#include "lib/ftl/macros.h" +#include "lib/ftl/memory/weak_ptr.h" +#include "base/mac/scoped_nsobject.h" +#include "flutter/services/platform/app_messages.mojom.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/application_messages_impl.h" +#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDynamicServiceLoader.h" +#include "flutter/shell/common/platform_view.h" + +@class CAEAGLLayer; +@class UIView; + +namespace shell { + +class IOSGLContext; + +class PlatformViewIOS : public PlatformView { + public: + explicit PlatformViewIOS(CAEAGLLayer* layer); + + ~PlatformViewIOS() override; + + void ToggleAccessibility(UIView* view, bool enable); + + void ConnectToEngineAndSetupServices(); + + sky::SkyEnginePtr& engineProxy(); + + flutter::platform::ApplicationMessagesPtr& AppMessageSender(); + + ApplicationMessagesImpl& AppMessageReceiver(); + + ftl::WeakPtr 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: + std::unique_ptr context_; + sky::SkyEnginePtr engine_; + mojo::ServiceProviderPtr dart_services_; + flutter::platform::ApplicationMessagesPtr app_message_sender_; + ApplicationMessagesImpl app_message_receiver_; + std::unique_ptr accessibility_bridge_; + base::scoped_nsprotocol dynamic_service_loader_; + ftl::WeakPtrFactory weak_factory_; + + void SetupAndLoadFromSource(const std::string& main, + const std::string& packages, + const std::string& assets_directory); + + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewIOS); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_IOS_PLATFORM_VIEW_IOS_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm new file mode 100644 index 0000000000..ef694ba781 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.mm @@ -0,0 +1,398 @@ +// 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/platform_view_ios.h" + +#include "base/mac/scoped_nsautorelease_pool.h" +#include "base/trace_event/trace_event.h" +#include "flutter/shell/platform/darwin/common/view_service_provider.h" +#include "flutter/sky/engine/wtf/MakeUnique.h" +#include "lib/ftl/synchronization/waitable_event.h" +#include "mojo/public/cpp/application/connect.h" + +#import +#import +#import +#import + +namespace shell { + +struct GLintSize { + GLint width; + GLint height; + + GLintSize() : width(0), height(0) {} + + GLintSize(GLint w, GLint h) : width(w), height(h) {} + + GLintSize(CGSize size) + : width(static_cast(size.width)), + height(static_cast(size.height)) {} + + bool operator==(const GLintSize& other) const { + return width == other.width && height == other.height; + } +}; + +class IOSGLContext { + public: + IOSGLContext(PlatformView::SurfaceConfig config, CAEAGLLayer* layer) + : layer_([layer retain]), + context_([[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]), + resource_context_([[EAGLContext alloc] + initWithAPI:kEAGLRenderingAPIOpenGLES2 + sharegroup:context_.get().sharegroup]), + framebuffer_(GL_NONE), + colorbuffer_(GL_NONE), + depthbuffer_(GL_NONE), + stencilbuffer_(GL_NONE), + depth_stencil_packed_buffer_(GL_NONE) { + base::mac::ScopedNSAutoreleasePool pool; + + CHECK(layer_ != nullptr); + CHECK(context_ != nullptr); + CHECK(resource_context_ != nullptr); + + bool context_current = [EAGLContext setCurrentContext:context_]; + + DCHECK(context_current); + DCHECK(glGetError() == GL_NO_ERROR); + + // Generate the framebuffer + + glGenFramebuffers(1, &framebuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + DCHECK(framebuffer_ != GL_NONE); + + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + // Setup color attachment + + glGenRenderbuffers(1, &colorbuffer_); + DCHECK(colorbuffer_ != GL_NONE); + + glBindRenderbuffer(GL_RENDERBUFFER, colorbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_RENDERBUFFER, colorbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + // On iOS, if both depth and stencil attachments are requested, we are + // required to create a single renderbuffer that acts as both. + + auto requires_packed = + (config.depth_bits != 0) && (config.stencil_bits != 0); + + if (requires_packed) { + glGenRenderbuffers(1, &depth_stencil_packed_buffer_); + glBindRenderbuffer(GL_RENDERBUFFER, depth_stencil_packed_buffer_); + DCHECK(depth_stencil_packed_buffer_ != GL_NONE); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, + GL_RENDERBUFFER, depth_stencil_packed_buffer_); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, depth_stencil_packed_buffer_); + DCHECK(depth_stencil_packed_buffer_ != GL_NONE); + } else { + // Setup the depth attachment if necessary + if (config.depth_bits != 0) { + glGenRenderbuffers(1, &depthbuffer_); + DCHECK(depthbuffer_ != GL_NONE); + + glBindRenderbuffer(GL_RENDERBUFFER, depthbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, + GL_RENDERBUFFER, depthbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + } + + // Setup the stencil attachment if necessary + if (config.stencil_bits != 0) { + glGenRenderbuffers(1, &stencilbuffer_); + DCHECK(stencilbuffer_ != GL_NONE); + + glBindRenderbuffer(GL_RENDERBUFFER, stencilbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, stencilbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + } + } + + // The default is RGBA + NSString* drawableColorFormat = kEAGLColorFormatRGBA8; + + if (config.red_bits <= 5 && config.green_bits <= 6 && + config.blue_bits <= 5 && config.alpha_bits == 0) { + drawableColorFormat = kEAGLColorFormatRGB565; + } + + layer_.get().drawableProperties = @{ + kEAGLDrawablePropertyColorFormat : drawableColorFormat, + kEAGLDrawablePropertyRetainedBacking : @(NO), + }; + } + + ~IOSGLContext() { + DCHECK(glGetError() == GL_NO_ERROR); + + // Deletes on GL_NONEs are ignored + glDeleteFramebuffers(1, &framebuffer_); + + glDeleteRenderbuffers(1, &colorbuffer_); + glDeleteRenderbuffers(1, &depthbuffer_); + glDeleteRenderbuffers(1, &stencilbuffer_); + glDeleteRenderbuffers(1, &depth_stencil_packed_buffer_); + + DCHECK(glGetError() == GL_NO_ERROR); + } + + bool PresentRenderBuffer() const { + base::mac::ScopedNSAutoreleasePool pool; + + const GLenum discards[] = { + GL_DEPTH_ATTACHMENT, GL_STENCIL_ATTACHMENT, + }; + + glDiscardFramebufferEXT(GL_FRAMEBUFFER, sizeof(discards) / sizeof(GLenum), + discards); + + glBindRenderbuffer(GL_RENDERBUFFER, colorbuffer_); + return [[EAGLContext currentContext] presentRenderbuffer:GL_RENDERBUFFER]; + } + + GLuint framebuffer() const { return framebuffer_; } + + bool MakeCurrent() { + base::mac::ScopedNSAutoreleasePool pool; + + return UpdateStorageSizeIfNecessary() && + [EAGLContext setCurrentContext:context_.get()]; + } + + bool ResourceMakeCurrent() { + base::mac::ScopedNSAutoreleasePool pool; + + return [EAGLContext setCurrentContext:resource_context_.get()]; + } + + private: + base::scoped_nsobject layer_; + base::scoped_nsobject context_; + base::scoped_nsobject resource_context_; + + GLuint framebuffer_; + GLuint colorbuffer_; + GLuint depthbuffer_; + GLuint stencilbuffer_; + GLuint depth_stencil_packed_buffer_; + + GLintSize storage_size_; + + bool UpdateStorageSizeIfNecessary() { + GLintSize size([layer_.get() bounds].size); + + if (size == storage_size_) { + // Nothing to since the stoage size is already consistent with the layer. + return true; + } + + if (![EAGLContext setCurrentContext:context_]) { + return false; + } + + DCHECK(glGetError() == GL_NO_ERROR); + + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); + + glBindRenderbuffer(GL_RENDERBUFFER, colorbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + + if (![context_.get() renderbufferStorage:GL_RENDERBUFFER + fromDrawable:layer_.get()]) { + return false; + } + + GLint width = 0; + GLint height = 0; + bool rebind_color_buffer = false; + + if (depthbuffer_ != GL_NONE || stencilbuffer_ != GL_NONE || + depth_stencil_packed_buffer_ != GL_NONE) { + // Fetch the dimensions of the color buffer whose backing was just updated + // so that backing of the attachments can be updated + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, + &width); + DCHECK(glGetError() == GL_NO_ERROR); + + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, + &height); + DCHECK(glGetError() == GL_NO_ERROR); + + rebind_color_buffer = true; + } + + if (depth_stencil_packed_buffer_ != GL_NONE) { + glBindRenderbuffer(GL_RENDERBUFFER, depth_stencil_packed_buffer_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, + height); + DCHECK(glGetError() == GL_NO_ERROR); + } + + if (depthbuffer_ != GL_NONE) { + glBindRenderbuffer(GL_RENDERBUFFER, depthbuffer_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, + height); + DCHECK(glGetError() == GL_NO_ERROR); + } + + if (stencilbuffer_ != GL_NONE) { + glBindRenderbuffer(GL_RENDERBUFFER, stencilbuffer_); + glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); + DCHECK(glGetError() == GL_NO_ERROR); + } + + if (rebind_color_buffer) { + glBindRenderbuffer(GL_RENDERBUFFER, colorbuffer_); + DCHECK(glGetError() == GL_NO_ERROR); + } + + storage_size_ = GLintSize(width, height); + DCHECK(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); + + return true; + } + + FTL_DISALLOW_COPY_AND_ASSIGN(IOSGLContext); +}; + +PlatformViewIOS::PlatformViewIOS(CAEAGLLayer* layer) + : context_(WTF::MakeUnique(surface_config_, layer)), + dynamic_service_loader_([[FlutterDynamicServiceLoader alloc] init]), + weak_factory_(this) { + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, + NSUserDomainMask, YES); + shell::Shell::Shared().tracing_controller().set_traces_base_path( + [paths.firstObject UTF8String]); +} + +PlatformViewIOS::~PlatformViewIOS() = default; + +sky::SkyEnginePtr& PlatformViewIOS::engineProxy() { + return engine_; +} + +flutter::platform::ApplicationMessagesPtr& PlatformViewIOS::AppMessageSender() { + return app_message_sender_; +} + +shell::ApplicationMessagesImpl& PlatformViewIOS::AppMessageReceiver() { + return app_message_receiver_; +} + +void PlatformViewIOS::ToggleAccessibility(UIView* view, bool enable) { + if (enable) { + if (!accessibility_bridge_ && dart_services_.get() != nullptr) { + accessibility_bridge_.reset( + new shell::AccessibilityBridge(view, dart_services_.get())); + } + } else { + accessibility_bridge_ = nullptr; + } +} + +static void DynamicServiceResolve(void* baton, + const mojo::String& service_name, + mojo::ScopedMessagePipeHandle handle) { + base::mac::ScopedNSAutoreleasePool pool; + auto loader = reinterpret_cast(baton); + [loader resolveService:@(service_name.data()) handle:handle.Pass()]; +} + +void PlatformViewIOS::ConnectToEngineAndSetupServices() { + ConnectToEngine(mojo::GetProxy(&engine_)); + + mojo::ServiceProviderPtr service_provider; + + auto service_provider_proxy = mojo::GetProxy(&service_provider); + + auto service_resolution_callback = base::Bind( + &DynamicServiceResolve, + base::Unretained(reinterpret_cast(dynamic_service_loader_.get()))); + + new PlatformServiceProvider(service_provider_proxy.Pass(), + service_resolution_callback); + + ftl::WeakPtr appplication_messages_impl = + app_message_receiver_.GetWeakPtr(); + + mojo::ServiceProviderPtr viewServiceProvider; + + new ViewServiceProvider( + [appplication_messages_impl]( + mojo::InterfaceRequest + request) { + if (appplication_messages_impl) + appplication_messages_impl->AddBinding(std::move(request)); + }, + mojo::GetProxy(&viewServiceProvider)); + + sky::ServicesDataPtr services = sky::ServicesData::New(); + services->incoming_services = service_provider.Pass(); + services->outgoing_services = mojo::GetProxy(&dart_services_); + services->view_services = viewServiceProvider.Pass(); + engine_->SetServices(services.Pass()); + + mojo::ConnectToService(dart_services_.get(), + mojo::GetProxy(&app_message_sender_)); +} + +void PlatformViewIOS::SetupAndLoadFromSource( + const std::string& main, + const std::string& packages, + const std::string& assets_directory) { + ConnectToEngineAndSetupServices(); + engine_->RunFromFile(main, packages, assets_directory); +} + +ftl::WeakPtr PlatformViewIOS::GetWeakViewPtr() { + return weak_factory_.GetWeakPtr(); +} + +uint64_t PlatformViewIOS::DefaultFramebuffer() const { + return context_ != nullptr ? context_->framebuffer() : GL_NONE; +} + +bool PlatformViewIOS::ContextMakeCurrent() { + return context_ != nullptr ? context_->MakeCurrent() : false; +} + +bool PlatformViewIOS::ResourceContextMakeCurrent() { + return context_ != nullptr ? context_->ResourceMakeCurrent() : false; +} + +bool PlatformViewIOS::SwapBuffers() { + TRACE_EVENT0("flutter", "PlatformViewIOS::SwapBuffers"); + return context_ != nullptr ? context_->PresentRenderBuffer() : false; +} + +void PlatformViewIOS::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 diff --git a/engine/src/flutter/shell/platform/linux/BUILD.gn b/engine/src/flutter/shell/platform/linux/BUILD.gn new file mode 100644 index 0000000000..cd78ab8d63 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/BUILD.gn @@ -0,0 +1,38 @@ +# 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. + +executable("linux") { + output_name = "sky_shell" + + sources = [ + "glfw_service_provider.cc", + "glfw_service_provider.h", + "main_linux.cc", + "message_pump_glfw.cc", + "message_pump_glfw.h", + "platform_view_glfw.cc", + "platform_view_glfw.h", + ] + + deps = [ + "//base", + "//flutter/services/engine:interfaces", + "//flutter/services/raw_keyboard:interfaces", + "//flutter/shell/common", + "//flutter/shell/gpu", + "//flutter/shell/testing", + "//flutter/skia", + "//lib/ftl", + "//mojo/common", + "//mojo/edk/base_edk", + "//mojo/edk/system", + "//mojo/public/cpp/bindings:utility", + "//mojo/public/interfaces/application", + "//third_party/glfw", + ] + + ldflags = [ + "-lGL", + ] +} diff --git a/engine/src/flutter/shell/platform/linux/glfw_service_provider.cc b/engine/src/flutter/shell/platform/linux/glfw_service_provider.cc new file mode 100644 index 0000000000..4b1cb17b09 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/glfw_service_provider.cc @@ -0,0 +1,19 @@ +// 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 "glfw_service_provider.h" + +namespace shell { + +GLFWServiceProvider::GLFWServiceProvider( + mojo::InterfaceRequest request) + : binding_(this, request.Pass()) {} + +GLFWServiceProvider::~GLFWServiceProvider() {} + +void GLFWServiceProvider::ConnectToService( + const mojo::String& service_name, + mojo::ScopedMessagePipeHandle client_handle) {} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/linux/glfw_service_provider.h b/engine/src/flutter/shell/platform/linux/glfw_service_provider.h new file mode 100644 index 0000000000..682ccb914d --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/glfw_service_provider.h @@ -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 FLUTTER_SHELL_PLATFORM_LINUX_GLFW_SERVICE_PROVIDER_H_ +#define FLUTTER_SHELL_PLATFORM_LINUX_GLFW_SERVICE_PROVIDER_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 GLFWServiceProvider : public mojo::ServiceProvider { + public: + GLFWServiceProvider(mojo::InterfaceRequest request); + + ~GLFWServiceProvider() override; + + void ConnectToService(const mojo::String& service_name, + mojo::ScopedMessagePipeHandle client_handle) override; + + private: + mojo::StrongBinding binding_; + + FTL_DISALLOW_COPY_AND_ASSIGN(GLFWServiceProvider); +}; + +} // namespace shell + +#endif // FLUTTER_SHELL_PLATFORM_LINUX_GLFW_SERVICE_PROVIDER_H_ diff --git a/engine/src/flutter/shell/platform/linux/main_linux.cc b/engine/src/flutter/shell/platform/linux/main_linux.cc new file mode 100644 index 0000000000..5f71f801e8 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/main_linux.cc @@ -0,0 +1,108 @@ +// 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/at_exit.h" +#include "base/basictypes.h" +#include "base/bind.h" +#include "base/command_line.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/platform/linux/message_pump_glfw.h" +#include "flutter/shell/platform/linux/platform_view_glfw.h" +#include "flutter/shell/testing/testing.h" +#include "mojo/edk/embedder/embedder.h" +#include "mojo/edk/embedder/simple_platform_support.h" + +namespace { + +int RunNonInteractive() { + base::MessageLoop message_loop; + + mojo::embedder::Init(mojo::embedder::CreateSimplePlatformSupport()); + shell::Shell::InitStandalone(); + + if (!shell::InitForTesting()) { + shell::switches::PrintUsage("sky_shell"); + return 1; + } + + message_loop.Run(); + return 0; +} + +static bool IsDartFile(const std::string& script_uri) { + std::string dart_extension = ".dart"; + return script_uri.rfind(dart_extension) == + (script_uri.size() - dart_extension.size()); +} + +int RunInteractive() { + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + + base::MessageLoop message_loop(shell::MessagePumpGLFW::Create()); + + mojo::embedder::Init(mojo::embedder::CreateSimplePlatformSupport()); + shell::Shell::InitStandalone(); + + auto args = command_line.GetArgs(); + if (args.empty()) + return 1; + + std::string bundle_path = + command_line.GetSwitchValueASCII(shell::switches::kFLX); + + if (bundle_path.empty()) { + // Alternatively, use the first positional argument. + bundle_path = args[0]; + } + + if (bundle_path.empty()) { + return 1; + } + + std::unique_ptr platform_view( + new shell::PlatformViewGLFW()); + + platform_view->ConnectToEngineAndSetupServices(); + + platform_view->NotifyCreated(); + + if (IsDartFile(bundle_path)) { + // Load directly from source. + platform_view->EngineProxy()->RunFromFile(bundle_path, "", ""); + + } else { + // Load from a bundle. + std::string script_uri = std::string("file://") + bundle_path; + platform_view->EngineProxy()->RunFromBundle(script_uri, bundle_path); + } + + message_loop.Run(); + + platform_view->NotifyDestroyed(); + + return 0; +} + +} // namespace + +int main(int argc, const char* argv[]) { + base::AtExitManager exit_manager; + base::CommandLine::Init(argc, argv); + + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + + if (command_line.HasSwitch(shell::switches::kHelp)) { + shell::switches::PrintUsage("sky_shell"); + return 0; + } + + if (command_line.HasSwitch(shell::switches::kNonInteractive)) { + return RunNonInteractive(); + } + + return RunInteractive(); +} diff --git a/engine/src/flutter/shell/platform/linux/message_pump_glfw.cc b/engine/src/flutter/shell/platform/linux/message_pump_glfw.cc new file mode 100644 index 0000000000..82ae94c6b6 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/message_pump_glfw.cc @@ -0,0 +1,82 @@ +// 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/linux/message_pump_glfw.h" + +#include + +#include "base/auto_reset.h" +#include "base/logging.h" +#include "base/time/time.h" + +namespace shell { + +MessagePumpGLFW::MessagePumpGLFW() : in_run_(false), should_quit_(false) {} + +MessagePumpGLFW::~MessagePumpGLFW() = default; + +scoped_ptr MessagePumpGLFW::Create() { + return scoped_ptr(new MessagePumpGLFW()); +} + +void MessagePumpGLFW::Run(Delegate* delegate) { + base::AutoReset auto_reset_keep_running(&should_quit_, false); + base::AutoReset auto_reset_in_run(&in_run_, true); + + for (;;) { + bool did_work = delegate->DoWork(); + if (should_quit_) + break; + + did_work |= delegate->DoDelayedWork(&delayed_work_time_); + if (should_quit_) + break; + + if (did_work) + continue; + + did_work = delegate->DoIdleWork(); + if (should_quit_) + break; + + if (did_work) + continue; + + if (delayed_work_time_.is_null()) { + glfwWaitEvents(); + } else { + base::TimeDelta delay = delayed_work_time_ - base::TimeTicks::Now(); + if (delay > base::TimeDelta()) { + glfwWaitEventsTimeout(delay.InSecondsF()); + } else { + // It looks like delayed_work_time_ indicates a time in the past, so we + // need to call DoDelayedWork now. + delayed_work_time_ = base::TimeTicks(); + } + } + + if (should_quit_) + break; + } +} + +void MessagePumpGLFW::Quit() { + DCHECK(in_run_) << "Quit was called outside of Run!"; + should_quit_ = true; + ScheduleWork(); +} + +void MessagePumpGLFW::ScheduleWork() { + glfwPostEmptyEvent(); +} + +void MessagePumpGLFW::ScheduleDelayedWork( + const base::TimeTicks& delayed_work_time) { + // We know that we can't be blocked on Wait right now since this method can + // only be called on the same thread as Run, so we only need to update our + // record of how long to sleep when we do sleep. + delayed_work_time_ = delayed_work_time; +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/linux/message_pump_glfw.h b/engine/src/flutter/shell/platform/linux/message_pump_glfw.h new file mode 100644 index 0000000000..f2b5767a55 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/message_pump_glfw.h @@ -0,0 +1,41 @@ +// 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_GLFW_MESSAGE_PUMP_GLFW_H_ +#define SHELL_PLATFORM_GLFW_MESSAGE_PUMP_GLFW_H_ + +#include "lib/ftl/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_pump.h" +#include "base/time/time.h" + +namespace shell { + +class MessagePumpGLFW : public base::MessagePump { + public: + MessagePumpGLFW(); + + ~MessagePumpGLFW() override; + + static scoped_ptr Create(); + + void Run(Delegate* delegate) override; + + void Quit() override; + + void ScheduleWork() override; + + void ScheduleDelayedWork(const base::TimeTicks& delayed_work_time) override; + + private: + bool in_run_; + bool should_quit_; + base::TimeTicks delayed_work_time_; + + FTL_DISALLOW_COPY_AND_ASSIGN(MessagePumpGLFW); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_GLFW_MESSAGE_PUMP_GLFW_H_ diff --git a/engine/src/flutter/shell/platform/linux/platform_view_glfw.cc b/engine/src/flutter/shell/platform/linux/platform_view_glfw.cc new file mode 100644 index 0000000000..eac3116dc3 --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/platform_view_glfw.cc @@ -0,0 +1,182 @@ +// 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/linux/platform_view_glfw.h" +#include "flutter/shell/platform/linux/glfw_service_provider.h" + +#include + +namespace shell { + +inline PlatformViewGLFW* ToPlatformView(GLFWwindow* window) { + return static_cast(glfwGetWindowUserPointer(window)); +} + +PlatformViewGLFW::PlatformViewGLFW() + : valid_(false), glfw_window_(nullptr), buttons_(0), weak_factory_(this) { + if (!glfwInit()) { + return; + } + + glfw_window_ = glfwCreateWindow(640, 480, "Flutter", NULL, NULL); + if (glfw_window_ == nullptr) { + return; + } + + glfwSetWindowUserPointer(glfw_window_, this); + + glfwSetWindowSizeCallback( + glfw_window_, [](GLFWwindow* window, int width, int height) { + ToPlatformView(window)->OnWindowSizeChanged(width, height); + }); + + glfwSetMouseButtonCallback( + glfw_window_, [](GLFWwindow* window, int button, int action, int mods) { + ToPlatformView(window)->OnMouseButtonChanged(button, action, mods); + }); + + glfwSetKeyCallback(glfw_window_, [](GLFWwindow* window, int key, int scancode, + int action, int mods) { + ToPlatformView(window)->OnKeyEvent(key, scancode, action, mods); + }); + + valid_ = true; +} + +PlatformViewGLFW::~PlatformViewGLFW() { + if (glfw_window_ != nullptr) { + glfwSetWindowUserPointer(glfw_window_, nullptr); + glfwDestroyWindow(glfw_window_); + glfw_window_ = nullptr; + } + + glfwTerminate(); +} + +void PlatformViewGLFW::ConnectToEngineAndSetupServices() { + ConnectToEngine(mojo::GetProxy(&engine_)); + + mojo::ServiceProviderPtr platform_service_provider; + new GLFWServiceProvider(mojo::GetProxy(&platform_service_provider)); + + sky::ServicesDataPtr services = sky::ServicesData::New(); + services->incoming_services = platform_service_provider.Pass(); + engine_->SetServices(services.Pass()); +} + +sky::SkyEnginePtr& PlatformViewGLFW::EngineProxy() { + return engine_; +} + +bool PlatformViewGLFW::IsValid() const { + return valid_; +} + +ftl::WeakPtr PlatformViewGLFW::GetWeakViewPtr() { + return weak_factory_.GetWeakPtr(); +} + +uint64_t PlatformViewGLFW::DefaultFramebuffer() const { + // The default window bound FBO. + return 0; +} + +bool PlatformViewGLFW::ContextMakeCurrent() { + glfwMakeContextCurrent(glfw_window_); + return true; +} + +bool PlatformViewGLFW::ResourceContextMakeCurrent() { + // Resource loading contexts are not supported on this platform. + return false; +} + +bool PlatformViewGLFW::SwapBuffers() { + glfwSwapBuffers(glfw_window_); + return true; +} + +void PlatformViewGLFW::RunFromSource(const std::string& main, + const std::string& packages, + const std::string& assets_directory) {} + +void PlatformViewGLFW::OnWindowSizeChanged(int width, int height) { + auto metrics = sky::ViewportMetrics::New(); + metrics->physical_width = width; + metrics->physical_height = height; + metrics->device_pixel_ratio = 1.0; + engine_->OnViewportMetricsChanged(metrics.Pass()); +} + +void PlatformViewGLFW::OnMouseButtonChanged(int button, int action, int mods) { + pointer::PointerType type; + if (action == GLFW_PRESS) { + if (!buttons_) { + type = pointer::PointerType::DOWN; + glfwSetCursorPosCallback( + glfw_window_, [](GLFWwindow* window, double x, double y) { + ToPlatformView(window)->OnCursorPosChanged(x, y); + }); + } else { + type = pointer::PointerType::MOVE; + } + // GLFW's button order matches what we want: + // https://github.com/flutter/engine/blob/master/sky/specs/pointer.md + // http://www.glfw.org/docs/3.2/group__buttons.html + buttons_ |= 1 << button; + } else if (action == GLFW_RELEASE) { + buttons_ &= ~(1 << button); + if (!buttons_) { + type = pointer::PointerType::UP; + glfwSetCursorPosCallback(glfw_window_, nullptr); + } else { + type = pointer::PointerType::MOVE; + } + } else { + DLOG(INFO) << "Unknown mouse action: " << action; + return; + } + + double x = 0.f, y = 0.f; + glfwGetCursorPos(glfw_window_, &x, &y); + + base::TimeDelta time_stamp = base::TimeTicks::Now() - base::TimeTicks(); + + auto pointer_data = pointer::Pointer::New(); + pointer_data->time_stamp = time_stamp.InMicroseconds(); + pointer_data->type = type; + pointer_data->kind = pointer::PointerKind::MOUSE; + pointer_data->x = x; + pointer_data->y = y; + pointer_data->buttons = buttons_; + pointer_data->pressure = 1.0; + pointer_data->pressure_max = 1.0; + + auto pointer_packet = pointer::PointerPacket::New(); + pointer_packet->pointers.push_back(pointer_data.Pass()); + engine_->OnPointerPacket(pointer_packet.Pass()); +} + +void PlatformViewGLFW::OnCursorPosChanged(double x, double y) { + base::TimeDelta time_stamp = base::TimeTicks::Now() - base::TimeTicks(); + + auto pointer_data = pointer::Pointer::New(); + pointer_data->time_stamp = time_stamp.InMicroseconds(); + pointer_data->type = pointer::PointerType::MOVE; + pointer_data->kind = pointer::PointerKind::MOUSE; + pointer_data->x = x; + pointer_data->y = y; + pointer_data->buttons = buttons_; + pointer_data->pressure = 1.0; + pointer_data->pressure_max = 1.0; + + auto pointer_packet = pointer::PointerPacket::New(); + pointer_packet->pointers.push_back(pointer_data.Pass()); + engine_->OnPointerPacket(pointer_packet.Pass()); +} + +void PlatformViewGLFW::OnKeyEvent(int key, int scancode, int action, int mods) { +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/linux/platform_view_glfw.h b/engine/src/flutter/shell/platform/linux/platform_view_glfw.h new file mode 100644 index 0000000000..329dc590cd --- /dev/null +++ b/engine/src/flutter/shell/platform/linux/platform_view_glfw.h @@ -0,0 +1,63 @@ +// 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_GLFW_PLATFORM_VIEW_GLFW_H_ +#define SHELL_PLATFORM_GLFW_PLATFORM_VIEW_GLFW_H_ + +#include + +#include "flutter/shell/common/platform_view.h" +#include "lib/ftl/memory/weak_ptr.h" + +struct GLFWwindow; + +namespace shell { + +class PlatformViewGLFW : public PlatformView { + public: + PlatformViewGLFW(); + + ~PlatformViewGLFW() override; + + void ConnectToEngineAndSetupServices(); + + sky::SkyEnginePtr& EngineProxy(); + + bool IsValid() const; + + ftl::WeakPtr 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: + bool valid_; + GLFWwindow* glfw_window_; + sky::SkyEnginePtr engine_; + int buttons_; + ftl::WeakPtrFactory weak_factory_; + + void OnWindowSizeChanged(int width, int height); + + void OnMouseButtonChanged(int button, int action, int mods); + + void OnCursorPosChanged(double x, double y); + + void OnKeyEvent(int key, int scancode, int action, int mods); + + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewGLFW); +}; + +} // namespace shell + +#endif // SHELL_PLATFORM_GLFW_PLATFORM_VIEW_GLFW_H_ diff --git a/engine/src/flutter/shell/testing/BUILD.gn b/engine/src/flutter/shell/testing/BUILD.gn new file mode 100644 index 0000000000..67a7f011bf --- /dev/null +++ b/engine/src/flutter/shell/testing/BUILD.gn @@ -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. + +source_set("testing") { + sources = [ + "platform_view_test.cc", + "platform_view_test.h", + "test_runner.cc", + "test_runner.h", + "testing.cc", + "testing.h", + ] + + deps = [ + "../common", + "//base", + "//flutter/services/engine:interfaces", + "//flutter/skia", + "//lib/ftl", + "//mojo/public/cpp/bindings", + ] +} diff --git a/engine/src/flutter/shell/testing/observatory/empty_main.dart b/engine/src/flutter/shell/testing/observatory/empty_main.dart new file mode 100644 index 0000000000..bf3b7d4496 --- /dev/null +++ b/engine/src/flutter/shell/testing/observatory/empty_main.dart @@ -0,0 +1,6 @@ +// 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. + +main() { +} diff --git a/engine/src/flutter/shell/testing/observatory/launcher.dart b/engine/src/flutter/shell/testing/observatory/launcher.dart new file mode 100644 index 0000000000..8e53db207e --- /dev/null +++ b/engine/src/flutter/shell/testing/observatory/launcher.dart @@ -0,0 +1,74 @@ +// 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 observatory_sky_shell_launcher; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +class ShellProcess { + final Completer _observatoryUriCompleter = new Completer(); + final Process _process; + + ShellProcess(this._process) { + assert(_process != null); + // Scan stdout and scrape the Observatory Uri. + _process.stdout.transform(UTF8.decoder) + .transform(new LineSplitter()).listen((line) { + const String observatoryUriPrefix = 'Observatory listening on '; + if (line.startsWith(observatoryUriPrefix)) { + print(line); + Uri uri = Uri.parse(line.substring(observatoryUriPrefix.length)); + _observatoryUriCompleter.complete(uri); + } + }); + } + + Future kill() async { + if (_process == null) { + return false; + } + return _process.kill(); + } + + Future waitForObservatory() async { + return _observatoryUriCompleter.future; + } +} + +class ShellLauncher { + final List args = [ + '--observatory-port=0', + ]; + final String shellExecutablePath; + final String mainDartPath; + final bool startPaused; + + ShellLauncher(this.shellExecutablePath, + this.mainDartPath, + this.startPaused, + List extraArgs) { + if (extraArgs is List) { + args.addAll(extraArgs); + } + args.add(mainDartPath); + } + + Future launch() async { + try { + List shellArguments = []; + if (startPaused) { + shellArguments.add('--start-paused'); + } + shellArguments.addAll(args); + print('Launching $shellExecutablePath $shellArguments'); + var process = await Process.start(shellExecutablePath, shellArguments); + return new ShellProcess(process); + } catch (e) { + print('Error launching shell: $e'); + } + return null; + } +} diff --git a/engine/src/flutter/shell/testing/observatory/service_client.dart b/engine/src/flutter/shell/testing/observatory/service_client.dart new file mode 100644 index 0000000000..00b62e8df9 --- /dev/null +++ b/engine/src/flutter/shell/testing/observatory/service_client.dart @@ -0,0 +1,63 @@ +// 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 observatory_sky_shell_service_client; + + +import 'dart:async'; +import 'dart:convert'; + +class ServiceClient { + ServiceClient(this.client) { + client.listen(_onData, + onError: _onError, + cancelOnError: true); + } + + Future invokeRPC(String method, [Map params]) async { + var key = _createKey(); + var request = JSON.encode({ + 'jsonrpc': '2.0', + 'method': method, + 'params': params == null ? {} : params, + 'id': key, + }); + client.add(request); + var completer = new Completer(); + _outstanding_requests[key] = completer; + print('-> $key ($method)'); + return completer.future; + } + + String _createKey() { + var key = '$_id'; + _id++; + return key; + } + + void _onData(String message) { + var response = JSON.decode(message); + var key = response['id']; + print('<- $key'); + var completer = _outstanding_requests.remove(key); + assert(completer != null); + var result = response['result']; + var error = response['error']; + if (error != null) { + assert(result == null); + completer.completeError(error); + } else { + assert(result != null); + completer.complete(result); + } + } + + void _onError(error) { + print('WebSocket error: $error'); + } + + final WebSocket client; + final Map _outstanding_requests = {}; + var _id = 1; +} diff --git a/engine/src/flutter/shell/testing/observatory/test.dart b/engine/src/flutter/shell/testing/observatory/test.dart new file mode 100644 index 0000000000..3a00383a48 --- /dev/null +++ b/engine/src/flutter/shell/testing/observatory/test.dart @@ -0,0 +1,192 @@ +// 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. + +// This is a minimal dependency heart beat test for Observatory. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'launcher.dart'; +import 'service_client.dart'; + +class Expect { + static equals(dynamic actual, dynamic expected) { + if (actual != expected) { + throw 'Expected $actual == $expected'; + } + } + + static contains(String needle, String haystack) { + if (!haystack.contains(needle)) { + throw 'Expected $haystack to contain $needle'; + } + } + + static isTrue(bool tf) { + if (tf != true) { + throw 'Expected $a to be true'; + } + } + + static isFalse(bool tf) { + if (tf != false) { + throw 'Expected $a to be false'; + } + } + + static notExecuted() { + throw 'Should not have hit'; + } + + static isNotNull(dynamic a) { + if (a == null) { + throw 'Expected $a to not be null'; + } + } +} + +Future readResponse(HttpClientResponse response) { + var completer = new Completer(); + var contents = new StringBuffer(); + response.transform(UTF8.decoder).listen((String data) { + contents.write(data); + }, onDone: () => completer.complete(contents.toString())); + return completer.future; +} + +// Test accessing the service protocol over http. +Future testHttpProtocolRequest(Uri uri) async { + uri = uri.replace(path: 'getVM'); + HttpClient client = new HttpClient(); + HttpClientRequest request = await client.getUrl(uri); + HttpClientResponse response = await request.close(); + Expect.equals(response.statusCode, 200); + Map responseAsMap = JSON.decode(await readResponse(response)); + Expect.equals(responseAsMap['jsonrpc'], "2.0"); + client.close(); +} + +// Test accessing the service protocol over ws. +Future testWebSocketProtocolRequest(Uri uri) async { + uri = uri.replace(scheme: 'ws', path: 'ws'); + WebSocket webSocketClient = await WebSocket.connect(uri.toString()); + ServiceClient serviceClient = new ServiceClient(webSocketClient); + Map response = await serviceClient.invokeRPC('getVM'); + Expect.equals(response['type'], 'VM'); + try { + await serviceClient.invokeRPC('BART_SIMPSON'); + Expect.notExecuted(); + } catch (e) { + // Method not found. + Expect.equals(e['code'], -32601); + } +} + +// Test accessing an Observatory UI asset. +Future testHttpAssetRequest(Uri uri) async { + uri = uri.replace(path: 'third_party/trace_viewer_full.html'); + HttpClient client = new HttpClient(); + HttpClientRequest request = await client.getUrl(uri); + HttpClientResponse response = await request.close(); + Expect.equals(response.statusCode, 200); + await response.drain(); + client.close(); +} + +Future testStartPaused(Uri uri) async { + uri = uri.replace(scheme: 'ws', path: 'ws'); + WebSocket webSocketClient = await WebSocket.connect(uri.toString()); + ServiceClient serviceClient = new ServiceClient(webSocketClient); + + // Wait until we have the isolateId. + String isolateId; + while (isolateId == null) { + Map response = await serviceClient.invokeRPC('getVM'); + Expect.equals(response['type'], 'VM'); + if (response['isolates'].length > 0) { + isolateId = response['isolates'][0]['id']; + } + } + + // Grab the isolate. + Map isolate = await serviceClient.invokeRPC('getIsolate', { + 'isolateId': isolateId, + }); + Expect.equals(isolate['type'], 'Isolate'); + // Verify that it is paused at start. + Expect.isNotNull(isolate['pauseEvent']); + Expect.equals(isolate['pauseEvent']['kind'], 'PauseStart'); + + // Resume the isolate. + await serviceClient.invokeRPC('resume', { + 'isolateId': isolateId, + }); + + // Wait until the isolate has resumed. + while (true) { + Map response = await serviceClient.invokeRPC('getIsolate', { + 'isolateId': isolateId, + }); + Expect.equals(response['type'], 'Isolate'); + Expect.isNotNull(response['pauseEvent']); + if (response['pauseEvent']['kind'] == 'Resume') { + break; + } + } +} + +typedef Future TestFunction(Uri uri); + +final List basicTests = [ + testHttpProtocolRequest, + testWebSocketProtocolRequest, + testHttpAssetRequest +]; + +final List startPausedTests = [ + testStartPaused, +]; + +bool runTests(ShellLauncher launcher, List tests) async { + ShellProcess process = await launcher.launch(); + Uri uri = await process.waitForObservatory(); + try { + for (var i = 0; i < tests.length; i++) { + print('Executing test ${i+1}/${tests.length}'); + await tests[i](uri); + } + } catch (e) { + print('Observatory test failure: $e'); + exitCode = -1; + } + await process.kill(); + return exitCode == 0; +} + +main(List args) async { + if (args.length < 2) { + print('Usage: dart ${Platform.script} ' + ' ...'); + return; + } + final String shellExecutablePath = args[0]; + final String mainDartPath = args[1]; + final List extraArgs = args.length <= 2 ? [] : args.sublist(2); + + final ShellLauncher launcher = + new ShellLauncher(shellExecutablePath, + mainDartPath, + false, + extraArgs); + + final ShellLauncher startPausedlauncher = + new ShellLauncher(shellExecutablePath, + mainDartPath, + true, + extraArgs); + + await runTests(launcher, basicTests); + await runTests(startPausedlauncher, startPausedTests); +} diff --git a/engine/src/flutter/shell/testing/platform_view_test.cc b/engine/src/flutter/shell/testing/platform_view_test.cc new file mode 100644 index 0000000000..392cd1db7f --- /dev/null +++ b/engine/src/flutter/shell/testing/platform_view_test.cc @@ -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. + +#include "flutter/shell/testing/platform_view_test.h" + +#include "flutter/shell/common/shell.h" + +namespace shell { + +PlatformViewTest::PlatformViewTest() : weak_factory_(this) {} + +PlatformViewTest::~PlatformViewTest() = default; + +ftl::WeakPtr PlatformViewTest::GetWeakViewPtr() { + return weak_factory_.GetWeakPtr(); +} + +uint64_t PlatformViewTest::DefaultFramebuffer() const { + return 0; +} + +bool PlatformViewTest::ContextMakeCurrent() { + return false; +} + +bool PlatformViewTest::ResourceContextMakeCurrent() { + return false; +} + +bool PlatformViewTest::SwapBuffers() { + return false; +} + +void PlatformViewTest::RunFromSource(const std::string& main, + const std::string& packages, + const std::string& assets_directory) {} + +} // namespace shell diff --git a/engine/src/flutter/shell/testing/platform_view_test.h b/engine/src/flutter/shell/testing/platform_view_test.h new file mode 100644 index 0000000000..357e4f2db8 --- /dev/null +++ b/engine/src/flutter/shell/testing/platform_view_test.h @@ -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_TESTING_PLATFORM_VIEW_TEST_H_ +#define SHELL_TESTING_PLATFORM_VIEW_TEST_H_ + +#include "flutter/shell/common/platform_view.h" +#include "lib/ftl/macros.h" +#include "lib/ftl/memory/weak_ptr.h" + +namespace shell { + +class Shell; + +class PlatformViewTest : public PlatformView { + public: + PlatformViewTest(); + + ~PlatformViewTest(); + + ftl::WeakPtr 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: + ftl::WeakPtrFactory weak_factory_; + + FTL_DISALLOW_COPY_AND_ASSIGN(PlatformViewTest); +}; + +} // namespace shell + +#endif // SHELL_TESTING_PLATFORM_VIEW_TEST_H_ diff --git a/engine/src/flutter/shell/testing/test_runner.cc b/engine/src/flutter/shell/testing/test_runner.cc new file mode 100644 index 0000000000..7428041f35 --- /dev/null +++ b/engine/src/flutter/shell/testing/test_runner.cc @@ -0,0 +1,42 @@ +// Copyright 2014 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/testing/test_runner.h" + +#include + +#include "base/message_loop/message_loop.h" +#include "base/strings/string_util.h" +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/shell.h" +#include "flutter/shell/testing/platform_view_test.h" + +namespace shell { + +TestRunner::TestRunner() + : platform_view_(new PlatformViewTest()), weak_ptr_factory_(this) { + platform_view_->ConnectToEngine(GetProxy(&sky_engine_)); + + sky::ViewportMetricsPtr metrics = sky::ViewportMetrics::New(); + + metrics->physical_width = 800; + metrics->physical_height = 600; + + sky_engine_->OnViewportMetricsChanged(metrics.Pass()); +} + +TestRunner::~TestRunner() = default; + +TestRunner& TestRunner::Shared() { + static TestRunner* g_test_runner = nullptr; + if (!g_test_runner) + g_test_runner = new TestRunner(); + return *g_test_runner; +} + +void TestRunner::Run(const TestDescriptor& test) { + sky_engine_->RunFromFile(test.path, test.packages, ""); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/testing/test_runner.h b/engine/src/flutter/shell/testing/test_runner.h new file mode 100644 index 0000000000..0078a2e742 --- /dev/null +++ b/engine/src/flutter/shell/testing/test_runner.h @@ -0,0 +1,44 @@ +// 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_TESTING_TEST_RUNNER_H_ +#define SHELL_TESTING_TEST_RUNNER_H_ + +#include +#include + +#include "flutter/services/engine/sky_engine.mojom.h" +#include "lib/ftl/macros.h" +#include "lib/ftl/memory/weak_ptr.h" +#include "mojo/public/cpp/bindings/binding_set.h" + +namespace shell { + +class PlatformView; + +class TestRunner { + public: + static TestRunner& Shared(); + + struct TestDescriptor { + std::string path; + std::string packages; + }; + + void Run(const TestDescriptor& test); + + private: + TestRunner(); + ~TestRunner(); + + std::unique_ptr platform_view_; + sky::SkyEnginePtr sky_engine_; + ftl::WeakPtrFactory weak_ptr_factory_; + + FTL_DISALLOW_COPY_AND_ASSIGN(TestRunner); +}; + +} // namespace shell + +#endif // SHELL_TESTING_TEST_RUNNER_H_ diff --git a/engine/src/flutter/shell/testing/testing.cc b/engine/src/flutter/shell/testing/testing.cc new file mode 100644 index 0000000000..e31c9224cd --- /dev/null +++ b/engine/src/flutter/shell/testing/testing.cc @@ -0,0 +1,27 @@ +// 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/testing/testing.h" + +#include "base/command_line.h" +#include "flutter/shell/common/switches.h" +#include "flutter/shell/testing/test_runner.h" + +namespace shell { + +bool InitForTesting() { + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + + TestRunner::TestDescriptor test; + test.packages = command_line.GetSwitchValueASCII(switches::kPackages); + auto args = command_line.GetArgs(); + if (args.empty()) + return false; + test.path = args[0]; + + TestRunner::Shared().Run(test); + return true; +} + +} // namespace shell diff --git a/engine/src/flutter/shell/testing/testing.h b/engine/src/flutter/shell/testing/testing.h new file mode 100644 index 0000000000..e85e0b9c73 --- /dev/null +++ b/engine/src/flutter/shell/testing/testing.h @@ -0,0 +1,14 @@ +// 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_TESTING_TESTING_H_ +#define SHELL_TESTING_TESTING_H_ + +namespace shell { + +bool InitForTesting(); + +} // namespace shell + +#endif // SHELL_TESTING_TESTING_H_ diff --git a/engine/src/flutter/sky/BUILD.gn b/engine/src/flutter/sky/BUILD.gn index 273025a05b..a02ba1d835 100644 --- a/engine/src/flutter/sky/BUILD.gn +++ b/engine/src/flutter/sky/BUILD.gn @@ -10,7 +10,7 @@ group("sky") { deps = [ "//flutter/sky/engine/wtf:unittests($host_toolchain)", "//flutter/sky/packages", - "//flutter/sky/shell", + "//flutter/shell", ] if (dart_host_toolchain == host_toolchain) {