diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index ca2a71387b..2ec58e6f5a 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1325,17 +1325,24 @@ FILE: ../../../flutter/shell/platform/linux/public/flutter_linux/flutter_linux.h FILE: ../../../flutter/shell/platform/windows/angle_surface_manager.cc FILE: ../../../flutter/shell/platform/windows/angle_surface_manager.h FILE: ../../../flutter/shell/platform/windows/client_wrapper/dart_project_unittests.cc +FILE: ../../../flutter/shell/platform/windows/client_wrapper/flutter_engine.cc +FILE: ../../../flutter/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc FILE: ../../../flutter/shell/platform/windows/client_wrapper/flutter_view_controller.cc FILE: ../../../flutter/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc FILE: ../../../flutter/shell/platform/windows/client_wrapper/flutter_view_unittests.cc FILE: ../../../flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h +FILE: ../../../flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h FILE: ../../../flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h FILE: ../../../flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h FILE: ../../../flutter/shell/platform/windows/client_wrapper/include/flutter/plugin_registrar_windows.h FILE: ../../../flutter/shell/platform/windows/client_wrapper/plugin_registrar_windows_unittests.cc FILE: ../../../flutter/shell/platform/windows/cursor_handler.cc FILE: ../../../flutter/shell/platform/windows/cursor_handler.h +FILE: ../../../flutter/shell/platform/windows/flutter_project_bundle.cc +FILE: ../../../flutter/shell/platform/windows/flutter_project_bundle.h FILE: ../../../flutter/shell/platform/windows/flutter_windows.cc +FILE: ../../../flutter/shell/platform/windows/flutter_windows_engine.cc +FILE: ../../../flutter/shell/platform/windows/flutter_windows_engine.h FILE: ../../../flutter/shell/platform/windows/flutter_windows_view.cc FILE: ../../../flutter/shell/platform/windows/flutter_windows_view.h FILE: ../../../flutter/shell/platform/windows/key_event_handler.cc diff --git a/engine/src/flutter/shell/platform/windows/BUILD.gn b/engine/src/flutter/shell/platform/windows/BUILD.gn index 14adddc19c..87bcde9ab7 100644 --- a/engine/src/flutter/shell/platform/windows/BUILD.gn +++ b/engine/src/flutter/shell/platform/windows/BUILD.gn @@ -42,7 +42,11 @@ source_set("flutter_windows_source") { "angle_surface_manager.h", "cursor_handler.cc", "cursor_handler.h", + "flutter_project_bundle.cc", + "flutter_project_bundle.h", "flutter_windows.cc", + "flutter_windows_engine.cc", + "flutter_windows_engine.h", "flutter_windows_view.cc", "flutter_windows_view.h", "key_event_handler.cc", diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/BUILD.gn b/engine/src/flutter/shell/platform/windows/client_wrapper/BUILD.gn index 6f89a81a2d..b9fbbcc946 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/BUILD.gn +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/BUILD.gn @@ -7,12 +7,16 @@ import("//flutter/testing/testing.gni") _wrapper_includes = [ "include/flutter/dart_project.h", + "include/flutter/flutter_engine.h", "include/flutter/flutter_view_controller.h", "include/flutter/flutter_view.h", "include/flutter/plugin_registrar_windows.h", ] -_wrapper_sources = [ "flutter_view_controller.cc" ] +_wrapper_sources = [ + "flutter_engine.cc", + "flutter_view_controller.cc", +] # This code will be merged into .../common/cpp/client_wrapper for client use, # so uses header paths that assume the merged state. Include the header @@ -69,6 +73,7 @@ executable("client_wrapper_windows_unittests") { sources = [ "dart_project_unittests.cc", + "flutter_engine_unittests.cc", "flutter_view_controller_unittests.cc", "flutter_view_unittests.cc", "plugin_registrar_windows_unittests.cc", diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine.cc b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine.cc new file mode 100644 index 0000000000..aeb8b73938 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine.cc @@ -0,0 +1,70 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/flutter/flutter_engine.h" + +#include +#include + +namespace flutter { + +FlutterEngine::FlutterEngine(const DartProject& project) + : project_(std::make_unique(project)) {} + +FlutterEngine::~FlutterEngine() { + ShutDown(); +} + +bool FlutterEngine::Run(const char* entry_point) { + if (engine_) { + std::cerr << "Cannot run an already running engine. Create a new instance " + "or call ShutDown first." + << std::endl; + return false; + } + + FlutterDesktopEngineProperties c_engine_properties = {}; + c_engine_properties.assets_path = project_->assets_path().c_str(); + c_engine_properties.icu_data_path = project_->icu_data_path().c_str(); + c_engine_properties.aot_library_path = project_->aot_library_path().c_str(); + c_engine_properties.entry_point = entry_point; + std::vector engine_switches; + std::transform( + project_->engine_switches().begin(), project_->engine_switches().end(), + std::back_inserter(engine_switches), + [](const std::string& arg) -> const char* { return arg.c_str(); }); + if (engine_switches.size() > 0) { + c_engine_properties.switches = &engine_switches[0]; + c_engine_properties.switches_count = engine_switches.size(); + } + + engine_ = UniqueEnginePtr(FlutterDesktopRunEngine(c_engine_properties), + FlutterDesktopShutDownEngine); + if (!engine_) { + std::cerr << "Failed to start engine." << std::endl; + return false; + } + return true; +} + +void FlutterEngine::ShutDown() { + engine_ = nullptr; +} + +std::chrono::nanoseconds FlutterEngine::ProcessMessages() { + return std::chrono::nanoseconds(FlutterDesktopProcessMessages(engine_.get())); +} + +FlutterDesktopPluginRegistrarRef FlutterEngine::GetRegistrarForPlugin( + const std::string& plugin_name) { + if (!engine_) { + std::cerr << "Cannot get plugin registrar on an engine that isn't running; " + "call Run first." + << std::endl; + return nullptr; + } + return FlutterDesktopGetPluginRegistrar(engine_.get(), plugin_name.c_str()); +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc new file mode 100644 index 0000000000..cc73374829 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_engine_unittests.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h" +#include "flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h" +#include "gtest/gtest.h" + +namespace flutter { + +namespace { + +// Stub implementation to validate calls to the API. +class TestFlutterWindowsApi : public testing::StubFlutterWindowsApi { + public: + // |flutter::testing::StubFlutterWindowsApi| + FlutterDesktopEngineRef RunEngine( + const FlutterDesktopEngineProperties& properties) override { + run_called_ = true; + return reinterpret_cast(1); + } + + // |flutter::testing::StubFlutterWindowsApi| + uint64_t ProcessMessages() override { return 99; } + + // |flutter::testing::StubFlutterWindowsApi| + bool ShutDownEngine() override { + shut_down_called_ = true; + return true; + } + + bool run_called() { return run_called_; } + + bool shut_down_called() { return shut_down_called_; } + + private: + bool run_called_ = false; + bool shut_down_called_ = false; +}; + +} // namespace + +TEST(FlutterEngineTest, CreateDestroy) { + testing::ScopedStubFlutterWindowsApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + { + FlutterEngine engine(DartProject(L"fake/project/path")); + engine.Run(); + EXPECT_EQ(test_api->run_called(), true); + EXPECT_EQ(test_api->shut_down_called(), false); + } + // Destroying should implicitly shut down if it hasn't been done manually. + EXPECT_EQ(test_api->shut_down_called(), true); +} + +TEST(FlutterEngineTest, ExplicitShutDown) { + testing::ScopedStubFlutterWindowsApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + FlutterEngine engine(DartProject(L"fake/project/path")); + engine.Run(); + EXPECT_EQ(test_api->run_called(), true); + EXPECT_EQ(test_api->shut_down_called(), false); + engine.ShutDown(); + EXPECT_EQ(test_api->shut_down_called(), true); +} + +TEST(FlutterEngineTest, ProcessMessages) { + testing::ScopedStubFlutterWindowsApi scoped_api_stub( + std::make_unique()); + auto test_api = static_cast(scoped_api_stub.stub()); + + FlutterEngine engine(DartProject(L"fake/project/path")); + engine.Run(); + + std::chrono::nanoseconds next_event_time = engine.ProcessMessages(); + EXPECT_EQ(next_event_time.count(), 99); +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller.cc b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller.cc index 16dd49f8a2..89b61f192c 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller.cc +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller.cc @@ -32,32 +32,7 @@ FlutterViewController::FlutterViewController(int width, return; } view_ = std::make_unique(FlutterDesktopGetView(controller_)); -} - -FlutterViewController::FlutterViewController( - const std::string& icu_data_path, - int width, - int height, - const std::string& assets_path, - const std::vector& arguments) { - if (controller_) { - std::cerr << "Only one Flutter view can exist at a time." << std::endl; - } - - std::vector engine_arguments; - std::transform( - arguments.begin(), arguments.end(), std::back_inserter(engine_arguments), - [](const std::string& arg) -> const char* { return arg.c_str(); }); - size_t arg_count = engine_arguments.size(); - - controller_ = FlutterDesktopCreateViewControllerLegacy( - width, height, assets_path.c_str(), icu_data_path.c_str(), - arg_count > 0 ? &engine_arguments[0] : nullptr, arg_count); - if (!controller_) { - std::cerr << "Failed to create view controller." << std::endl; - return; - } - view_ = std::make_unique(FlutterDesktopGetView(controller_)); + engine_ = FlutterDesktopGetEngine(controller_); } FlutterViewController::~FlutterViewController() { @@ -67,18 +42,16 @@ FlutterViewController::~FlutterViewController() { } std::chrono::nanoseconds FlutterViewController::ProcessMessages() { - return std::chrono::nanoseconds(FlutterDesktopProcessMessages(controller_)); + return std::chrono::nanoseconds(FlutterDesktopProcessMessages(engine_)); } FlutterDesktopPluginRegistrarRef FlutterViewController::GetRegistrarForPlugin( const std::string& plugin_name) { - if (!controller_) { - std::cerr << "Cannot get plugin registrar without a window; call " - "CreateWindow first." - << std::endl; + if (!engine_) { + std::cerr << "Cannot get plugin registrar without an engine." << std::endl; return nullptr; } - return FlutterDesktopGetPluginRegistrar(controller_, plugin_name.c_str()); + return FlutterDesktopGetPluginRegistrar(engine_, plugin_name.c_str()); } } // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc index ec1b7fb561..126a7dcb2b 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc @@ -25,16 +25,6 @@ class TestWindowsApi : public testing::StubFlutterWindowsApi { } // namespace -TEST(FlutterViewControllerTest, CreateDestroyLegacy) { - testing::ScopedStubFlutterWindowsApi scoped_api_stub( - std::make_unique()); - auto test_api = static_cast(scoped_api_stub.stub()); - { - FlutterViewController controller("", 100, 100, "", - std::vector{}); - } -} - TEST(FlutterViewControllerTest, CreateDestroy) { DartProject project(L"data"); testing::ScopedStubFlutterWindowsApi scoped_api_stub( diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h index ae542aebf1..6c94ffa757 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h @@ -45,6 +45,7 @@ class DartProject { // flexible options for project structures are needed later without it // being a breaking change. Provide access to internal classes that need // them. + friend class FlutterEngine; friend class FlutterViewController; friend class DartProjectTest; diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h new file mode 100644 index 0000000000..c398b7f5be --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_engine.h @@ -0,0 +1,70 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ + +#define NOMINMAX +#include + +#include +#include +#include + +#include "dart_project.h" +#include "plugin_registrar.h" +#include "plugin_registry.h" + +namespace flutter { + +// An instance of a Flutter engine. +// +// In the future, this will be the API surface used for all interactions with +// the engine, rather than having them duplicated on FlutterViewController. +// For now it is only used in the rare where you need a headless Flutter engine. +class FlutterEngine : public PluginRegistry { + public: + // Creates a new engine for running the given project. + explicit FlutterEngine(const DartProject& project); + + virtual ~FlutterEngine(); + + // Prevent copying. + FlutterEngine(FlutterEngine const&) = delete; + FlutterEngine& operator=(FlutterEngine const&) = delete; + + // Starts running the engine. + // + // If the optional entry point is not provided, defaults to main(). + bool Run(const char* entry_point = nullptr); + + // Terminates the running engine. + void ShutDown(); + + // Processes any pending events in the Flutter engine, and returns the + // nanosecond delay until the next scheduled event (or max, if none). + // + // This should be called on every run of the application-level runloop, and + // a wait for native events in the runloop should never be longer than the + // last return value from this function. + std::chrono::nanoseconds ProcessMessages(); + + // flutter::PluginRegistry: + FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( + const std::string& plugin_name) override; + + private: + using UniqueEnginePtr = + std::unique_ptr; + + // Handle for interacting with the C API's engine reference. + UniqueEnginePtr engine_ = + UniqueEnginePtr(nullptr, FlutterDesktopShutDownEngine); + + std::unique_ptr project_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h index 607e01a72f..b5cdee4d4f 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h @@ -33,13 +33,6 @@ class FlutterViewController : public PluginRegistry { int height, const DartProject& project); - // DEPRECATED. Will be removed soon; use the version above. - explicit FlutterViewController(const std::string& icu_data_path, - int width, - int height, - const std::string& assets_path, - const std::vector& arguments); - virtual ~FlutterViewController(); // Prevent copying. @@ -64,6 +57,9 @@ class FlutterViewController : public PluginRegistry { // Handle for interacting with the C API's view controller, if any. FlutterDesktopViewControllerRef controller_ = nullptr; + // |controller_|'s engine. + FlutterDesktopEngineRef engine_ = nullptr; + // The owned FlutterView. std::unique_ptr view_; }; diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc b/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc index b84d9195da..79844b8f8d 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.cc @@ -46,23 +46,6 @@ FlutterDesktopViewControllerRef FlutterDesktopCreateViewController( return nullptr; } -FlutterDesktopViewControllerRef FlutterDesktopCreateViewControllerLegacy( - int initial_width, - int initial_height, - const char* assets_path, - const char* icu_data_path, - const char** arguments, - size_t argument_count) { - if (s_stub_implementation) { - // This stub will be removed shortly, and the current tests don't need the - // arguments, so there's no need to translate them to engine_properties. - FlutterDesktopEngineProperties engine_properties; - return s_stub_implementation->CreateViewController( - initial_width, initial_height, engine_properties); - } - return nullptr; -} - void FlutterDesktopDestroyViewController( FlutterDesktopViewControllerRef controller) { if (s_stub_implementation) { @@ -76,8 +59,13 @@ FlutterDesktopViewRef FlutterDesktopGetView( return reinterpret_cast(1); } -uint64_t FlutterDesktopProcessMessages( +FlutterDesktopEngineRef FlutterDesktopGetEngine( FlutterDesktopViewControllerRef controller) { + // The stub ignores this, so just return an arbitrary non-zero value. + return reinterpret_cast(1); +} + +uint64_t FlutterDesktopProcessMessages(FlutterDesktopEngineRef engine) { if (s_stub_implementation) { return s_stub_implementation->ProcessMessages(); } @@ -107,7 +95,7 @@ bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) { } FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar( - FlutterDesktopViewControllerRef controller, + FlutterDesktopEngineRef engine, const char* plugin_name) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast(1); diff --git a/engine/src/flutter/shell/platform/windows/flutter_project_bundle.cc b/engine/src/flutter/shell/platform/windows/flutter_project_bundle.cc new file mode 100644 index 0000000000..2459311524 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/flutter_project_bundle.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/windows/flutter_project_bundle.h" + +#include +#include + +#include "flutter/shell/platform/common/cpp/path_utils.h" + +namespace flutter { + +FlutterProjectBundle::FlutterProjectBundle( + const FlutterDesktopEngineProperties& properties) + : assets_path_(properties.assets_path), + icu_path_(properties.icu_data_path) { + if (properties.aot_library_path != nullptr) { + aot_library_path_ = std::filesystem::path(properties.aot_library_path); + } + + // Resolve any relative paths. + if (assets_path_.is_relative() || icu_path_.is_relative() || + (!aot_library_path_.empty() && aot_library_path_.is_relative())) { + std::filesystem::path executable_location = GetExecutableDirectory(); + if (executable_location.empty()) { + std::cerr + << "Unable to find executable location to resolve resource paths." + << std::endl; + assets_path_ = std::filesystem::path(); + icu_path_ = std::filesystem::path(); + } else { + assets_path_ = std::filesystem::path(executable_location) / assets_path_; + icu_path_ = std::filesystem::path(executable_location) / icu_path_; + if (!aot_library_path_.empty()) { + aot_library_path_ = + std::filesystem::path(executable_location) / aot_library_path_; + } + } + } + + if (properties.switches_count > 0) { + switches_.insert(switches_.end(), &properties.switches[0], + &properties.switches[properties.switches_count]); + } +} + +bool FlutterProjectBundle::HasValidPaths() { + return !assets_path_.empty() && !icu_path_.empty(); +} + +// Attempts to load AOT data from the given path, which must be absolute and +// non-empty. Logs and returns nullptr on failure. +UniqueAotDataPtr FlutterProjectBundle::LoadAotData() { + if (aot_library_path_.empty()) { + std::cerr + << "Attempted to load AOT data, but no aot_library_path was provided." + << std::endl; + return nullptr; + } + if (!std::filesystem::exists(aot_library_path_)) { + std::cerr << "Can't load AOT data from " << aot_library_path_.u8string() + << "; no such file." << std::endl; + return nullptr; + } + std::string path_string = aot_library_path_.u8string(); + FlutterEngineAOTDataSource source = {}; + source.type = kFlutterEngineAOTDataSourceTypeElfPath; + source.elf_path = path_string.c_str(); + FlutterEngineAOTData data = nullptr; + auto result = FlutterEngineCreateAOTData(&source, &data); + if (result != kSuccess) { + std::cerr << "Failed to load AOT data from: " << path_string << std::endl; + return nullptr; + } + return UniqueAotDataPtr(data); +} + +FlutterProjectBundle::~FlutterProjectBundle() {} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/flutter_project_bundle.h b/engine/src/flutter/shell/platform/windows/flutter_project_bundle.h new file mode 100644 index 0000000000..f8ab57be1e --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/flutter_project_bundle.h @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PROJECT_BUNDLE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PROJECT_BUNDLE_H_ + +#include +#include +#include + +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" + +namespace flutter { + +struct AotDataDeleter { + void operator()(FlutterEngineAOTData aot_data) { + FlutterEngineCollectAOTData(aot_data); + } +}; +using UniqueAotDataPtr = std::unique_ptr<_FlutterEngineAOTData, AotDataDeleter>; + +// The data associated with a Flutter project needed to run it in an engine. +class FlutterProjectBundle { + public: + // Creates a new project bundle from the given properties. + // + // Treats any relative paths as relative to the directory of this executable. + explicit FlutterProjectBundle( + const FlutterDesktopEngineProperties& properties); + + ~FlutterProjectBundle(); + + // Whether or not the bundle is valid. This does not check that the paths + // exist, or contain valid data, just that paths were able to be constructed. + bool HasValidPaths(); + + // Returns the path to the assets directory. + const std::filesystem::path& assets_path() { return assets_path_; } + + // Returns the path to the ICU data file. + const std::filesystem::path& icu_path() { return icu_path_; } + + // Returns any switches that should be passed to the engine. + const std::vector& switches() { return switches_; } + + // Attempts to load AOT data for this bundle. The returned data must be + // retained until any engine instance it is passed to has been shut down. + // + // Logs and returns nullptr on failure. + UniqueAotDataPtr LoadAotData(); + + private: + std::filesystem::path assets_path_; + std::filesystem::path icu_path_; + std::vector switches_; + + // Path to the AOT library file, if any. + std::filesystem::path aot_library_path_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_PROJECT_BUNDLE_H_ diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows.cc b/engine/src/flutter/shell/platform/windows/flutter_windows.cc index 19bf9c97c7..5841c8860d 100644 --- a/engine/src/flutter/shell/platform/windows/flutter_windows.cc +++ b/engine/src/flutter/shell/platform/windows/flutter_windows.cc @@ -19,6 +19,8 @@ #include "flutter/shell/platform/common/cpp/incoming_message_dispatcher.h" #include "flutter/shell/platform/common/cpp/path_utils.h" #include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/windows/flutter_project_bundle.h" +#include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/win32_dpi_utils.h" #include "flutter/shell/platform/windows/win32_flutter_window.h" @@ -29,172 +31,16 @@ static_assert(FLUTTER_ENGINE_VERSION == 1, ""); -// Attempts to load AOT data from the given path, which must be absolute and -// non-empty. Logs and returns nullptr on failure. -UniqueAotDataPtr LoadAotData(std::filesystem::path aot_data_path) { - if (aot_data_path.empty()) { - std::cerr - << "Attempted to load AOT data, but no aot_library_path was provided." - << std::endl; - return nullptr; - } - if (!std::filesystem::exists(aot_data_path)) { - std::cerr << "Can't load AOT data from " << aot_data_path.u8string() - << "; no such file." << std::endl; - return nullptr; - } - std::string path_string = aot_data_path.u8string(); - FlutterEngineAOTDataSource source = {}; - source.type = kFlutterEngineAOTDataSourceTypeElfPath; - source.elf_path = path_string.c_str(); - FlutterEngineAOTData data = nullptr; - auto result = FlutterEngineCreateAOTData(&source, &data); - if (result != kSuccess) { - std::cerr << "Failed to load AOT data from: " << path_string << std::endl; - return nullptr; - } - return UniqueAotDataPtr(data); +// Returns the engine corresponding to the given opaque API handle. +static flutter::FlutterWindowsEngine* EngineFromHandle( + FlutterDesktopEngineRef ref) { + return reinterpret_cast(ref); } -// Spins up an instance of the Flutter Engine. -// -// This function launches the Flutter Engine in a background thread, supplying -// the necessary callbacks for rendering within a win32window (if one is -// provided). -// -// Returns the state object for the engine, or null on failure to start the -// engine. -static std::unique_ptr RunFlutterEngine( - flutter::FlutterWindowsView* view, - const FlutterDesktopEngineProperties& engine_properties) { - auto state = std::make_unique(); - - // FlutterProjectArgs is expecting a full argv, so when processing it for - // flags the first item is treated as the executable and ignored. Add a dummy - // value so that all provided arguments are used. - std::vector argv = {"placeholder"}; - if (engine_properties.switches_count > 0) { - argv.insert(argv.end(), &engine_properties.switches[0], - &engine_properties.switches[engine_properties.switches_count]); - } - - view->CreateRenderSurface(); - - // Provide the necessary callbacks for rendering within a win32 child window. - FlutterRendererConfig config = {}; - config.type = kOpenGL; - config.open_gl.struct_size = sizeof(config.open_gl); - config.open_gl.make_current = [](void* user_data) -> bool { - auto host = static_cast(user_data); - return host->MakeCurrent(); - }; - config.open_gl.clear_current = [](void* user_data) -> bool { - auto host = static_cast(user_data); - return host->ClearContext(); - }; - config.open_gl.present = [](void* user_data) -> bool { - auto host = static_cast(user_data); - return host->SwapBuffers(); - }; - config.open_gl.fbo_callback = [](void* user_data) -> uint32_t { return 0; }; - config.open_gl.gl_proc_resolver = [](void* user_data, - const char* what) -> void* { - return reinterpret_cast(eglGetProcAddress(what)); - }; - config.open_gl.make_resource_current = [](void* user_data) -> bool { - auto host = static_cast(user_data); - return host->MakeResourceCurrent(); - }; - - // Configure task runner interop. - auto state_ptr = state.get(); - state->task_runner = std::make_unique( - GetCurrentThreadId(), [state_ptr](const auto* task) { - if (FlutterEngineRunTask(state_ptr->engine, task) != kSuccess) { - std::cerr << "Could not post an engine task." << std::endl; - } - }); - FlutterTaskRunnerDescription platform_task_runner = {}; - platform_task_runner.struct_size = sizeof(FlutterTaskRunnerDescription); - platform_task_runner.user_data = state->task_runner.get(); - platform_task_runner.runs_task_on_current_thread_callback = - [](void* user_data) -> bool { - return reinterpret_cast(user_data) - ->RunsTasksOnCurrentThread(); - }; - platform_task_runner.post_task_callback = [](FlutterTask task, - uint64_t target_time_nanos, - void* user_data) -> void { - reinterpret_cast(user_data)->PostTask( - task, target_time_nanos); - }; - - FlutterCustomTaskRunners custom_task_runners = {}; - custom_task_runners.struct_size = sizeof(FlutterCustomTaskRunners); - custom_task_runners.platform_task_runner = &platform_task_runner; - - std::filesystem::path assets_path(engine_properties.assets_path); - std::filesystem::path icu_path(engine_properties.icu_data_path); - std::filesystem::path aot_library_path = - engine_properties.aot_library_path == nullptr - ? std::filesystem::path() - : std::filesystem::path(engine_properties.aot_library_path); - if (assets_path.is_relative() || icu_path.is_relative() || - (!aot_library_path.empty() && aot_library_path.is_relative())) { - // Treat relative paths as relative to the directory of this executable. - std::filesystem::path executable_location = - flutter::GetExecutableDirectory(); - if (executable_location.empty()) { - std::cerr - << "Unable to find executable location to resolve resource paths." - << std::endl; - return nullptr; - } - assets_path = std::filesystem::path(executable_location) / assets_path; - icu_path = std::filesystem::path(executable_location) / icu_path; - if (!aot_library_path.empty()) { - aot_library_path = - std::filesystem::path(executable_location) / aot_library_path; - } - } - std::string assets_path_string = assets_path.u8string(); - std::string icu_path_string = icu_path.u8string(); - - if (FlutterEngineRunsAOTCompiledDartCode()) { - state->aot_data = LoadAotData(aot_library_path); - if (!state->aot_data) { - std::cerr << "Unable to start engine without AOT data." << std::endl; - return nullptr; - } - } - - FlutterProjectArgs args = {}; - args.struct_size = sizeof(FlutterProjectArgs); - args.assets_path = assets_path_string.c_str(); - args.icu_data_path = icu_path_string.c_str(); - args.command_line_argc = static_cast(argv.size()); - args.command_line_argv = &argv[0]; - args.platform_message_callback = - [](const FlutterPlatformMessage* engine_message, - void* user_data) -> void { - auto window = reinterpret_cast(user_data); - return window->HandlePlatformMessage(engine_message); - }; - args.custom_task_runners = &custom_task_runners; - if (state->aot_data) { - args.aot_data = state->aot_data.get(); - } - - FLUTTER_API_SYMBOL(FlutterEngine) engine = nullptr; - auto result = - FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, &args, view, &engine); - if (result != kSuccess || engine == nullptr) { - std::cerr << "Failed to start Flutter engine: error " << result - << std::endl; - return nullptr; - } - state->engine = engine; - return state; +// Returns opaque API handle for the given engine instance. +static FlutterDesktopEngineRef HandleForEngine( + flutter::FlutterWindowsEngine* engine) { + return reinterpret_cast(engine); } FlutterDesktopViewControllerRef FlutterDesktopCreateViewController( @@ -204,59 +50,48 @@ FlutterDesktopViewControllerRef FlutterDesktopCreateViewController( std::unique_ptr window_wrapper = std::make_unique(width, height); - FlutterDesktopViewControllerRef state = - flutter::FlutterWindowsView::CreateFlutterWindowsView( - std::move(window_wrapper)); + auto state = std::make_unique(); + state->view = + std::make_unique(std::move(window_wrapper)); + state->view->CreateRenderSurface(); + state->view_wrapper = std::make_unique(); + state->view_wrapper->view = state->view.get(); - auto engine_state = RunFlutterEngine(state->view.get(), engine_properties); - - if (!engine_state) { + flutter::FlutterProjectBundle project(engine_properties); + auto engine = std::make_unique(project); + if (!engine) { return nullptr; } - state->view->SetState(engine_state->engine); - state->engine_state = std::move(engine_state); - return state; + state->view->SetEngine(std::move(engine)); + if (!state->view->GetEngine()->RunWithEntrypoint( + engine_properties.entry_point)) { + return nullptr; + } + return state.release(); } -FlutterDesktopViewControllerRef FlutterDesktopCreateViewControllerLegacy( - int initial_width, - int initial_height, - const char* assets_path, - const char* icu_data_path, - const char** arguments, - size_t argument_count) { - std::filesystem::path assets_path_fs = std::filesystem::u8path(assets_path); - std::filesystem::path icu_data_path_fs = - std::filesystem::u8path(icu_data_path); - FlutterDesktopEngineProperties engine_properties = {}; - engine_properties.assets_path = assets_path_fs.c_str(); - engine_properties.icu_data_path = icu_data_path_fs.c_str(); - engine_properties.switches = arguments; - engine_properties.switches_count = argument_count; - - return FlutterDesktopCreateViewController(initial_width, initial_height, - engine_properties); -} - -uint64_t FlutterDesktopProcessMessages( - FlutterDesktopViewControllerRef controller) { - return controller->engine_state->task_runner->ProcessTasks().count(); +uint64_t FlutterDesktopProcessMessages(FlutterDesktopEngineRef engine) { + return EngineFromHandle(engine)->task_runner()->ProcessTasks().count(); } void FlutterDesktopDestroyViewController( FlutterDesktopViewControllerRef controller) { - FlutterEngineShutdown(controller->engine_state->engine); delete controller; } +FlutterDesktopEngineRef FlutterDesktopGetEngine( + FlutterDesktopViewControllerRef controller) { + return HandleForEngine(controller->view->GetEngine()); +} + FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar( - FlutterDesktopViewControllerRef controller, + FlutterDesktopEngineRef engine, const char* plugin_name) { // Currently, one registrar acts as the registrar for all plugins, so the // name is ignored. It is part of the API to reduce churn in the future when // aligning more closely with the Flutter registrar system. - return controller->view->GetRegistrar(); + return EngineFromHandle(engine)->GetRegistrar(); } FlutterDesktopViewRef FlutterDesktopGetView( @@ -289,15 +124,20 @@ void FlutterDesktopResyncOutputStreams() { FlutterDesktopEngineRef FlutterDesktopRunEngine( const FlutterDesktopEngineProperties& engine_properties) { - auto engine = RunFlutterEngine(nullptr, engine_properties); - return engine.release(); + flutter::FlutterProjectBundle project(engine_properties); + auto engine = std::make_unique(project); + if (!engine->RunWithEntrypoint(engine_properties.entry_point)) { + return nullptr; + } + return HandleForEngine(engine.release()); } bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) { std::cout << "Shutting down flutter engine process." << std::endl; - auto result = FlutterEngineShutdown(engine_ref->engine); - delete engine_ref; - return (result == kSuccess); + flutter::FlutterWindowsEngine* engine = EngineFromHandle(engine_ref); + bool result = engine->Stop(); + delete engine; + return result; } void FlutterDesktopRegistrarEnableInputBlocking( @@ -319,7 +159,7 @@ void FlutterDesktopRegistrarSetDestructionHandler( FlutterDesktopViewRef FlutterDesktopRegistrarGetView( FlutterDesktopPluginRegistrarRef registrar) { - return registrar->view; + return registrar->view.get(); } bool FlutterDesktopMessengerSendWithReply(FlutterDesktopMessengerRef messenger, diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows_engine.cc b/engine/src/flutter/shell/platform/windows/flutter_windows_engine.cc new file mode 100644 index 0000000000..957c9432d8 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/flutter_windows_engine.cc @@ -0,0 +1,216 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/shell/platform/windows/flutter_windows_engine.h" + +#include +#include + +#include "flutter/shell/platform/common/cpp/path_utils.h" +#include "flutter/shell/platform/windows/flutter_windows_view.h" + +namespace flutter { + +namespace { + +// Creates and returns a FlutterRendererConfig that renders to the view (if any) +// of a FlutterWindowsEngine, which should be the user_data received by the +// render callbacks. +FlutterRendererConfig GetRendererConfig() { + FlutterRendererConfig config = {}; + config.type = kOpenGL; + config.open_gl.struct_size = sizeof(config.open_gl); + config.open_gl.make_current = [](void* user_data) -> bool { + auto host = static_cast(user_data); + if (!host->view()) { + return false; + } + return host->view()->MakeCurrent(); + }; + config.open_gl.clear_current = [](void* user_data) -> bool { + auto host = static_cast(user_data); + if (!host->view()) { + return false; + } + return host->view()->ClearContext(); + }; + config.open_gl.present = [](void* user_data) -> bool { + auto host = static_cast(user_data); + if (!host->view()) { + return false; + } + return host->view()->SwapBuffers(); + }; + config.open_gl.fbo_callback = [](void* user_data) -> uint32_t { return 0; }; + config.open_gl.gl_proc_resolver = [](void* user_data, + const char* what) -> void* { + return reinterpret_cast(eglGetProcAddress(what)); + }; + config.open_gl.make_resource_current = [](void* user_data) -> bool { + auto host = static_cast(user_data); + if (!host->view()) { + return false; + } + return host->view()->MakeResourceCurrent(); + }; + return config; +} + +// Converts a FlutterPlatformMessage to an equivalent FlutterDesktopMessage. +static FlutterDesktopMessage ConvertToDesktopMessage( + const FlutterPlatformMessage& engine_message) { + FlutterDesktopMessage message = {}; + message.struct_size = sizeof(message); + message.channel = engine_message.channel; + message.message = engine_message.message; + message.message_size = engine_message.message_size; + message.response_handle = engine_message.response_handle; + return message; +} + +} // namespace + +FlutterWindowsEngine::FlutterWindowsEngine(const FlutterProjectBundle& project) + : project_(std::make_unique(project)) { + task_runner_ = std::make_unique( + GetCurrentThreadId(), [this](const auto* task) { + if (!engine_) { + std::cerr << "Cannot post an engine task when engine is not running." + << std::endl; + return; + } + if (FlutterEngineRunTask(engine_, task) != kSuccess) { + std::cerr << "Failed to post an engine task." << std::endl; + } + }); + + // Set up the structure of the state/handle objects; engine and view paramater + // will be filled in late. + auto messenger = std::make_unique(); + message_dispatcher_ = + std::make_unique(messenger.get()); + messenger->dispatcher = message_dispatcher_.get(); + + plugin_registrar_ = std::make_unique(); + plugin_registrar_->messenger = std::move(messenger); + plugin_registrar_->view = std::make_unique(); +} + +FlutterWindowsEngine::~FlutterWindowsEngine() { + Stop(); +} + +bool FlutterWindowsEngine::RunWithEntrypoint(const char* entrypoint) { + if (!project_->HasValidPaths()) { + std::cerr << "Missing or unresolvable paths to assets." << std::endl; + return false; + } + std::string assets_path_string = project_->assets_path().u8string(); + std::string icu_path_string = project_->icu_path().u8string(); + if (FlutterEngineRunsAOTCompiledDartCode()) { + aot_data_ = project_->LoadAotData(); + if (!aot_data_) { + std::cerr << "Unable to start engine without AOT data." << std::endl; + return false; + } + } + + // FlutterProjectArgs is expecting a full argv, so when processing it for + // flags the first item is treated as the executable and ignored. Add a dummy + // value so that all provided arguments are used. + std::vector argv = {"placeholder"}; + std::transform( + project_->switches().begin(), project_->switches().end(), + std::back_inserter(argv), + [](const std::string& arg) -> const char* { return arg.c_str(); }); + + // Configure task runners. + FlutterTaskRunnerDescription platform_task_runner = {}; + platform_task_runner.struct_size = sizeof(FlutterTaskRunnerDescription); + platform_task_runner.user_data = task_runner_.get(); + platform_task_runner.runs_task_on_current_thread_callback = + [](void* user_data) -> bool { + return static_cast(user_data)->RunsTasksOnCurrentThread(); + }; + platform_task_runner.post_task_callback = [](FlutterTask task, + uint64_t target_time_nanos, + void* user_data) -> void { + static_cast(user_data)->PostTask(task, target_time_nanos); + }; + FlutterCustomTaskRunners custom_task_runners = {}; + custom_task_runners.struct_size = sizeof(FlutterCustomTaskRunners); + custom_task_runners.platform_task_runner = &platform_task_runner; + + FlutterProjectArgs args = {}; + args.struct_size = sizeof(FlutterProjectArgs); + args.assets_path = assets_path_string.c_str(); + args.icu_data_path = icu_path_string.c_str(); + args.command_line_argc = static_cast(argv.size()); + args.command_line_argv = argv.size() > 0 ? argv.data() : nullptr; + args.platform_message_callback = + [](const FlutterPlatformMessage* engine_message, + void* user_data) -> void { + auto host = static_cast(user_data); + return host->HandlePlatformMessage(engine_message); + }; + args.custom_task_runners = &custom_task_runners; + if (aot_data_) { + args.aot_data = aot_data_.get(); + } + if (entrypoint) { + args.custom_dart_entrypoint = entrypoint; + } + + FlutterRendererConfig renderer_config = GetRendererConfig(); + + auto result = FlutterEngineRun(FLUTTER_ENGINE_VERSION, &renderer_config, + &args, this, &engine_); + if (result != kSuccess || engine_ == nullptr) { + std::cerr << "Failed to start Flutter engine: error " << result + << std::endl; + return false; + } + + plugin_registrar_->messenger->engine = engine_; + return true; +} + +bool FlutterWindowsEngine::Stop() { + if (engine_) { + if (plugin_registrar_ && plugin_registrar_->destruction_handler) { + plugin_registrar_->destruction_handler(plugin_registrar_.get()); + } + FlutterEngineResult result = FlutterEngineShutdown(engine_); + engine_ = nullptr; + return (result == kSuccess); + } + return false; +} + +void FlutterWindowsEngine::SetView(FlutterWindowsView* view) { + view_ = view; + plugin_registrar_->view->view = view; +} + +// Returns the currently configured Plugin Registrar. +FlutterDesktopPluginRegistrarRef FlutterWindowsEngine::GetRegistrar() { + return plugin_registrar_.get(); +} + +void FlutterWindowsEngine::HandlePlatformMessage( + const FlutterPlatformMessage* engine_message) { + if (engine_message->struct_size != sizeof(FlutterPlatformMessage)) { + std::cerr << "Invalid message size received. Expected: " + << sizeof(FlutterPlatformMessage) << " but received " + << engine_message->struct_size << std::endl; + return; + } + + auto message = ConvertToDesktopMessage(*engine_message); + + message_dispatcher_->HandleMessage( + message, [this] {}, [this] {}); +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows_engine.h b/engine/src/flutter/shell/platform/windows/flutter_windows_engine.h new file mode 100644 index 0000000000..3d562b1283 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/flutter_windows_engine.h @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_ + +#include +#include + +#include "flutter/shell/platform/common/cpp/incoming_message_dispatcher.h" +#include "flutter/shell/platform/windows/flutter_project_bundle.h" +#include "flutter/shell/platform/windows/public/flutter_windows.h" +#include "flutter/shell/platform/windows/win32_task_runner.h" +#include "flutter/shell/platform/windows/window_state.h" + +namespace flutter { + +class FlutterWindowsView; + +// Manages state associated with the underlying FlutterEngine that isn't +// related to its display. +// +// In most cases this will be associated with a FlutterView, but if not will +// run in headless mode. +class FlutterWindowsEngine { + public: + // Creates a new Flutter engine object configured to run |project|. + explicit FlutterWindowsEngine(const FlutterProjectBundle& project); + + virtual ~FlutterWindowsEngine(); + + // Prevent copying. + FlutterWindowsEngine(FlutterWindowsEngine const&) = delete; + FlutterWindowsEngine& operator=(FlutterWindowsEngine const&) = delete; + + // Starts running the engine with the given entrypoint. If null, defaults to + // main(). + // + // Returns false if the engine couldn't be started. + bool RunWithEntrypoint(const char* entrypoint); + + // Stops the engine. This invalidates the pointer returned by engine(). + // + // Returns false if stopping the engine fails, or if it was not running. + bool Stop(); + + // Sets the view that is displaying this engine's content. + void SetView(FlutterWindowsView* view); + + // The view displaying this engine's content, if any. This will be null for + // headless engines. + FlutterWindowsView* view() { return view_; } + + // Returns the currently configured Plugin Registrar. + FlutterDesktopPluginRegistrarRef GetRegistrar(); + + FLUTTER_API_SYMBOL(FlutterEngine) engine() { return engine_; } + + Win32TaskRunner* task_runner() { return task_runner_.get(); } + + // Callback passed to Flutter engine for notifying window of platform + // messages. + void HandlePlatformMessage(const FlutterPlatformMessage*); + + private: + // The handle to the embedder.h engine instance. + FLUTTER_API_SYMBOL(FlutterEngine) engine_ = nullptr; + + std::unique_ptr project_; + + // AOT data, if any. + UniqueAotDataPtr aot_data_; + + // The view displaying the content running in this engine, if any. + FlutterWindowsView* view_ = nullptr; + + // Task runner for tasks posted from the engine. + std::unique_ptr task_runner_; + + // Message dispatch manager for messages from engine_. + std::unique_ptr message_dispatcher_; + + // The plugin registrar handle given to API clients. + std::unique_ptr plugin_registrar_; +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_ diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows_view.cc b/engine/src/flutter/shell/platform/windows/flutter_windows_view.cc index db650a4e0a..9c463c367b 100644 --- a/engine/src/flutter/shell/platform/windows/flutter_windows_view.cc +++ b/engine/src/flutter/shell/platform/windows/flutter_windows_view.cc @@ -1,63 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + #include "flutter/shell/platform/windows/flutter_windows_view.h" #include namespace flutter { -FlutterWindowsView::FlutterWindowsView() { +FlutterWindowsView::FlutterWindowsView( + std::unique_ptr window_binding) { surface_manager_ = std::make_unique(); + + // Take the binding handler, and give it a pointer back to self. + binding_handler_ = std::move(window_binding); + binding_handler_->SetView(this); + + render_target_ = std::make_unique( + binding_handler_->GetRenderTarget()); } FlutterWindowsView::~FlutterWindowsView() { DestroyRenderSurface(); - if (plugin_registrar_ && plugin_registrar_->destruction_handler) { - plugin_registrar_->destruction_handler(plugin_registrar_.get()); - } } -FlutterDesktopViewControllerRef FlutterWindowsView::CreateFlutterWindowsView( - std::unique_ptr windowbinding) { - auto state = std::make_unique(); - state->view = std::make_unique(); +void FlutterWindowsView::SetEngine( + std::unique_ptr engine) { + engine_ = std::move(engine); - // FlutterWindowsView instance owns windowbinding - state->view->binding_handler_ = std::move(windowbinding); - - // a window wrapper for the state block, distinct from the - // window_wrapper handed to plugin_registrar. - state->view_wrapper = std::make_unique(); - - // Give the binding handler a pointer back to this | FlutterWindowsView | - state->view->binding_handler_->SetView(state->view.get()); - - // opaque pointer to FlutterWindowsView - state->view_wrapper->view = state->view.get(); - - state->view->render_target_ = std::make_unique( - state->view->binding_handler_->GetRenderTarget()); - - return state.release(); -} - -void FlutterWindowsView::SetState(FLUTTER_API_SYMBOL(FlutterEngine) eng) { - engine_ = eng; - - auto messenger = std::make_unique(); - message_dispatcher_ = - std::make_unique(messenger.get()); - messenger->engine = engine_; - messenger->dispatcher = message_dispatcher_.get(); - - window_wrapper_ = std::make_unique(); - window_wrapper_->view = this; - plugin_registrar_ = std::make_unique(); - plugin_registrar_->messenger = std::move(messenger); - plugin_registrar_->view = window_wrapper_.get(); + engine_->SetView(this); internal_plugin_registrar_ = - std::make_unique(plugin_registrar_.get()); + std::make_unique(engine_->GetRegistrar()); - // Set up the keyboard handlers. + // Set up the system channel handlers. auto internal_plugin_messenger = internal_plugin_registrar_->messenger(); keyboard_hook_handlers_.push_back( std::make_unique(internal_plugin_messenger)); @@ -74,39 +50,6 @@ void FlutterWindowsView::SetState(FLUTTER_API_SYMBOL(FlutterEngine) eng) { binding_handler_->GetDpiScale()); } -FlutterDesktopPluginRegistrarRef FlutterWindowsView::GetRegistrar() { - return plugin_registrar_.get(); -} - -// Converts a FlutterPlatformMessage to an equivalent FlutterDesktopMessage. -static FlutterDesktopMessage ConvertToDesktopMessage( - const FlutterPlatformMessage& engine_message) { - FlutterDesktopMessage message = {}; - message.struct_size = sizeof(message); - message.channel = engine_message.channel; - message.message = engine_message.message; - message.message_size = engine_message.message_size; - message.response_handle = engine_message.response_handle; - return message; -} - -// The Flutter Engine calls out to this function when new platform messages -// are available. -void FlutterWindowsView::HandlePlatformMessage( - const FlutterPlatformMessage* engine_message) { - if (engine_message->struct_size != sizeof(FlutterPlatformMessage)) { - std::cerr << "Invalid message size received. Expected: " - << sizeof(FlutterPlatformMessage) << " but received " - << engine_message->struct_size << std::endl; - return; - } - - auto message = ConvertToDesktopMessage(*engine_message); - - message_dispatcher_->HandleMessage( - message, [this] {}, [this] {}); -} - void FlutterWindowsView::OnWindowSizeChanged(size_t width, size_t height) const { SendWindowMetrics(width, height, binding_handler_->GetDpiScale()); @@ -162,17 +105,17 @@ void FlutterWindowsView::OnScroll(double x, } void FlutterWindowsView::OnFontChange() { - if (engine_ == nullptr) { + if (engine_->engine() == nullptr) { return; } - FlutterEngineReloadSystemFonts(engine_); + FlutterEngineReloadSystemFonts(engine_->engine()); } // Sends new size information to FlutterEngine. void FlutterWindowsView::SendWindowMetrics(size_t width, size_t height, double dpiScale) const { - if (engine_ == nullptr) { + if (engine_->engine() == nullptr) { return; } @@ -181,7 +124,7 @@ void FlutterWindowsView::SendWindowMetrics(size_t width, event.width = width; event.height = height; event.pixel_ratio = dpiScale; - auto result = FlutterEngineSendWindowMetricsEvent(engine_, &event); + auto result = FlutterEngineSendWindowMetricsEvent(engine_->engine(), &event); } // Set's |event_data|'s phase to either kMove or kHover depending on the current @@ -293,7 +236,7 @@ void FlutterWindowsView::SendPointerEventWithData( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); - FlutterEngineSendPointerEvent(engine_, &event, 1); + FlutterEngineSendPointerEvent(engine_->engine(), &event, 1); if (event_data.phase == FlutterPointerPhase::kAdd) { SetMouseFlutterStateAdded(true); @@ -333,4 +276,8 @@ WindowsRenderTarget* FlutterWindowsView::GetRenderTarget() { return render_target_.get(); } +FlutterWindowsEngine* FlutterWindowsView::GetEngine() { + return engine_.get(); +} + } // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows_view.h b/engine/src/flutter/shell/platform/windows/flutter_windows_view.h index f19e9f97ac..13ff056f67 100644 --- a/engine/src/flutter/shell/platform/windows/flutter_windows_view.h +++ b/engine/src/flutter/shell/platform/windows/flutter_windows_view.h @@ -7,14 +7,15 @@ #include +#include #include #include #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h" -#include "flutter/shell/platform/common/cpp/incoming_message_dispatcher.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/angle_surface_manager.h" #include "flutter/shell/platform/windows/cursor_handler.h" +#include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/key_event_handler.h" #include "flutter/shell/platform/windows/keyboard_hook_handler.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" @@ -30,26 +31,18 @@ namespace flutter { // view that works with win32 hwnds and Windows::UI::Composition visuals. class FlutterWindowsView : public WindowBindingHandlerDelegate { public: - FlutterWindowsView(); + // Creates a FlutterWindowsView with the given implementator of + // WindowBindingHandler. + // + // In order for object to render Flutter content the SetEngine method must be + // called with a valid FlutterWindowsEngine instance. + FlutterWindowsView(std::unique_ptr window_binding); ~FlutterWindowsView(); - // Factory for creating FlutterWindowsView requiring an implementator of - // WindowBindingHandler. In order for object to render Flutter content - // the SetState method must be called with a valid FlutterEngine instance. - static FlutterDesktopViewControllerRef CreateFlutterWindowsView( - std::unique_ptr window_binding); - // Configures the window instance with an instance of a running Flutter // engine. - void SetState(FLUTTER_API_SYMBOL(FlutterEngine) state); - - // Returns the currently configured Plugin Registrar. - FlutterDesktopPluginRegistrarRef GetRegistrar(); - - // Callback passed to Flutter engine for notifying window of platform - // messages. - void HandlePlatformMessage(const FlutterPlatformMessage*); + void SetEngine(std::unique_ptr engine); // Creates rendering surface for Flutter engine to draw into. // Should be called before calling FlutterEngineRun using this view. @@ -61,6 +54,9 @@ class FlutterWindowsView : public WindowBindingHandlerDelegate { // Return the currently configured WindowsRenderTarget. WindowsRenderTarget* GetRenderTarget(); + // Returns the engine backing this view. + FlutterWindowsEngine* GetEngine(); + // Callbacks for clearing context, settings context and swapping buffers. bool ClearContext(); bool MakeCurrent(); @@ -189,21 +185,12 @@ class FlutterWindowsView : public WindowBindingHandlerDelegate { // surfaces. Surface creation functionality requires a valid render_target. std::unique_ptr surface_manager_; - // The handle to the Flutter engine instance. - FLUTTER_API_SYMBOL(FlutterEngine) engine_ = nullptr; + // The engine associated with this view. + std::unique_ptr engine_; // Keeps track of mouse state in relation to the window. MouseState mouse_state_; - // The window handle given to API clients. - std::unique_ptr window_wrapper_; - - // The plugin registrar handle given to API clients. - std::unique_ptr plugin_registrar_; - - // Message dispatch manager for messages from the Flutter engine. - std::unique_ptr message_dispatcher_; - // The plugin registrar managing internal plugins. std::unique_ptr internal_plugin_registrar_; diff --git a/engine/src/flutter/shell/platform/windows/public/flutter_windows.h b/engine/src/flutter/shell/platform/windows/public/flutter_windows.h index 5915da7b32..15d6b48616 100644 --- a/engine/src/flutter/shell/platform/windows/public/flutter_windows.h +++ b/engine/src/flutter/shell/platform/windows/public/flutter_windows.h @@ -25,7 +25,8 @@ typedef struct FlutterDesktopViewControllerState* typedef struct FlutterDesktopView* FlutterDesktopViewRef; // Opaque reference to a Flutter engine instance. -typedef struct FlutterDesktopEngineState* FlutterDesktopEngineRef; +struct FlutterDesktopEngine; +typedef struct FlutterDesktopEngine* FlutterDesktopEngineRef; // Properties for configuring a Flutter engine instance. typedef struct { @@ -45,6 +46,9 @@ typedef struct { // it will be ignored in that case. const wchar_t* aot_library_path; + // The entry point to use in the Dart project. If null, defaults to main(). + const char* entry_point; + // The switches to pass to the Flutter engine. // // See: https://github.com/flutter/engine/blob/master/shell/common/switches.h @@ -67,15 +71,6 @@ FlutterDesktopCreateViewController( int height, const FlutterDesktopEngineProperties& engine_properties); -// DEPRECATED. Will be removed soon; switch to the version above. -FLUTTER_EXPORT FlutterDesktopViewControllerRef -FlutterDesktopCreateViewControllerLegacy(int initial_width, - int initial_height, - const char* assets_path, - const char* icu_data_path, - const char** arguments, - size_t argument_count); - // Shuts down the engine instance associated with |controller|, and cleans up // associated state. // @@ -83,11 +78,17 @@ FlutterDesktopCreateViewControllerLegacy(int initial_width, FLUTTER_EXPORT void FlutterDesktopDestroyViewController( FlutterDesktopViewControllerRef controller); +// Returns the handle for the engine running in FlutterDesktopViewControllerRef. +// +// Its lifetime is the same as the |controller|'s. +FLUTTER_EXPORT FlutterDesktopEngineRef +FlutterDesktopGetEngine(FlutterDesktopViewControllerRef controller); + // Returns the plugin registrar handle for the plugin with the given name. // // The name must be unique across the application. FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef -FlutterDesktopGetPluginRegistrar(FlutterDesktopViewControllerRef controller, +FlutterDesktopGetPluginRegistrar(FlutterDesktopEngineRef engine, const char* plugin_name); // Returns the view managed by the given controller. @@ -95,13 +96,13 @@ FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopGetView(FlutterDesktopViewControllerRef controller); // Processes any pending events in the Flutter engine, and returns the -// number of nanoseconds until the next scheduled event (or max, if none). +// number of nanoseconds until the next scheduled event (or max, if none). // // This should be called on every run of the application-level runloop, and // a wait for native events in the runloop should never be longer than the // last return value from this function. FLUTTER_EXPORT uint64_t -FlutterDesktopProcessMessages(FlutterDesktopViewControllerRef controller); +FlutterDesktopProcessMessages(FlutterDesktopEngineRef engine); // Return backing HWND for manipulation in host application. FLUTTER_EXPORT HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view); @@ -127,9 +128,9 @@ FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopRunEngine( const FlutterDesktopEngineProperties& engine_properties); // Shuts down the given engine instance. Returns true if the shutdown was -// successful. |engine_ref| is no longer valid after this call. +// successful. |engine| is no longer valid after this call. FLUTTER_EXPORT bool FlutterDesktopShutDownEngine( - FlutterDesktopEngineRef engine_ref); + FlutterDesktopEngineRef engine); // Returns the view associated with this registrar's engine instance // This is a Windows-specific extension to flutter_plugin_registrar.h. diff --git a/engine/src/flutter/shell/platform/windows/window_state.h b/engine/src/flutter/shell/platform/windows/window_state.h index d1eceb866f..5807905109 100644 --- a/engine/src/flutter/shell/platform/windows/window_state.h +++ b/engine/src/flutter/shell/platform/windows/window_state.h @@ -8,25 +8,18 @@ #include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h" #include "flutter/shell/platform/common/cpp/incoming_message_dispatcher.h" #include "flutter/shell/platform/embedder/embedder.h" -#include "flutter/shell/platform/windows/key_event_handler.h" -#include "flutter/shell/platform/windows/keyboard_hook_handler.h" -#include "flutter/shell/platform/windows/text_input_plugin.h" -#include "flutter/shell/platform/windows/win32_platform_handler.h" -#include "flutter/shell/platform/windows/win32_task_runner.h" namespace flutter { +struct FlutterWindowsEngine; struct FlutterWindowsView; -} +} // namespace flutter // Struct for storing state within an instance of the windows native (HWND or // CoreWindow) Window. struct FlutterDesktopViewControllerState { - // The view that owns this state object. + // The view that backs this state object. std::unique_ptr view; - // The state associate with the engine backing the view. - std::unique_ptr engine_state; - // The window handle given to API clients. std::unique_ptr view_wrapper; }; @@ -36,27 +29,7 @@ struct FlutterDesktopViewControllerState { // to all of the controller-based functionality. struct FlutterDesktopView { // The view that (indirectly) owns this state object. - flutter::FlutterWindowsView* view; -}; - -struct AotDataDeleter { - void operator()(FlutterEngineAOTData aot_data) { - FlutterEngineCollectAOTData(aot_data); - } -}; - -using UniqueAotDataPtr = std::unique_ptr<_FlutterEngineAOTData, AotDataDeleter>; - -// Struct for storing state of a Flutter engine instance. -struct FlutterDesktopEngineState { - // The handle to the Flutter engine instance. - FLUTTER_API_SYMBOL(FlutterEngine) engine; - - // Task runner for tasks posted from the engine. - std::unique_ptr task_runner; - - // AOT data, if any. - UniqueAotDataPtr aot_data; + flutter::FlutterWindowsView* view = nullptr; }; // State associated with the plugin registrar. @@ -65,7 +38,7 @@ struct FlutterDesktopPluginRegistrar { std::unique_ptr messenger; // The handle for the view associated with this registrar. - FlutterDesktopView* view; + std::unique_ptr view; // Callback to be called on registrar destruction. FlutterDesktopOnRegistrarDestroyed destruction_handler;