From be5bc34af10d78833637699bda269faf8e259501 Mon Sep 17 00:00:00 2001 From: stuartmorgan Date: Wed, 16 Oct 2019 21:30:06 -0700 Subject: [PATCH] Add a task runner for the Win32 embedding (flutter/engine#13043) Adds a task runner, and exposes API to allow application-level runloops to know when they need to next call the API to process engine events. Internally, sends null events to wake up the app runloop when new events are scheduled to ensure the wait time is updated accordingly. Fixes #36420 --- .../ci/licenses_golden/licenses_flutter | 2 + .../flutter/shell/platform/windows/BUILD.gn | 2 + .../client_wrapper/flutter_view_controller.cc | 4 +- .../include/flutter/flutter_view_controller.h | 11 +- .../testing/stub_flutter_windows_api.cc | 4 +- .../testing/stub_flutter_windows_api.h | 2 +- .../shell/platform/windows/flutter_windows.cc | 83 +++++++++------ .../platform/windows/public/flutter_windows.h | 11 +- .../platform/windows/win32_flutter_window.cc | 3 - .../platform/windows/win32_task_runner.cc | 100 ++++++++++++++++++ .../platform/windows/win32_task_runner.h | 70 ++++++++++++ .../shell/platform/windows/window_state.h | 10 +- 12 files changed, 256 insertions(+), 46 deletions(-) create mode 100644 engine/src/flutter/shell/platform/windows/win32_task_runner.cc create mode 100644 engine/src/flutter/shell/platform/windows/win32_task_runner.h diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 8eb1d22d1a..8c7ee25b05 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1039,6 +1039,8 @@ FILE: ../../../flutter/shell/platform/windows/win32_dpi_helper.cc FILE: ../../../flutter/shell/platform/windows/win32_dpi_helper.h FILE: ../../../flutter/shell/platform/windows/win32_flutter_window.cc FILE: ../../../flutter/shell/platform/windows/win32_flutter_window.h +FILE: ../../../flutter/shell/platform/windows/win32_task_runner.cc +FILE: ../../../flutter/shell/platform/windows/win32_task_runner.h FILE: ../../../flutter/shell/platform/windows/win32_window.cc FILE: ../../../flutter/shell/platform/windows/win32_window.h FILE: ../../../flutter/shell/platform/windows/win32_window_unittests.cc diff --git a/engine/src/flutter/shell/platform/windows/BUILD.gn b/engine/src/flutter/shell/platform/windows/BUILD.gn index cd496949ea..36da0da253 100644 --- a/engine/src/flutter/shell/platform/windows/BUILD.gn +++ b/engine/src/flutter/shell/platform/windows/BUILD.gn @@ -55,6 +55,8 @@ source_set("flutter_windows_source") { "win32_dpi_helper.h", "win32_flutter_window.cc", "win32_flutter_window.h", + "win32_task_runner.cc", + "win32_task_runner.h", "win32_window.cc", "win32_window.h", "window_state.h", 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 823ea5826a..210524705a 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 @@ -44,8 +44,8 @@ HWND FlutterViewController::GetNativeWindow() { return FlutterDesktopGetHWND(controller_); } -void FlutterViewController::ProcessMessages() { - FlutterDesktopProcessMessages(); +std::chrono::nanoseconds FlutterViewController::ProcessMessages() { + return std::chrono::nanoseconds(FlutterDesktopProcessMessages(controller_)); } FlutterDesktopPluginRegistrarRef FlutterViewController::GetRegistrarForPlugin( 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 69ce1bafda..80299bc691 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 @@ -7,6 +7,7 @@ #include +#include #include #include @@ -51,9 +52,13 @@ class FlutterViewController : public PluginRegistry { // Return backing HWND for manipulation in host application. HWND GetNativeWindow(); - // Must be called in run loop to enable the view to do work on each tick of - // loop. - void ProcessMessages(); + // 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( 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 c4280d7d08..d3367cc19d 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 @@ -64,10 +64,12 @@ HWND FlutterDesktopGetHWND(FlutterDesktopViewControllerRef controller) { return reinterpret_cast(-1); } -void FlutterDesktopProcessMessages() { +uint64_t FlutterDesktopProcessMessages( + FlutterDesktopViewControllerRef controller) { if (s_stub_implementation) { return s_stub_implementation->FlutterDesktopProcessMessages(); } + return 0; } FlutterDesktopEngineRef FlutterDesktopRunEngine(const char* assets_path, diff --git a/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h b/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h index a86faef9e6..640dcabe9e 100644 --- a/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h +++ b/engine/src/flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h @@ -44,7 +44,7 @@ class StubFlutterWindowsApi { virtual void DestroyViewController() {} // Called for FlutterDesktopProcessMessages - virtual void FlutterDesktopProcessMessages() {} + virtual uint64_t FlutterDesktopProcessMessages() { return 0; } // Called for FlutterDesktopProcessMessages virtual HWND FlutterDesktopGetHWND() { return reinterpret_cast(1); } diff --git a/engine/src/flutter/shell/platform/windows/flutter_windows.cc b/engine/src/flutter/shell/platform/windows/flutter_windows.cc index beff9bed1a..c210898e97 100644 --- a/engine/src/flutter/shell/platform/windows/flutter_windows.cc +++ b/engine/src/flutter/shell/platform/windows/flutter_windows.cc @@ -20,6 +20,7 @@ #include "flutter/shell/platform/windows/platform_handler.h" #include "flutter/shell/platform/windows/text_input_plugin.h" #include "flutter/shell/platform/windows/win32_flutter_window.h" +#include "flutter/shell/platform/windows/win32_task_runner.h" #include "flutter/shell/platform/windows/window_state.h" static_assert(FLUTTER_ENGINE_VERSION == 1, ""); @@ -30,13 +31,16 @@ static_assert(FLUTTER_ENGINE_VERSION == 1, ""); // the necessary callbacks for rendering within a win32window (if one is // provided). // -// Returns a caller-owned pointer to the engine. -static FLUTTER_API_SYMBOL(FlutterEngine) - RunFlutterEngine(flutter::Win32FlutterWindow* window, - const char* assets_path, - const char* icu_data_path, - const char** arguments, - size_t arguments_count) { +// Returns the state object for the engine, or null on failure to start the +// engine. +static std::unique_ptr RunFlutterEngine( + flutter::Win32FlutterWindow* window, + const char* assets_path, + const char* icu_data_path, + const char** arguments, + size_t arguments_count) { + 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. @@ -47,9 +51,8 @@ static FLUTTER_API_SYMBOL(FlutterEngine) window->CreateRenderSurface(); - FlutterRendererConfig config = {}; - // 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 { @@ -74,6 +77,33 @@ static FLUTTER_API_SYMBOL(FlutterEngine) 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; + FlutterProjectArgs args = {}; args.struct_size = sizeof(FlutterProjectArgs); args.assets_path = assets_path; @@ -86,8 +116,7 @@ static FLUTTER_API_SYMBOL(FlutterEngine) auto window = reinterpret_cast(user_data); return window->HandlePlatformMessage(engine_message); }; - - // args.custom_task_runners = custom_task_runners; TODO + args.custom_task_runners = &custom_task_runners; FLUTTER_API_SYMBOL(FlutterEngine) engine = nullptr; auto result = @@ -97,8 +126,8 @@ static FLUTTER_API_SYMBOL(FlutterEngine) << std::endl; return nullptr; } - - return engine; + state->engine = engine; + return state; } FlutterDesktopViewControllerRef FlutterDesktopCreateViewController( @@ -112,30 +141,29 @@ FlutterDesktopViewControllerRef FlutterDesktopCreateViewController( flutter::Win32FlutterWindow::CreateWin32FlutterWindow(initial_width, initial_height); - auto engine = RunFlutterEngine(state->view.get(), assets_path, icu_data_path, - arguments, argument_count); + auto engine_state = RunFlutterEngine( + state->view.get(), assets_path, icu_data_path, arguments, argument_count); - if (engine == nullptr) { + if (!engine_state) { return nullptr; } - - state->view->SetState(engine); - state->engine = engine; - + state->view->SetState(engine_state->engine); + state->engine_state = std::move(engine_state); return state; } -void FlutterDesktopProcessMessages() { - __FlutterEngineFlushPendingTasksNow(); +uint64_t FlutterDesktopProcessMessages( + FlutterDesktopViewControllerRef controller) { + return controller->engine_state->task_runner->ProcessTasks().count(); } HWND FlutterDesktopGetHWND(FlutterDesktopViewControllerRef controller) { - return (controller)->view->GetWindowHandle(); + return controller->view->GetWindowHandle(); } void FlutterDesktopDestroyViewController( FlutterDesktopViewControllerRef controller) { - FlutterEngineShutdown(controller->engine); + FlutterEngineShutdown(controller->engine_state->engine); delete controller; } @@ -155,12 +183,7 @@ FlutterDesktopEngineRef FlutterDesktopRunEngine(const char* assets_path, size_t argument_count) { auto engine = RunFlutterEngine(nullptr, assets_path, icu_data_path, arguments, argument_count); - if (engine == nullptr) { - return nullptr; - } - auto engine_state = new FlutterDesktopEngineState(); - engine_state->engine = engine; - return engine_state; + return engine.release(); } bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) { 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 ccbd16c334..7d3798d870 100644 --- a/engine/src/flutter/shell/platform/windows/public/flutter_windows.h +++ b/engine/src/flutter/shell/platform/windows/public/flutter_windows.h @@ -65,9 +65,14 @@ FlutterDesktopGetPluginRegistrar(FlutterDesktopViewControllerRef controller, FLUTTER_EXPORT HWND FlutterDesktopGetHWND(FlutterDesktopViewControllerRef controller); -// Must be called in run loop to enable the view to do work on each tick of -// loop. -FLUTTER_EXPORT void FlutterDesktopProcessMessages(); +// Processes any pending events in the Flutter engine, and returns the +// 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); // Runs an instance of a headless Flutter engine. // diff --git a/engine/src/flutter/shell/platform/windows/win32_flutter_window.cc b/engine/src/flutter/shell/platform/windows/win32_flutter_window.cc index 1ea055c120..b5d8de160a 100644 --- a/engine/src/flutter/shell/platform/windows/win32_flutter_window.cc +++ b/engine/src/flutter/shell/platform/windows/win32_flutter_window.cc @@ -59,9 +59,6 @@ void Win32FlutterWindow::SetState(FLUTTER_API_SYMBOL(FlutterEngine) eng) { platform_handler_ = std::make_unique( internal_plugin_messenger, this); - auto state = std::make_unique(); - state->engine = engine_; - process_events_ = true; } diff --git a/engine/src/flutter/shell/platform/windows/win32_task_runner.cc b/engine/src/flutter/shell/platform/windows/win32_task_runner.cc new file mode 100644 index 0000000000..b2f5d473e5 --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/win32_task_runner.cc @@ -0,0 +1,100 @@ +// 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/win32_task_runner.h" + +#include +#include + +namespace flutter { + +Win32TaskRunner::Win32TaskRunner(DWORD main_thread_id, + TaskExpiredCallback on_task_expired) + : main_thread_id_(main_thread_id), + on_task_expired_(std::move(on_task_expired)) {} + +Win32TaskRunner::~Win32TaskRunner() = default; + +bool Win32TaskRunner::RunsTasksOnCurrentThread() const { + return GetCurrentThreadId() == main_thread_id_; +} + +std::chrono::nanoseconds Win32TaskRunner::ProcessTasks() { + const TaskTimePoint now = TaskTimePoint::clock::now(); + + std::vector expired_tasks; + + // Process expired tasks. + { + std::lock_guard lock(task_queue_mutex_); + while (!task_queue_.empty()) { + const auto& top = task_queue_.top(); + // If this task (and all tasks after this) has not yet expired, there is + // nothing more to do. Quit iterating. + if (top.fire_time > now) { + break; + } + + // Make a record of the expired task. Do NOT service the task here + // because we are still holding onto the task queue mutex. We don't want + // other threads to block on posting tasks onto this thread till we are + // done processing expired tasks. + expired_tasks.push_back(task_queue_.top().task); + + // Remove the tasks from the delayed tasks queue. + task_queue_.pop(); + } + } + + // Fire expired tasks. + { + // Flushing tasks here without holing onto the task queue mutex. + for (const auto& task : expired_tasks) { + on_task_expired_(&task); + } + } + + // Calculate duration to sleep for on next iteration. + { + std::lock_guard lock(task_queue_mutex_); + const auto next_wake = task_queue_.empty() ? TaskTimePoint::max() + : task_queue_.top().fire_time; + + return std::min(next_wake - now, std::chrono::nanoseconds::max()); + } +} + +Win32TaskRunner::TaskTimePoint Win32TaskRunner::TimePointFromFlutterTime( + uint64_t flutter_target_time_nanos) { + const auto now = TaskTimePoint::clock::now(); + const auto flutter_duration = + flutter_target_time_nanos - FlutterEngineGetCurrentTime(); + return now + std::chrono::nanoseconds(flutter_duration); +} + +void Win32TaskRunner::PostTask(FlutterTask flutter_task, + uint64_t flutter_target_time_nanos) { + static std::atomic_uint64_t sGlobalTaskOrder(0); + + Task task; + task.order = ++sGlobalTaskOrder; + task.fire_time = TimePointFromFlutterTime(flutter_target_time_nanos); + task.task = flutter_task; + + { + std::lock_guard lock(task_queue_mutex_); + task_queue_.push(task); + + // Make sure the queue mutex is unlocked before waking up the loop. In case + // the wake causes this thread to be descheduled for the primary thread to + // process tasks, the acquisition of the lock on that thread while holding + // the lock here momentarily till the end of the scope is a pessimization. + } + + if (!PostThreadMessage(main_thread_id_, WM_NULL, 0, 0)) { + OutputDebugString(L"Failed to post message to main thread."); + } +} + +} // namespace flutter diff --git a/engine/src/flutter/shell/platform/windows/win32_task_runner.h b/engine/src/flutter/shell/platform/windows/win32_task_runner.h new file mode 100644 index 0000000000..08be94941f --- /dev/null +++ b/engine/src/flutter/shell/platform/windows/win32_task_runner.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_WIN32_TASK_RUNNER_H_ +#define FLUTTER_SHELL_PLATFORM_WINDOWS_WIN32_TASK_RUNNER_H_ + +#include + +#include +#include +#include +#include +#include + +#include "flutter/shell/platform/embedder/embedder.h" + +namespace flutter { + +// A custom task runner that integrates with user32 GetMessage semantics so that +// host app can own its own message loop and flutter still gets to process +// tasks on a timely basis. +class Win32TaskRunner { + public: + using TaskExpiredCallback = std::function; + Win32TaskRunner(DWORD main_thread_id, TaskExpiredCallback on_task_expired); + + ~Win32TaskRunner(); + + // Returns if the current thread is the thread used by the win32 event loop. + bool RunsTasksOnCurrentThread() const; + + std::chrono::nanoseconds ProcessTasks(); + + // Post a Flutter engine tasks to the event loop for delayed execution. + void PostTask(FlutterTask flutter_task, uint64_t flutter_target_time_nanos); + + private: + using TaskTimePoint = std::chrono::steady_clock::time_point; + struct Task { + uint64_t order; + TaskTimePoint fire_time; + FlutterTask task; + + struct Comparer { + bool operator()(const Task& a, const Task& b) { + if (a.fire_time == b.fire_time) { + return a.order > b.order; + } + return a.fire_time > b.fire_time; + } + }; + }; + DWORD main_thread_id_; + TaskExpiredCallback on_task_expired_; + std::mutex task_queue_mutex_; + std::priority_queue, Task::Comparer> task_queue_; + std::condition_variable task_queue_cv_; + + Win32TaskRunner(const Win32TaskRunner&) = delete; + + Win32TaskRunner& operator=(const Win32TaskRunner&) = delete; + + static TaskTimePoint TimePointFromFlutterTime( + uint64_t flutter_target_time_nanos); +}; + +} // namespace flutter + +#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WIN32_TASK_RUNNER_H_ diff --git a/engine/src/flutter/shell/platform/windows/window_state.h b/engine/src/flutter/shell/platform/windows/window_state.h index a7c3ca0bee..254ab46c2e 100644 --- a/engine/src/flutter/shell/platform/windows/window_state.h +++ b/engine/src/flutter/shell/platform/windows/window_state.h @@ -12,17 +12,18 @@ #include "flutter/shell/platform/windows/keyboard_hook_handler.h" #include "flutter/shell/platform/windows/platform_handler.h" #include "flutter/shell/platform/windows/text_input_plugin.h" +#include "flutter/shell/platform/windows/win32_task_runner.h" struct flutter::Win32FlutterWindow; // Struct for storing state within an instance of the windows native (HWND or // CoreWindow) Window. struct FlutterDesktopViewControllerState { - //// The win32 window that owns this state object. + // The win32 window that owns this state object. std::unique_ptr view; - // The handle to the Flutter engine instance. - FLUTTER_API_SYMBOL(FlutterEngine) engine; + // 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; @@ -40,6 +41,9 @@ struct FlutterDesktopView { 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; }; // State associated with the plugin registrar.