Flutter Windows Embedder
flutter_windows_unittests.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
6 
7 #include <dxgi.h>
8 #include <wrl/client.h>
9 #include <thread>
10 
11 #include "flutter/fml/synchronization/count_down_latch.h"
12 #include "flutter/fml/synchronization/waitable_event.h"
14 #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
17 #include "flutter/shell/platform/windows/testing/engine_modifier.h"
18 #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
19 #include "flutter/shell/platform/windows/testing/windows_test.h"
20 #include "flutter/shell/platform/windows/testing/windows_test_config_builder.h"
21 #include "flutter/shell/platform/windows/testing/windows_test_context.h"
23 #include "flutter/testing/stream_capture.h"
24 #include "gmock/gmock.h"
25 #include "gtest/gtest.h"
26 #include "third_party/tonic/converter/dart_converter.h"
27 
28 namespace flutter {
29 namespace testing {
30 
31 namespace {
32 
33 // An EGL manager that initializes EGL but fails to create surfaces.
34 class HalfBrokenEGLManager : public egl::Manager {
35  public:
36  HalfBrokenEGLManager()
37  : egl::Manager(egl::GpuPreference::NoPreference,
38  /*allow_inverted_surface=*/false) {}
39 
40  std::unique_ptr<egl::WindowSurface>
41  CreateWindowSurface(HWND hwnd, size_t width, size_t height) override {
42  return nullptr;
43  }
44 };
45 
46 class MockWindowsLifecycleManager : public WindowsLifecycleManager {
47  public:
48  MockWindowsLifecycleManager(FlutterWindowsEngine* engine)
49  : WindowsLifecycleManager(engine) {}
50 
51  MOCK_METHOD(void, SetLifecycleState, (AppLifecycleState), (override));
52 };
53 
54 // Process the next win32 message if there is one. This can be used to
55 // pump the Windows platform thread task runner.
56 void PumpMessage() {
57  ::MSG msg;
58  if (::GetMessage(&msg, nullptr, 0, 0)) {
59  ::TranslateMessage(&msg);
60  ::DispatchMessage(&msg);
61  }
62 }
63 
64 } // namespace
65 
66 // Verify that we can fetch a texture registrar.
67 // Prevent regression: https://github.com/flutter/flutter/issues/86617
68 TEST(WindowsNoFixtureTest, GetTextureRegistrar) {
69  FlutterDesktopEngineProperties properties = {};
70  properties.assets_path = L"";
71  properties.icu_data_path = L"icudtl.dat";
72  properties.impeller_switch = DefaultImpeller;
73  auto engine = FlutterDesktopEngineCreate(&properties);
74  ASSERT_NE(engine, nullptr);
75  auto texture_registrar = FlutterDesktopEngineGetTextureRegistrar(engine);
76  EXPECT_NE(texture_registrar, nullptr);
78 }
79 
80 // Verify we can successfully launch main().
81 TEST_F(WindowsTest, LaunchMain) {
82  auto& context = GetContext();
83  WindowsConfigBuilder builder(context);
84  ViewControllerPtr controller{builder.Run()};
85  ASSERT_NE(controller, nullptr);
86 }
87 
88 // Verify there is no unexpected output from launching main.
89 TEST_F(WindowsTest, LaunchMainHasNoOutput) {
90  // Replace stderr stream buffer with our own. (stdout may contain expected
91  // output printed by Dart, such as the Dart VM service startup message)
92  StreamCapture stderr_capture(&std::cerr);
93 
94  auto& context = GetContext();
95  WindowsConfigBuilder builder(context);
96  ViewControllerPtr controller{builder.Run()};
97  ASSERT_NE(controller, nullptr);
98 
99  stderr_capture.Stop();
100 
101  // Verify stderr has no output.
102  EXPECT_TRUE(stderr_capture.GetOutput().empty());
103 }
104 
105 // Verify we can successfully launch a custom entry point.
106 TEST_F(WindowsTest, LaunchCustomEntrypoint) {
107  auto& context = GetContext();
108  WindowsConfigBuilder builder(context);
109  builder.SetDartEntrypoint("customEntrypoint");
110  ViewControllerPtr controller{builder.Run()};
111  ASSERT_NE(controller, nullptr);
112 }
113 
114 // Verify that engine launches with the custom entrypoint specified in the
115 // FlutterDesktopEngineRun parameter when no entrypoint is specified in
116 // FlutterDesktopEngineProperties.dart_entrypoint.
117 //
118 // TODO(cbracken): https://github.com/flutter/flutter/issues/109285
119 TEST_F(WindowsTest, LaunchCustomEntrypointInEngineRunInvocation) {
120  auto& context = GetContext();
121  WindowsConfigBuilder builder(context);
122  EnginePtr engine{builder.InitializeEngine()};
123  ASSERT_NE(engine, nullptr);
124 
125  ASSERT_TRUE(FlutterDesktopEngineRun(engine.get(), "customEntrypoint"));
126 }
127 
128 // Verify that the engine can launch in headless mode.
129 TEST_F(WindowsTest, LaunchHeadlessEngine) {
130  auto& context = GetContext();
131  WindowsConfigBuilder builder(context);
132  builder.SetDartEntrypoint("signalViewIds");
133  EnginePtr engine{builder.RunHeadless()};
134  ASSERT_NE(engine, nullptr);
135 
136  std::string view_ids;
137  bool signaled = false;
138  context.AddFfiNativeFunction(
139  "SignalStringValue", CREATE_FFI_LAMBDA([&](Dart_Handle handle) {
140  ASSERT_FALSE(Dart_IsError(handle));
141  view_ids = tonic::DartConverter<std::string>::FromDart(handle);
142  signaled = true;
143  }));
144 
145  ViewControllerPtr controller{builder.Run()};
146  ASSERT_NE(controller, nullptr);
147 
148  while (!signaled) {
149  PumpMessage();
150  }
151 
152  // Verify a headless app has the implicit view.
153  EXPECT_EQ(view_ids, "View IDs: [0]");
154 }
155 
156 // Verify that the engine can return to headless mode.
157 TEST_F(WindowsTest, EngineCanTransitionToHeadless) {
158  auto& context = GetContext();
159  WindowsConfigBuilder builder(context);
160  EnginePtr engine{builder.RunHeadless()};
161  ASSERT_NE(engine, nullptr);
162 
163  // Create and then destroy a view controller that does not own its engine.
164  // This causes the engine to transition back to headless mode.
165  {
167  ViewControllerPtr controller{
168  FlutterDesktopEngineCreateViewController(engine.get(), &properties)};
169 
170  ASSERT_NE(controller, nullptr);
171  }
172 
173  // The engine is back in headless mode now.
174  ASSERT_NE(engine, nullptr);
175 
176  auto engine_ptr = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
177  ASSERT_TRUE(engine_ptr->running());
178 }
179 
180 // Verify that accessibility features are initialized when a view is created.
181 TEST_F(WindowsTest, LaunchRefreshesAccessibility) {
182  auto& context = GetContext();
183  WindowsConfigBuilder builder(context);
184  EnginePtr engine{builder.InitializeEngine()};
185  EngineModifier modifier{
186  reinterpret_cast<FlutterWindowsEngine*>(engine.get())};
187 
188  auto called = false;
189  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
190  UpdateAccessibilityFeatures, ([&called](auto engine, auto flags) {
191  called = true;
192  return kSuccess;
193  }));
194 
195  ViewControllerPtr controller{
196  FlutterDesktopViewControllerCreate(0, 0, engine.release())};
197 
198  ASSERT_TRUE(called);
199 }
200 
201 // Verify that engine fails to launch when a conflicting entrypoint in
202 // FlutterDesktopEngineProperties.dart_entrypoint and the
203 // FlutterDesktopEngineRun parameter.
204 //
205 // TODO(cbracken): https://github.com/flutter/flutter/issues/109285
206 TEST_F(WindowsTest, LaunchConflictingCustomEntrypoints) {
207  auto& context = GetContext();
208  WindowsConfigBuilder builder(context);
209  builder.SetDartEntrypoint("customEntrypoint");
210  EnginePtr engine{builder.InitializeEngine()};
211  ASSERT_NE(engine, nullptr);
212 
213  ASSERT_FALSE(FlutterDesktopEngineRun(engine.get(), "conflictingEntrypoint"));
214 }
215 
216 // Verify that native functions can be registered and resolved.
217 TEST_F(WindowsTest, VerifyNativeFunction) {
218  auto& context = GetContext();
219  WindowsConfigBuilder builder(context);
220  builder.SetDartEntrypoint("verifyNativeFunction");
221 
222  bool signaled = false;
223  auto native_entry = CREATE_FFI_LAMBDA([&]() { signaled = true; });
224  context.AddFfiNativeFunction("Signal", native_entry);
225 
226  ViewControllerPtr controller{builder.Run()};
227  ASSERT_NE(controller, nullptr);
228 
229  // Wait until signal has been called.
230  while (!signaled) {
231  PumpMessage();
232  }
233 }
234 
235 // Verify that native functions that pass parameters can be registered and
236 // resolved.
237 TEST_F(WindowsTest, VerifyNativeFunctionWithParameters) {
238  auto& context = GetContext();
239  WindowsConfigBuilder builder(context);
240  builder.SetDartEntrypoint("verifyNativeFunctionWithParameters");
241 
242  bool bool_value = false;
243  bool signaled = false;
244  auto native_entry = CREATE_FFI_LAMBDA([&](bool value) {
245  bool_value = value;
246  signaled = true;
247  });
248  context.AddFfiNativeFunction("SignalBoolValue", native_entry);
249 
250  ViewControllerPtr controller{builder.Run()};
251  ASSERT_NE(controller, nullptr);
252 
253  // Wait until signalBoolValue has been called.
254  while (!signaled) {
255  PumpMessage();
256  }
257  EXPECT_TRUE(bool_value);
258 }
259 
260 // Verify that Platform.executable returns the executable name.
261 TEST_F(WindowsTest, PlatformExecutable) {
262  auto& context = GetContext();
263  WindowsConfigBuilder builder(context);
264  builder.SetDartEntrypoint("readPlatformExecutable");
265 
266  std::string executable_name;
267  bool signaled = false;
268  auto native_entry = CREATE_FFI_LAMBDA([&](Dart_Handle handle) {
269  ASSERT_FALSE(Dart_IsError(handle));
270  executable_name = tonic::DartConverter<std::string>::FromDart(handle);
271  signaled = true;
272  });
273  context.AddFfiNativeFunction("SignalStringValue", native_entry);
274 
275  ViewControllerPtr controller{builder.Run()};
276  ASSERT_NE(controller, nullptr);
277 
278  // Wait until signalStringValue has been called.
279  while (!signaled) {
280  PumpMessage();
281  }
282  EXPECT_EQ(executable_name, "flutter_windows_unittests.exe");
283 }
284 
285 // Verify that native functions that return values can be registered and
286 // resolved.
287 TEST_F(WindowsTest, VerifyNativeFunctionWithReturn) {
288  auto& context = GetContext();
289  WindowsConfigBuilder builder(context);
290  builder.SetDartEntrypoint("verifyNativeFunctionWithReturn");
291 
292  bool bool_value_to_return = true;
293  int count = 2;
294  auto bool_return_entry = CREATE_FFI_LAMBDA([&]() {
295  --count;
296  return bool_value_to_return;
297  });
298  context.AddFfiNativeFunction("SignalBoolReturn", bool_return_entry);
299 
300  bool bool_value_passed = false;
301  auto bool_pass_entry = CREATE_FFI_LAMBDA([&](bool value) {
302  bool_value_passed = value;
303  --count;
304  });
305  context.AddFfiNativeFunction("SignalBoolValue", bool_pass_entry);
306 
307  ViewControllerPtr controller{builder.Run()};
308  ASSERT_NE(controller, nullptr);
309 
310  // Wait until signalBoolReturn and signalBoolValue have been called.
311  while (count > 0) {
312  PumpMessage();
313  }
314  EXPECT_TRUE(bool_value_passed);
315 }
316 
317 // Verify the next frame callback is executed.
318 TEST_F(WindowsTest, NextFrameCallback) {
319  struct Captures {
320  fml::AutoResetWaitableEvent frame_scheduled_latch;
321  std::thread::id thread_id;
322  bool done = false;
323  };
324  Captures captures;
325 
326  auto platform_thread = std::make_unique<fml::Thread>("test_platform_thread");
327  platform_thread->GetTaskRunner()->PostTask([&]() {
328  captures.thread_id = std::this_thread::get_id();
329 
330  auto& context = GetContext();
331  WindowsConfigBuilder builder(context);
332  builder.SetDartEntrypoint("drawHelloWorld");
333 
334  auto native_entry =
335  CREATE_FFI_LAMBDA([&]() { captures.frame_scheduled_latch.Signal(); });
336  context.AddFfiNativeFunction("NotifyFirstFrameScheduled", native_entry);
337 
338  ViewControllerPtr controller{builder.Run()};
339  EXPECT_NE(controller, nullptr);
340 
341  auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
342 
344  engine,
345  [](void* user_data) {
346  auto captures = static_cast<Captures*>(user_data);
347 
348  EXPECT_TRUE(captures->frame_scheduled_latch.IsSignaledForTest());
349 
350  // Callback should execute on platform thread.
351  EXPECT_EQ(std::this_thread::get_id(), captures->thread_id);
352 
353  // Signal the test passed and end the Windows message loop.
354  captures->done = true;
355  },
356  &captures);
357 
358  // Pump messages for the Windows platform task runner.
359  while (!captures.done) {
360  PumpMessage();
361  }
362  });
363 
364  // Wait for the platform thread to exit.
365  platform_thread->Join();
366 }
367 
368 // Verify the embedder ignores presents to the implicit view when there is no
369 // implicit view.
370 TEST_F(WindowsTest, PresentHeadless) {
371  auto& context = GetContext();
372  WindowsConfigBuilder builder(context);
373  builder.SetDartEntrypoint("renderImplicitView");
374 
375  EnginePtr engine{builder.RunHeadless()};
376  ASSERT_NE(engine, nullptr);
377 
378  bool done = false;
380  engine.get(),
381  [](void* user_data) {
382  // This executes on the platform thread.
383  auto done = reinterpret_cast<std::atomic<bool>*>(user_data);
384  *done = true;
385  },
386  &done);
387 
388  // This app is in headless mode, however, the engine assumes the implicit
389  // view always exists. Send window metrics for the implicit view, causing
390  // the engine to present to the implicit view. The embedder must not crash.
391  auto engine_ptr = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
392  FlutterWindowMetricsEvent metrics = {};
393  metrics.struct_size = sizeof(FlutterWindowMetricsEvent);
394  metrics.width = 100;
395  metrics.height = 100;
396  metrics.pixel_ratio = 1.0;
397  metrics.view_id = kImplicitViewId;
398  engine_ptr->SendWindowMetricsEvent(metrics);
399 
400  // Pump messages for the Windows platform task runner.
401  while (!done) {
402  PumpMessage();
403  }
404 }
405 
406 // Verify IsPlatformThread returns true on the platform thread.
407 TEST_F(WindowsTest, IsPlatformThread) {
408  auto& context = GetContext();
409  WindowsConfigBuilder builder(context);
410 
411  EnginePtr engine{builder.RunHeadless()};
412  ASSERT_NE(engine, nullptr);
413 
414  EXPECT_TRUE(FlutterDesktopEngineIsPlatformThread(engine.get()));
415 }
416 
417 // Verify IsPlatformThread returns false on a background thread.
418 TEST_F(WindowsTest, IsNotPlatformThread) {
419  auto& context = GetContext();
420  WindowsConfigBuilder builder(context);
421 
422  EnginePtr engine{builder.RunHeadless()};
423  ASSERT_NE(engine, nullptr);
424 
425  bool result = true;
426  std::thread background(
427  [&]() { result = FlutterDesktopEngineIsPlatformThread(engine.get()); });
428  background.join();
429 
430  EXPECT_FALSE(result);
431 }
432 
433 // Verify a task can be posted to the platform thread while on the platform
434 // thread.
435 TEST_F(WindowsTest, PostPlatformThreadTaskFromPlatformThread) {
436  auto& context = GetContext();
437  WindowsConfigBuilder builder(context);
438 
439  EnginePtr engine{builder.RunHeadless()};
440  ASSERT_NE(engine, nullptr);
441 
442  struct Captures {
443  std::thread::id thread_id;
444  bool done = false;
445  } captures;
446 
448  engine.get(),
449  [](void* user_data) {
450  auto captures = static_cast<Captures*>(user_data);
451  captures->thread_id = std::this_thread::get_id();
452  captures->done = true;
453  },
454  /*on_cancel=*/nullptr, &captures);
455 
456  while (!captures.done) {
457  PumpMessage();
458  }
459 
460  EXPECT_EQ(captures.thread_id, std::this_thread::get_id());
461 }
462 
463 // Verify a task can be posted to the platform thread while on a background
464 // thread.
465 TEST_F(WindowsTest, PostPlatformThreadTaskFromBackgroundThread) {
466  auto& context = GetContext();
467  WindowsConfigBuilder builder(context);
468 
469  EnginePtr engine{builder.RunHeadless()};
470  ASSERT_NE(engine, nullptr);
471 
472  std::mutex background_thread_id_mutex;
473  struct Captures {
474  std::thread::id background_thread_id;
475  std::thread::id platform_thread_id;
476  bool done = false;
477  } captures;
478 
479  std::thread background([&]() {
480  {
481  std::scoped_lock lock{background_thread_id_mutex};
482  captures.background_thread_id = std::this_thread::get_id();
483  }
484 
486  engine.get(),
487  [](void* user_data) {
488  auto captures = static_cast<Captures*>(user_data);
489  captures->platform_thread_id = std::this_thread::get_id();
490  captures->done = true;
491  },
492  /*on_cancel=*/nullptr, &captures);
493  });
494  background.join();
495 
496  while (!captures.done) {
497  PumpMessage();
498  }
499 
500  std::scoped_lock lock{background_thread_id_mutex};
501  EXPECT_NE(captures.background_thread_id, std::thread::id{});
502  EXPECT_NE(captures.background_thread_id, captures.platform_thread_id);
503  EXPECT_EQ(captures.platform_thread_id, std::this_thread::get_id());
504 }
505 
506 // Verify that destroying the engine after posting a task invokes the cancel
507 // callback instead of the task callback.
508 TEST_F(WindowsTest, PostPlatformThreadTaskCancelledOnEngineDestroy) {
509  auto& context = GetContext();
510  WindowsConfigBuilder builder(context);
511 
512  EnginePtr engine{builder.RunHeadless()};
513  ASSERT_NE(engine, nullptr);
514 
515  struct Captures {
516  bool callback_called = false;
517  bool cancel_called = false;
518  } captures;
519 
521  engine.get(),
522  [](void* user_data) {
523  static_cast<Captures*>(user_data)->callback_called = true;
524  },
525  [](void* user_data) {
526  static_cast<Captures*>(user_data)->cancel_called = true;
527  },
528  &captures);
529 
530  // Destroy the engine before the task has a chance to run. The cancel
531  // callback should be called and the task callback should not.
532  engine.reset();
533 
534  EXPECT_FALSE(captures.callback_called);
535  EXPECT_TRUE(captures.cancel_called);
536 }
537 
538 // Verify that the cancel callback is not invoked for a task that runs.
539 TEST_F(WindowsTest, PostPlatformThreadTaskNotCancelledWhenRun) {
540  auto& context = GetContext();
541  WindowsConfigBuilder builder(context);
542 
543  EnginePtr engine{builder.RunHeadless()};
544  ASSERT_NE(engine, nullptr);
545 
546  struct Captures {
547  bool callback_called = false;
548  bool cancel_called = false;
549  } captures;
550 
552  engine.get(),
553  [](void* user_data) {
554  static_cast<Captures*>(user_data)->callback_called = true;
555  },
556  [](void* user_data) {
557  static_cast<Captures*>(user_data)->cancel_called = true;
558  },
559  &captures);
560 
561  EXPECT_FALSE(captures.cancel_called);
562 
563  while (!captures.callback_called) {
564  PumpMessage();
565  }
566 
567  // Ensures that the cancel callback is not called,
568  // in case the engine was shut down after running the task.
569  engine.reset();
570 
571  EXPECT_TRUE(captures.callback_called);
572  EXPECT_FALSE(captures.cancel_called);
573 }
574 
575 // Implicit view has the implicit view ID.
576 TEST_F(WindowsTest, GetViewId) {
577  auto& context = GetContext();
578  WindowsConfigBuilder builder(context);
579  ViewControllerPtr controller{builder.Run()};
580  ASSERT_NE(controller, nullptr);
581  FlutterDesktopViewId view_id =
582  FlutterDesktopViewControllerGetViewId(controller.get());
583 
584  ASSERT_EQ(view_id, static_cast<FlutterDesktopViewId>(kImplicitViewId));
585 }
586 
587 TEST_F(WindowsTest, GetGraphicsAdapter) {
588  auto& context = GetContext();
589  WindowsConfigBuilder builder(context);
590  ViewControllerPtr controller{builder.Run()};
591  ASSERT_NE(controller, nullptr);
592  auto view = FlutterDesktopViewControllerGetView(controller.get());
593 
594  Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter;
595  dxgi_adapter = FlutterDesktopViewGetGraphicsAdapter(view);
596  ASSERT_NE(dxgi_adapter, nullptr);
597  DXGI_ADAPTER_DESC desc{};
598  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
599 }
600 
601 TEST_F(WindowsTest, GetEngineGraphicsAdapter) {
602  auto& context = GetContext();
603  WindowsConfigBuilder builder(context);
604  ViewControllerPtr controller{builder.Run()};
605  ASSERT_NE(controller, nullptr);
606  auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
607 
608  // Can't use smart pointer because the result is not a real COM object.
609  IDXGIAdapter* dxgi_adapter;
610  ASSERT_TRUE(FlutterDesktopEngineGetGraphicsAdapter(engine, &dxgi_adapter));
611  ASSERT_NE(dxgi_adapter, nullptr);
612  DXGI_ADAPTER_DESC desc{};
613  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
614 }
615 
616 TEST_F(WindowsTest, GetGraphicsAdapterWithLowPowerPreference) {
617  std::optional<LUID> luid = egl::Manager::GetLowPowerGpuLuid();
618  if (!luid) {
619  GTEST_SKIP() << "Not able to find low power GPU, nothing to check.";
620  }
621 
622  auto& context = GetContext();
623  WindowsConfigBuilder builder(context);
624  builder.SetGpuPreference(FlutterDesktopGpuPreference::LowPowerPreference);
625  ViewControllerPtr controller{builder.Run()};
626  ASSERT_NE(controller, nullptr);
627  auto view = FlutterDesktopViewControllerGetView(controller.get());
628 
629  Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter;
630  dxgi_adapter = FlutterDesktopViewGetGraphicsAdapter(view);
631  ASSERT_NE(dxgi_adapter, nullptr);
632  DXGI_ADAPTER_DESC desc{};
633  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
634  ASSERT_EQ(desc.AdapterLuid.HighPart, luid->HighPart);
635  ASSERT_EQ(desc.AdapterLuid.LowPart, luid->LowPart);
636 }
637 
638 TEST_F(WindowsTest, GetGraphicsAdapterWithHighPerformancePreference) {
639  std::optional<LUID> luid = egl::Manager::GetHighPerformanceGpuLuid();
640  if (!luid) {
641  GTEST_SKIP() << "Not able to find high performance GPU, nothing to check.";
642  }
643 
644  auto& context = GetContext();
645  WindowsConfigBuilder builder(context);
646  builder.SetGpuPreference(
648  ViewControllerPtr controller{builder.Run()};
649  ASSERT_NE(controller, nullptr);
650  auto view = FlutterDesktopViewControllerGetView(controller.get());
651 
652  Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter;
653  dxgi_adapter = FlutterDesktopViewGetGraphicsAdapter(view);
654  ASSERT_NE(dxgi_adapter, nullptr);
655  DXGI_ADAPTER_DESC desc{};
656  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
657  ASSERT_EQ(desc.AdapterLuid.HighPart, luid->HighPart);
658  ASSERT_EQ(desc.AdapterLuid.LowPart, luid->LowPart);
659 }
660 
661 TEST_F(WindowsTest, GetEngineGraphicsAdapterWithLowPowerPreference) {
662  std::optional<LUID> luid = egl::Manager::GetLowPowerGpuLuid();
663  if (!luid) {
664  GTEST_SKIP() << "Not able to find low power GPU, nothing to check.";
665  }
666 
667  auto& context = GetContext();
668  WindowsConfigBuilder builder(context);
669  builder.SetGpuPreference(FlutterDesktopGpuPreference::LowPowerPreference);
670  ViewControllerPtr controller{builder.Run()};
671  ASSERT_NE(controller, nullptr);
672  auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
673 
674  // Can't use smart pointer because the result is not a real COM object.
675  IDXGIAdapter* dxgi_adapter;
676  ASSERT_TRUE(FlutterDesktopEngineGetGraphicsAdapter(engine, &dxgi_adapter));
677  ASSERT_NE(dxgi_adapter, nullptr);
678  DXGI_ADAPTER_DESC desc{};
679  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
680  ASSERT_EQ(desc.AdapterLuid.HighPart, luid->HighPart);
681  ASSERT_EQ(desc.AdapterLuid.LowPart, luid->LowPart);
682 }
683 
684 TEST_F(WindowsTest, GetEngineGraphicsAdapterWithHighPerformancePreference) {
685  std::optional<LUID> luid = egl::Manager::GetHighPerformanceGpuLuid();
686  if (!luid) {
687  GTEST_SKIP() << "Not able to find high performance GPU, nothing to check.";
688  }
689 
690  auto& context = GetContext();
691  WindowsConfigBuilder builder(context);
692  builder.SetGpuPreference(
694  ViewControllerPtr controller{builder.Run()};
695  ASSERT_NE(controller, nullptr);
696  auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
697 
698  // Can't use smart pointer because the result is not a real COM object.
699  IDXGIAdapter* dxgi_adapter;
700  ASSERT_TRUE(FlutterDesktopEngineGetGraphicsAdapter(engine, &dxgi_adapter));
701  ASSERT_NE(dxgi_adapter, nullptr);
702  DXGI_ADAPTER_DESC desc{};
703  ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
704  ASSERT_EQ(desc.AdapterLuid.HighPart, luid->HighPart);
705  ASSERT_EQ(desc.AdapterLuid.LowPart, luid->LowPart);
706 }
707 
708 // Implicit view has the implicit view ID.
709 TEST_F(WindowsTest, PluginRegistrarGetImplicitView) {
710  auto& context = GetContext();
711  WindowsConfigBuilder builder(context);
712  ViewControllerPtr controller{builder.Run()};
713  ASSERT_NE(controller, nullptr);
714 
715  FlutterDesktopEngineRef engine =
716  FlutterDesktopViewControllerGetEngine(controller.get());
718  FlutterDesktopEngineGetPluginRegistrar(engine, "foo_bar");
719  FlutterDesktopViewRef implicit_view =
721 
722  ASSERT_NE(implicit_view, nullptr);
723 }
724 
725 TEST_F(WindowsTest, PluginRegistrarGetView) {
726  auto& context = GetContext();
727  WindowsConfigBuilder builder(context);
728  ViewControllerPtr controller{builder.Run()};
729  ASSERT_NE(controller, nullptr);
730 
731  FlutterDesktopEngineRef engine =
732  FlutterDesktopViewControllerGetEngine(controller.get());
734  FlutterDesktopEngineGetPluginRegistrar(engine, "foo_bar");
735 
736  FlutterDesktopViewId view_id =
737  FlutterDesktopViewControllerGetViewId(controller.get());
738  FlutterDesktopViewRef view =
739  FlutterDesktopPluginRegistrarGetViewById(registrar, view_id);
740 
742  registrar, static_cast<FlutterDesktopViewId>(123));
743 
744  ASSERT_NE(view, nullptr);
745  ASSERT_EQ(view_123, nullptr);
746 }
747 
748 TEST_F(WindowsTest, PluginRegistrarGetViewHeadless) {
749  auto& context = GetContext();
750  WindowsConfigBuilder builder(context);
751  EnginePtr engine{builder.RunHeadless()};
752  ASSERT_NE(engine, nullptr);
753 
755  FlutterDesktopEngineGetPluginRegistrar(engine.get(), "foo_bar");
756 
757  FlutterDesktopViewRef implicit_view =
760  registrar, static_cast<FlutterDesktopViewId>(123));
761 
762  ASSERT_EQ(implicit_view, nullptr);
763  ASSERT_EQ(view_123, nullptr);
764 }
765 
766 // Verify the app does not crash if EGL initializes successfully but
767 // the rendering surface cannot be created.
768 TEST_F(WindowsTest, SurfaceOptional) {
769  auto& context = GetContext();
770  WindowsConfigBuilder builder(context);
771  EnginePtr engine{builder.InitializeEngine()};
772  EngineModifier modifier{
773  reinterpret_cast<FlutterWindowsEngine*>(engine.get())};
774 
775  auto egl_manager = std::make_unique<HalfBrokenEGLManager>();
776  ASSERT_TRUE(egl_manager->IsValid());
777  modifier.SetEGLManager(std::move(egl_manager));
778 
779  ViewControllerPtr controller{
780  FlutterDesktopViewControllerCreate(0, 0, engine.release())};
781 
782  ASSERT_NE(controller, nullptr);
783 }
784 
785 // Verify the app produces the expected lifecycle events.
786 TEST_F(WindowsTest, Lifecycle) {
787  auto& context = GetContext();
788  WindowsConfigBuilder builder(context);
789  EnginePtr engine{builder.InitializeEngine()};
790  auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
791  EngineModifier modifier{windows_engine};
792 
793  auto lifecycle_manager =
794  std::make_unique<MockWindowsLifecycleManager>(windows_engine);
795  auto lifecycle_manager_ptr = lifecycle_manager.get();
796  modifier.SetLifecycleManager(std::move(lifecycle_manager));
797 
798  EXPECT_CALL(*lifecycle_manager_ptr,
799  SetLifecycleState(AppLifecycleState::kInactive))
800  .WillOnce([lifecycle_manager_ptr](AppLifecycleState state) {
801  lifecycle_manager_ptr->WindowsLifecycleManager::SetLifecycleState(
802  state);
803  });
804 
805  EXPECT_CALL(*lifecycle_manager_ptr,
806  SetLifecycleState(AppLifecycleState::kHidden))
807  .WillOnce([lifecycle_manager_ptr](AppLifecycleState state) {
808  lifecycle_manager_ptr->WindowsLifecycleManager::SetLifecycleState(
809  state);
810  });
811 
812  FlutterDesktopViewControllerProperties properties = {0, 0};
813 
814  // Create a controller. This launches the engine and sets the app lifecycle
815  // to the "resumed" state.
816  ViewControllerPtr controller{
817  FlutterDesktopEngineCreateViewController(engine.get(), &properties)};
818 
819  FlutterDesktopViewRef view =
820  FlutterDesktopViewControllerGetView(controller.get());
821  ASSERT_NE(view, nullptr);
822 
823  HWND hwnd = FlutterDesktopViewGetHWND(view);
824  ASSERT_NE(hwnd, nullptr);
825 
826  // Give the window a non-zero size to show it. This does not change the app
827  // lifecycle directly. However, destroying the view will now result in a
828  // "hidden" app lifecycle event.
829  ::MoveWindow(hwnd, /* X */ 0, /* Y */ 0, /* nWidth*/ 100, /* nHeight*/ 100,
830  /* bRepaint*/ false);
831 
832  while (lifecycle_manager_ptr->IsUpdateStateScheduled()) {
833  PumpMessage();
834  }
835 
836  // Resets the view, simulating the window being hidden.
837  controller.reset();
838 
839  while (lifecycle_manager_ptr->IsUpdateStateScheduled()) {
840  PumpMessage();
841  }
842 }
843 
844 TEST_F(WindowsTest, GetKeyboardStateHeadless) {
845  auto& context = GetContext();
846  WindowsConfigBuilder builder(context);
847  builder.SetDartEntrypoint("sendGetKeyboardState");
848 
849  std::atomic<bool> done = false;
850  context.AddFfiNativeFunction(
851  "SignalStringValue", CREATE_FFI_LAMBDA([&](Dart_Handle handle) {
852  ASSERT_FALSE(Dart_IsError(handle));
853  auto value = tonic::DartConverter<std::string>::FromDart(handle);
854  EXPECT_EQ(value, "Success");
855  done = true;
856  }));
857 
858  ViewControllerPtr controller{builder.Run()};
859  ASSERT_NE(controller, nullptr);
860 
861  // Pump messages for the Windows platform task runner.
862  ::MSG msg;
863  while (!done) {
864  PumpMessage();
865  }
866 }
867 
868 // Verify the embedder can add and remove views.
869 TEST_F(WindowsTest, AddRemoveView) {
870  std::mutex mutex;
871  std::string view_ids;
872 
873  auto& context = GetContext();
874  WindowsConfigBuilder builder(context);
875  builder.SetDartEntrypoint("onMetricsChangedSignalViewIds");
876 
877  bool ready = false;
878  context.AddFfiNativeFunction("Signal",
879  CREATE_FFI_LAMBDA([&]() { ready = true; }));
880 
881  context.AddFfiNativeFunction(
882  "SignalStringValue", CREATE_FFI_LAMBDA([&](Dart_Handle handle) {
883  ASSERT_FALSE(Dart_IsError(handle));
884 
885  std::scoped_lock lock{mutex};
886  view_ids = tonic::DartConverter<std::string>::FromDart(handle);
887  }));
888 
889  // Create the implicit view.
890  ViewControllerPtr first_controller{builder.Run()};
891  ASSERT_NE(first_controller, nullptr);
892 
893  while (!ready) {
894  PumpMessage();
895  }
896 
897  // Create a second view.
898  FlutterDesktopEngineRef engine =
899  FlutterDesktopViewControllerGetEngine(first_controller.get());
901  properties.width = 100;
902  properties.height = 100;
903  ViewControllerPtr second_controller{
904  FlutterDesktopEngineCreateViewController(engine, &properties)};
905  ASSERT_NE(second_controller, nullptr);
906 
907  // Pump messages for the Windows platform task runner until the view is added.
908  while (true) {
909  PumpMessage();
910  std::scoped_lock lock{mutex};
911  if (view_ids == "View IDs: [0, 1]") {
912  break;
913  }
914  }
915 
916  // Delete the second view and pump messages for the Windows platform task
917  // runner until the view is removed.
918  second_controller.reset();
919  while (true) {
920  PumpMessage();
921  std::scoped_lock lock{mutex};
922  if (view_ids == "View IDs: [0]") {
923  break;
924  }
925  }
926 }
927 
928 TEST_F(WindowsTest, EngineId) {
929  auto& context = GetContext();
930  WindowsConfigBuilder builder(context);
931  builder.SetDartEntrypoint("testEngineId");
932 
933  std::optional<int64_t> engineId;
934  context.AddFfiNativeFunction(
935  "NotifyEngineId", CREATE_FFI_LAMBDA([&](Dart_Handle argument) {
936  if (!Dart_IsNull(argument)) {
937  const auto handle = tonic::DartConverter<int64_t>::FromDart(argument);
938  engineId = handle;
939  }
940  }));
941  // Create the implicit view.
942  ViewControllerPtr first_controller{builder.Run()};
943  ASSERT_NE(first_controller, nullptr);
944 
945  while (!engineId.has_value()) {
946  PumpMessage();
947  }
948 
949  auto engine = FlutterDesktopViewControllerGetEngine(first_controller.get());
950  EXPECT_EQ(engine, FlutterDesktopEngineForId(*engineId));
951 }
952 
953 TEST_F(WindowsTest, EnableIAccessible) {
954  auto& context = GetContext();
955  WindowsConfigBuilder builder(context);
956  builder.SetAccessibilityMode(
958  builder.SetDartEntrypoint("sendSemanticsTree");
959 
960  // Setup: a signal for when we have send out all of our semantics updates
961  bool done = false;
962  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
963  context.AddFfiNativeFunction("Signal", native_entry);
964 
965  // Setup: Create a view
966  ViewControllerPtr controller{builder.Run()};
967  ASSERT_NE(controller, nullptr);
968 
969  auto view = FlutterDesktopViewControllerGetView(controller.get());
970  ASSERT_NE(view, nullptr);
971 
972  // Setup: UpdateSemanticsEnabled will trigger the semantics updates
973  // to get sent.
974  auto windows_view = reinterpret_cast<FlutterWindowsView*>(view);
975  windows_view->OnUpdateSemanticsEnabled(true);
976 
977  while (!done) {
978  PumpMessage();
979  }
980 
981  HWND hwnd = FlutterDesktopViewGetHWND(view);
982  ASSERT_NE(hwnd, nullptr);
983 
984  LRESULT lres = SendMessage(hwnd, WM_GETOBJECT, 0, OBJID_CLIENT);
985  ASSERT_NE(lres, 0);
986 
987  // In IAccessible mode, the object returned from WM_GETOBJECT should support
988  // IAccessible but not IAccessibleEx.
989  IAccessible* accessible = nullptr;
990  HRESULT hr = ObjectFromLresult(lres, IID_IAccessible, 0, (void**)&accessible);
991  ASSERT_TRUE(SUCCEEDED(hr));
992  ASSERT_NE(accessible, nullptr);
993 
994  IAccessibleEx* accessible_ex = nullptr;
995  hr = ObjectFromLresult(lres, IID_IAccessibleEx, 0, (void**)&accessible_ex);
996  ASSERT_TRUE(FAILED(hr));
997  ASSERT_EQ(accessible_ex, nullptr);
998 }
999 
1000 TEST_F(WindowsTest, EnableIAccessibleEx) {
1001  auto& context = GetContext();
1002  WindowsConfigBuilder builder(context);
1003  builder.SetAccessibilityMode(
1005  builder.SetDartEntrypoint("sendSemanticsTree");
1006 
1007  // Setup: a signal for when we have send out all of our semantics updates
1008  bool done = false;
1009  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
1010  context.AddFfiNativeFunction("Signal", native_entry);
1011 
1012  // Setup: Create a view
1013  ViewControllerPtr controller{builder.Run()};
1014  ASSERT_NE(controller, nullptr);
1015 
1016  auto view = FlutterDesktopViewControllerGetView(controller.get());
1017  ASSERT_NE(view, nullptr);
1018 
1019  // Setup: UpdateSemanticsEnabled will trigger the semantics updates
1020  // to get sent.
1021  auto windows_view = reinterpret_cast<FlutterWindowsView*>(view);
1022  windows_view->OnUpdateSemanticsEnabled(true);
1023 
1024  while (!done) {
1025  PumpMessage();
1026  }
1027 
1028  HWND hwnd = FlutterDesktopViewGetHWND(view);
1029  ASSERT_NE(hwnd, nullptr);
1030 
1031  LRESULT lres = SendMessage(hwnd, WM_GETOBJECT, 0, OBJID_CLIENT);
1032  ASSERT_NE(lres, 0);
1033 
1034  // In IAccessibleEx mode, the object returned from WM_GETOBJECT should
1035  // support IAccessibleEx.
1036  IAccessibleEx* accessible_ex = nullptr;
1037  HRESULT hr =
1038  ObjectFromLresult(lres, IID_IAccessibleEx, 0, (void**)&accessible_ex);
1039  ASSERT_TRUE(SUCCEEDED(hr));
1040  ASSERT_NE(accessible_ex, nullptr);
1041  accessible_ex->Release();
1042 }
1043 
1044 } // namespace testing
1045 } // namespace flutter
virtual void OnUpdateSemanticsEnabled(bool enabled) override
WindowsLifecycleManager(FlutterWindowsEngine *engine)
virtual void SetLifecycleState(AppLifecycleState state)
static std::optional< LUID > GetLowPowerGpuLuid()
Definition: manager.cc:482
static std::optional< LUID > GetHighPerformanceGpuLuid()
Definition: manager.cc:486
MOCK_METHOD(void, Quit,(std::optional< HWND >, std::optional< WPARAM >, std::optional< LPARAM >, UINT),(override))
bool FlutterDesktopEngineGetGraphicsAdapter(FlutterDesktopEngineRef engine, IDXGIAdapter **adapter_out)
FlutterDesktopEngineRef FlutterDesktopEngineCreate(const FlutterDesktopEngineProperties *engine_properties)
FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopEngineForId(int64_t engine_id)
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById(FlutterDesktopPluginRegistrarRef registrar, FlutterDesktopViewId view_id)
FlutterDesktopPluginRegistrarRef FlutterDesktopEngineGetPluginRegistrar(FlutterDesktopEngineRef engine, const char *plugin_name)
bool FlutterDesktopEngineIsPlatformThread(FlutterDesktopEngineRef engine)
FlutterDesktopViewControllerRef FlutterDesktopViewControllerCreate(int width, int height, FlutterDesktopEngineRef engine)
bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine_ref)
void FlutterDesktopEnginePostPlatformThreadTask(FlutterDesktopEngineRef engine, VoidCallback callback, VoidCallback on_cancel, void *user_data)
FlutterDesktopTextureRegistrarRef FlutterDesktopEngineGetTextureRegistrar(FlutterDesktopEngineRef engine)
IDXGIAdapter * FlutterDesktopViewGetGraphicsAdapter(FlutterDesktopViewRef view)
FlutterDesktopViewId FlutterDesktopViewControllerGetViewId(FlutterDesktopViewControllerRef ref)
FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine(FlutterDesktopViewControllerRef ref)
void FlutterDesktopEngineSetNextFrameCallback(FlutterDesktopEngineRef engine, VoidCallback callback, void *user_data)
HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view)
FlutterDesktopViewRef FlutterDesktopViewControllerGetView(FlutterDesktopViewControllerRef ref)
FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView(FlutterDesktopPluginRegistrarRef registrar)
FlutterDesktopViewControllerRef FlutterDesktopEngineCreateViewController(FlutterDesktopEngineRef engine, const FlutterDesktopViewControllerProperties *properties)
bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine, const char *entry_point)
struct FlutterDesktopEngine * FlutterDesktopEngineRef
int64_t FlutterDesktopViewId
struct FlutterDesktopView * FlutterDesktopViewRef
@ LowPowerPreference
@ HighPerformancePreference
@ NoPreference
@ DefaultImpeller
@ IAccessibleMode
@ IAccessibleExMode
TEST_F(AccessibilityPluginTest, DirectAnnounceCall)
TEST(AccessibilityBridgeWindows, GetParent)
constexpr FlutterViewId kImplicitViewId
FlutterDesktopImpellerSwitch impeller_switch