[Windows] Prepare to add/remove views (flutter/engine#51908)

_This is a refactoring with no semantic changes._

Prepare the Windows embedder to add/remove views. In a multi-view world, the platform thread can remove a view while the raster thread presenting to the same view. A lock will be introduced to ensure this does not happen. This shuffles the code around so that the engine can acquire the lock before the compositor presents to the view.

Prepares for https://github.com/flutter/flutter/issues/138179
Part of https://github.com/flutter/flutter/issues/142845

[C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
This commit is contained in:
Loïc Sharma
2024-04-04 14:33:05 -07:00
committed by GitHub
parent 7553282a55
commit b0a3fb598e
11 changed files with 172 additions and 170 deletions

View File

@@ -9,6 +9,8 @@
namespace flutter {
class FlutterWindowsView;
// Enables the Flutter engine to render content on Windows.
//
// The engine uses this to:
@@ -31,7 +33,7 @@ class Compositor {
virtual bool CollectBackingStore(const FlutterBackingStore* store) = 0;
// Present Flutter content and platform views onto the view.
virtual bool Present(FlutterViewId view_id,
virtual bool Present(FlutterWindowsView* view,
const FlutterLayer** layers,
size_t layers_count) = 0;
};

View File

@@ -92,13 +92,10 @@ bool CompositorOpenGL::CollectBackingStore(const FlutterBackingStore* store) {
return true;
}
bool CompositorOpenGL::Present(FlutterViewId view_id,
bool CompositorOpenGL::Present(FlutterWindowsView* view,
const FlutterLayer** layers,
size_t layers_count) {
FlutterWindowsView* view = engine_->view(view_id);
if (!view) {
return false;
}
FML_DCHECK(view != nullptr);
// Clear the view if there are no layers to present.
if (layers_count == 0) {

View File

@@ -7,6 +7,7 @@
#include <memory>
#include "flutter/fml/macros.h"
#include "flutter/impeller/renderer/backend/gles/proc_table_gles.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/compositor.h"
@@ -28,7 +29,7 @@ class CompositorOpenGL : public Compositor {
bool CollectBackingStore(const FlutterBackingStore* store) override;
/// |Compositor|
bool Present(FlutterViewId view_id,
bool Present(FlutterWindowsView* view,
const FlutterLayer** layers,
size_t layers_count) override;
@@ -56,6 +57,8 @@ class CompositorOpenGL : public Compositor {
// Clear the view's surface and removes any previously presented layers.
bool Clear(FlutterWindowsView* view);
FML_DISALLOW_COPY_AND_ASSIGN(CompositorOpenGL);
};
} // namespace flutter

View File

@@ -108,9 +108,6 @@ class CompositorOpenGLTest : public WindowsTest {
ViewModifier modifier{view_.get()};
modifier.SetSurface(std::move(surface));
}
EngineModifier modifier{engine_.get()};
modifier.SetImplicitView(view_.get());
}
private:
@@ -169,7 +166,7 @@ TEST_F(CompositorOpenGLTest, Present) {
EXPECT_CALL(*surface(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface(), MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface(), SwapBuffers).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), &layer_ptr, 1));
EXPECT_TRUE(compositor.Present(view(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
@@ -185,53 +182,7 @@ TEST_F(CompositorOpenGLTest, PresentEmpty) {
EXPECT_CALL(*surface(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface(), MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface(), SwapBuffers).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), nullptr, 0));
}
TEST_F(CompositorOpenGLTest, HeadlessPresentIgnored) {
UseHeadlessEngine();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(kImplicitViewId, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorOpenGLTest, UnknownViewIgnored) {
UseEngineWithView();
auto compositor = CompositorOpenGL{engine(), kMockResolver};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
EXPECT_CALL(*render_context(), MakeCurrent).WillOnce(Return(true));
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
FlutterViewId unknown_view_id = 123;
ASSERT_NE(view()->view_id(), unknown_view_id);
ASSERT_EQ(engine()->view(unknown_view_id), nullptr);
EXPECT_FALSE(compositor.Present(unknown_view_id, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
EXPECT_TRUE(compositor.Present(view(), nullptr, 0));
}
TEST_F(CompositorOpenGLTest, NoSurfaceIgnored) {
@@ -250,7 +201,7 @@ TEST_F(CompositorOpenGLTest, NoSurfaceIgnored) {
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(view()->view_id(), &layer_ptr, 1));
EXPECT_FALSE(compositor.Present(view(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}

View File

@@ -9,8 +9,7 @@
namespace flutter {
CompositorSoftware::CompositorSoftware(FlutterWindowsEngine* engine)
: engine_(engine) {}
CompositorSoftware::CompositorSoftware() {}
bool CompositorSoftware::CreateBackingStore(
const FlutterBackingStoreConfig& config,
@@ -38,13 +37,10 @@ bool CompositorSoftware::CollectBackingStore(const FlutterBackingStore* store) {
return true;
}
bool CompositorSoftware::Present(FlutterViewId view_id,
bool CompositorSoftware::Present(FlutterWindowsView* view,
const FlutterLayer** layers,
size_t layers_count) {
FlutterWindowsView* view = engine_->view(view_id);
if (!view) {
return false;
}
FML_DCHECK(view != nullptr);
// Clear the view if there are no layers to present.
if (layers_count == 0) {

View File

@@ -5,6 +5,7 @@
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_SOFTWARE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_SOFTWARE_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/compositor.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
@@ -15,7 +16,7 @@ namespace flutter {
// rasterization and bitmaps.
class CompositorSoftware : public Compositor {
public:
CompositorSoftware(FlutterWindowsEngine* engine);
CompositorSoftware();
/// |Compositor|
bool CreateBackingStore(const FlutterBackingStoreConfig& config,
@@ -24,12 +25,12 @@ class CompositorSoftware : public Compositor {
bool CollectBackingStore(const FlutterBackingStore* store) override;
/// |Compositor|
bool Present(FlutterViewId view_id,
bool Present(FlutterWindowsView* view,
const FlutterLayer** layers,
size_t layers_count) override;
private:
FlutterWindowsEngine* engine_;
FML_DISALLOW_COPY_AND_ASSIGN(CompositorSoftware);
};
} // namespace flutter

View File

@@ -46,12 +46,6 @@ class CompositorSoftwareTest : public WindowsTest {
FlutterWindowsEngine* engine() { return engine_.get(); }
MockFlutterWindowsView* view() { return view_.get(); }
void UseHeadlessEngine() {
FlutterWindowsEngineBuilder builder{GetContext()};
engine_ = builder.Build();
}
void UseEngineWithView() {
FlutterWindowsEngineBuilder builder{GetContext()};
@@ -62,9 +56,6 @@ class CompositorSoftwareTest : public WindowsTest {
engine_ = builder.Build();
view_ = std::make_unique<MockFlutterWindowsView>(engine_.get(),
std::move(window));
EngineModifier modifier{engine_.get()};
modifier.SetImplicitView(view_.get());
}
private:
@@ -77,9 +68,7 @@ class CompositorSoftwareTest : public WindowsTest {
} // namespace
TEST_F(CompositorSoftwareTest, CreateBackingStore) {
UseHeadlessEngine();
auto compositor = CompositorSoftware{engine()};
CompositorSoftware compositor;
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
@@ -91,7 +80,7 @@ TEST_F(CompositorSoftwareTest, CreateBackingStore) {
TEST_F(CompositorSoftwareTest, Present) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
CompositorSoftware compositor;
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
@@ -104,7 +93,7 @@ TEST_F(CompositorSoftwareTest, Present) {
const FlutterLayer* layer_ptr = &layer;
EXPECT_CALL(*view(), PresentSoftwareBitmap).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), &layer_ptr, 1));
EXPECT_TRUE(compositor.Present(view(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
@@ -112,54 +101,10 @@ TEST_F(CompositorSoftwareTest, Present) {
TEST_F(CompositorSoftwareTest, PresentEmpty) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
CompositorSoftware compositor;
EXPECT_CALL(*view(), ClearSoftwareBitmap).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), nullptr, 0));
}
TEST_F(CompositorSoftwareTest, UnknownViewIgnored) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
FlutterViewId unknown_view_id = 123;
ASSERT_NE(view()->view_id(), unknown_view_id);
ASSERT_EQ(engine()->view(unknown_view_id), nullptr);
EXPECT_FALSE(compositor.Present(unknown_view_id, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorSoftwareTest, HeadlessPresentIgnored) {
UseHeadlessEngine();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(kImplicitViewId, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
EXPECT_TRUE(compositor.Present(view(), nullptr, 0));
}
} // namespace testing

View File

@@ -315,9 +315,49 @@ void drawHelloWorld() {
..addPicture(ui.Offset.zero, picture)
..pop();
ui.window.render(sceneBuilder.build());
ui.PlatformDispatcher.instance.implicitView?.render(sceneBuilder.build());
};
ui.PlatformDispatcher.instance.scheduleFrame();
notifyFirstFrameScheduled();
}
ui.Picture _createColoredBox(ui.Color color, ui.Size size) {
final ui.Paint paint = ui.Paint();
paint.color = color;
final ui.PictureRecorder baseRecorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(baseRecorder);
canvas.drawRect(ui.Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint);
return baseRecorder.endRecording();
}
@pragma('vm:entry-point')
void renderImplicitView() {
ui.PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final ui.Size size = ui.Size(800.0, 600.0);
final ui.Color red = ui.Color.fromARGB(127, 255, 0, 0);
final ui.SceneBuilder builder = ui.SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
ui.Offset(0.0, 0.0), _createColoredBox(red, size));
builder.pop();
ui.PlatformDispatcher.instance.implicitView?.render(builder.build());
};
ui.PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void signalViewIds() {
final Iterable<ui.FlutterView> views = ui.PlatformDispatcher.instance.views;
final List<int> viewIds =
views.map((ui.FlutterView view) => view.viewId).toList();
viewIds.sort();
signalStringValue('View IDs: [${viewIds.join(', ')}]');
}

View File

@@ -393,7 +393,7 @@ bool FlutterWindowsEngine::Run(std::string_view entrypoint) {
// constructors: https://github.com/flutter/flutter/issues/143375
compositor_ = std::make_unique<CompositorOpenGL>(this, resolver);
} else {
compositor_ = std::make_unique<CompositorSoftware>(this);
compositor_ = std::make_unique<CompositorSoftware>();
}
FlutterCompositor compositor = {};
@@ -418,8 +418,7 @@ bool FlutterWindowsEngine::Run(std::string_view entrypoint) {
[](const FlutterPresentViewInfo* info) -> bool {
auto host = static_cast<FlutterWindowsEngine*>(info->user_data);
return host->compositor_->Present(info->view_id, info->layers,
info->layers_count);
return host->Present(info);
};
args.compositor = &compositor;
@@ -873,4 +872,15 @@ void FlutterWindowsEngine::OnChannelUpdate(std::string name, bool listening) {
}
}
bool FlutterWindowsEngine::Present(const FlutterPresentViewInfo* info) {
auto iterator = views_.find(info->view_id);
if (iterator == views_.end()) {
return false;
}
FlutterWindowsView* view = iterator->second;
return compositor_->Present(view, info->layers, info->layers_count);
}
} // namespace flutter

View File

@@ -344,6 +344,11 @@ class FlutterWindowsEngine {
// Send the currently enabled accessibility features to the engine.
void SendAccessibilityFeatures();
// Present content to a view. Returns true if the content was presented.
//
// This is invoked on the raster thread.
bool Present(const FlutterPresentViewInfo* info);
// The handle to the embedder.h engine instance.
FLUTTER_API_SYMBOL(FlutterEngine) engine_ = nullptr;

View File

@@ -47,6 +47,16 @@ class MockWindowsLifecycleManager : public WindowsLifecycleManager {
MOCK_METHOD(void, SetLifecycleState, (AppLifecycleState), (override));
};
// Process the next win32 message if there is one. This can be used to
// pump the Windows platform thread task runner.
void PumpMessage() {
::MSG msg;
if (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
} // namespace
// Verify that we can fetch a texture registrar.
@@ -116,8 +126,26 @@ TEST_F(WindowsTest, LaunchCustomEntrypointInEngineRunInvocation) {
TEST_F(WindowsTest, LaunchHeadlessEngine) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("signalViewIds");
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
std::string view_ids;
fml::AutoResetWaitableEvent latch;
context.AddNativeFunction(
"SignalStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(Dart_IsError(handle));
view_ids = tonic::DartConverter<std::string>::FromDart(handle);
latch.Signal();
}));
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Verify a headless app has the implicit view.
latch.Wait();
EXPECT_EQ(view_ids, "View IDs: [0]");
}
// Verify that the engine can return to headless mode.
@@ -283,6 +311,7 @@ TEST_F(WindowsTest, NextFrameCallback) {
fml::AutoResetWaitableEvent frame_scheduled_latch;
fml::AutoResetWaitableEvent frame_drawn_latch;
std::thread::id thread_id;
bool done = false;
};
Captures captures;
@@ -315,22 +344,58 @@ TEST_F(WindowsTest, NextFrameCallback) {
ASSERT_EQ(std::this_thread::get_id(), captures->thread_id);
// Signal the test passed and end the Windows message loop.
captures->done = true;
captures->frame_drawn_latch.Signal();
::PostQuitMessage(0);
},
&captures);
// Pump messages for the Windows platform task runner.
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
while (!captures.done) {
PumpMessage();
}
});
captures.frame_drawn_latch.Wait();
}
// Verify the embedder ignores presents to the implicit view when there is no
// implicit view.
TEST_F(WindowsTest, PresentHeadless) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("renderImplicitView");
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
bool done = false;
FlutterDesktopEngineSetNextFrameCallback(
engine.get(),
[](void* user_data) {
// This executes on the platform thread.
auto done = reinterpret_cast<std::atomic<bool>*>(user_data);
*done = true;
},
&done);
// This app is in headless mode, however, the engine assumes the implicit
// view always exists. Send window metrics for the implicit view, causing
// the engine to present to the implicit view. The embedder must not crash.
auto engine_ptr = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
FlutterWindowMetricsEvent metrics = {};
metrics.struct_size = sizeof(FlutterWindowMetricsEvent);
metrics.width = 100;
metrics.height = 100;
metrics.pixel_ratio = 1.0;
metrics.view_id = kImplicitViewId;
engine_ptr->SendWindowMetricsEvent(metrics);
// Pump messages for the Windows platform task runner.
while (!done) {
PumpMessage();
}
}
// Implicit view has the implicit view ID.
TEST_F(WindowsTest, GetViewId) {
auto& context = GetContext();
@@ -481,41 +546,28 @@ TEST_F(WindowsTest, Lifecycle) {
}
TEST_F(WindowsTest, GetKeyboardStateHeadless) {
// Run the test on its own thread so that it can pump its event loop while
// this thread waits.
fml::AutoResetWaitableEvent latch;
auto platform_task_runner = CreateNewThread("test_platform_thread");
platform_task_runner->PostTask([&]() {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("sendGetKeyboardState");
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("sendGetKeyboardState");
bool done = false;
context.AddNativeFunction(
"SignalStringValue",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(Dart_IsError(handle));
auto value = tonic::DartConverter<std::string>::FromDart(handle);
EXPECT_EQ(value, "Success");
done = true;
latch.Signal();
}));
std::atomic<bool> done = false;
context.AddNativeFunction(
"SignalStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(Dart_IsError(handle));
auto value = tonic::DartConverter<std::string>::FromDart(handle);
EXPECT_EQ(value, "Success");
done = true;
}));
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Pump messages for the Windows platform task runner.
::MSG msg;
while (!done) {
if (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
});
latch.Wait();
// Pump messages for the Windows platform task runner.
::MSG msg;
while (!done) {
PumpMessage();
}
}
} // namespace testing