Flutter Windows Embedder
flutter_windows_engine_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 
5 #include <string>
6 #include <thread>
7 #include <vector>
9 
10 #include "flutter/fml/logging.h"
11 #include "flutter/fml/macros.h"
12 #include "flutter/shell/platform/embedder/embedder.h"
13 #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
16 #include "flutter/shell/platform/windows/testing/egl/mock_manager.h"
17 #include "flutter/shell/platform/windows/testing/engine_modifier.h"
18 #include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
19 #include "flutter/shell/platform/windows/testing/mock_platform_view_manager.h"
20 #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
21 #include "flutter/shell/platform/windows/testing/mock_windows_proc_table.h"
22 #include "flutter/shell/platform/windows/testing/test_keyboard.h"
23 #include "flutter/shell/platform/windows/testing/windows_test.h"
24 #include "flutter/shell/platform/windows/testing/windows_test_config_builder.h"
25 #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_win.h"
26 #include "fml/synchronization/waitable_event.h"
27 #include "gmock/gmock.h"
28 #include "gtest/gtest.h"
29 
30 // winbase.h defines GetCurrentTime as a macro.
31 #undef GetCurrentTime
32 
33 namespace {
34 // Process the next win32 message if there is one. This can be used to
35 // pump the Windows platform thread task runner.
36 void PumpMessage() {
37  ::MSG msg;
38  if (::GetMessage(&msg, nullptr, 0, 0)) {
39  ::TranslateMessage(&msg);
40  ::DispatchMessage(&msg);
41  }
42 }
43 } // namespace
44 
45 namespace flutter {
46 namespace testing {
47 
48 using ::testing::_;
49 using ::testing::DoAll;
50 using ::testing::NiceMock;
51 using ::testing::Return;
52 using ::testing::SetArgPointee;
53 
54 class FlutterWindowsEngineTest : public WindowsTest {};
55 
56 // The engine can be run without any views.
58  FlutterWindowsEngineBuilder builder{GetContext()};
59  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
60 
61  EngineModifier modifier(engine.get());
62  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
63 
64  ASSERT_TRUE(engine->Run());
65  ASSERT_EQ(engine->view(kImplicitViewId), nullptr);
66  ASSERT_EQ(engine->view(123), nullptr);
67 }
68 
69 TEST_F(FlutterWindowsEngineTest, TaskRunnerDelayedTask) {
70  bool finished = false;
71  auto runner = std::make_unique<TaskRunner>(
72  [] {
73  return static_cast<uint64_t>(
74  fml::TimePoint::Now().ToEpochDelta().ToNanoseconds());
75  },
76  [&](const FlutterTask*) { finished = true; });
77  runner->PostFlutterTask(
78  FlutterTask{},
79  static_cast<uint64_t>((fml::TimePoint::Now().ToEpochDelta() +
80  fml::TimeDelta::FromMilliseconds(50))
81  .ToNanoseconds()));
82  auto start = fml::TimePoint::Now();
83  while (!finished) {
84  PumpMessage();
85  }
86  auto duration = fml::TimePoint::Now() - start;
87  EXPECT_GE(duration, fml::TimeDelta::FromMilliseconds(50));
88 }
89 
90 // https://github.com/flutter/flutter/issues/173843)
91 TEST_F(FlutterWindowsEngineTest, TaskRunnerDoesNotDeadlock) {
92  auto runner = std::make_unique<TaskRunner>(
93  [] {
94  return static_cast<uint64_t>(
95  fml::TimePoint::Now().ToEpochDelta().ToNanoseconds());
96  },
97  [&](const FlutterTask*) {});
98 
99  struct RunnerHolder {
100  void PostTaskLoop() {
101  runner->PostTask([this] { PostTaskLoop(); });
102  }
103  std::unique_ptr<TaskRunner> runner;
104  };
105 
106  RunnerHolder container{.runner = std::move(runner)};
107  // Spam flutter tasks.
108  container.PostTaskLoop();
109 
110  const LPCWSTR class_name = L"FlutterTestWindowClass";
111  WNDCLASS wc = {0};
112  wc.lpfnWndProc = DefWindowProc;
113  wc.lpszClassName = class_name;
114  RegisterClass(&wc);
115 
116  HWND window;
117  container.runner->PostTask([&] {
118  window = CreateWindowEx(0, class_name, L"Empty Window", WS_OVERLAPPEDWINDOW,
119  CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, nullptr,
120  nullptr, nullptr, nullptr);
121  ShowWindow(window, SW_SHOW);
122  });
123 
124  while (true) {
125  ::MSG msg;
126  if (::GetMessage(&msg, nullptr, 0, 0)) {
127  if (msg.message == WM_PAINT) {
128  break;
129  }
130  ::TranslateMessage(&msg);
131  ::DispatchMessage(&msg);
132  }
133  }
134 
135  DestroyWindow(window);
136  UnregisterClassW(class_name, nullptr);
137 }
138 
139 TEST_F(FlutterWindowsEngineTest, RunDoesExpectedInitialization) {
140  FlutterWindowsEngineBuilder builder{GetContext()};
141  builder.AddDartEntrypointArgument("arg1");
142  builder.AddDartEntrypointArgument("arg2");
143 
144  auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
145 
146  HMONITOR mock_monitor = reinterpret_cast<HMONITOR>(1);
147 
148  MONITORINFOEXW monitor_info = {};
149  monitor_info.cbSize = sizeof(MONITORINFOEXW);
150  monitor_info.rcMonitor = {0, 0, 1920, 1080};
151  monitor_info.rcWork = {0, 0, 1920, 1080};
152  monitor_info.dwFlags = MONITORINFOF_PRIMARY;
153  wcscpy_s(monitor_info.szDevice, L"\\\\.\\DISPLAY1");
154 
155  EXPECT_CALL(*windows_proc_table, GetMonitorInfoW(mock_monitor, _))
156  .WillRepeatedly(DoAll(SetArgPointee<1>(monitor_info), Return(TRUE)));
157 
158  EXPECT_CALL(*windows_proc_table, EnumDisplayMonitors(nullptr, nullptr, _, _))
159  .WillRepeatedly([&](HDC hdc, LPCRECT lprcClip, MONITORENUMPROC lpfnEnum,
160  LPARAM dwData) {
161  lpfnEnum(mock_monitor, nullptr, &monitor_info.rcMonitor, dwData);
162  return TRUE;
163  });
164 
165  EXPECT_CALL(*windows_proc_table, GetDpiForMonitor(mock_monitor, _))
166  .WillRepeatedly(Return(96));
167 
168  // Mock locale information
169  EXPECT_CALL(*windows_proc_table, GetThreadPreferredUILanguages(_, _, _, _))
170  .WillRepeatedly(
171  [](DWORD flags, PULONG count, PZZWSTR languages, PULONG length) {
172  // We need to mock the locale information twice because the first
173  // call is to get the size and the second call is to fill the
174  // buffer.
175  if (languages == nullptr) {
176  // First call is to get the size
177  *count = 1; // One language
178  *length = 10; // "fr-FR\0\0" (double null-terminated)
179  return TRUE;
180  } else {
181  // Second call is to fill the buffer
182  *count = 1;
183  // Fill with "fr-FR\0\0" (double null-terminated)
184  wchar_t* lang_buffer = languages;
185  wcscpy(lang_buffer, L"fr-FR");
186  // Move past the first null terminator to add the second
187  lang_buffer += wcslen(L"fr-FR") + 1;
188  *lang_buffer = L'\0';
189  return TRUE;
190  }
191  });
192 
193  builder.SetWindowsProcTable(windows_proc_table);
194 
195  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
196  EngineModifier modifier(engine.get());
197 
198  // The engine should be run with expected configuration values.
199  bool run_called = false;
200  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
201  Run, ([&run_called, engine_instance = engine.get()](
202  size_t version, const FlutterRendererConfig* config,
203  const FlutterProjectArgs* args, void* user_data,
204  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
205  run_called = true;
206  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
207 
208  EXPECT_EQ(version, FLUTTER_ENGINE_VERSION);
209  EXPECT_NE(config, nullptr);
210  // We have an EGL manager, so this should be using OpenGL.
211  EXPECT_EQ(config->type, kOpenGL);
212  EXPECT_EQ(user_data, engine_instance);
213  // Spot-check arguments.
214  EXPECT_NE(args->assets_path, nullptr);
215  EXPECT_NE(args->icu_data_path, nullptr);
216  EXPECT_EQ(args->dart_entrypoint_argc, 2U);
217  EXPECT_EQ(strcmp(args->dart_entrypoint_argv[0], "arg1"), 0);
218  EXPECT_EQ(strcmp(args->dart_entrypoint_argv[1], "arg2"), 0);
219  EXPECT_NE(args->platform_message_callback, nullptr);
220  EXPECT_NE(args->custom_task_runners, nullptr);
221  EXPECT_NE(args->custom_task_runners->thread_priority_setter, nullptr);
222  EXPECT_EQ(args->custom_dart_entrypoint, nullptr);
223  EXPECT_NE(args->vsync_callback, nullptr);
224  EXPECT_EQ(args->update_semantics_callback, nullptr);
225  EXPECT_NE(args->update_semantics_callback2, nullptr);
226  EXPECT_EQ(args->update_semantics_node_callback, nullptr);
227  EXPECT_EQ(args->update_semantics_custom_action_callback, nullptr);
228  EXPECT_NE(args->view_focus_change_request_callback, nullptr);
229 
230  args->custom_task_runners->thread_priority_setter(
231  FlutterThreadPriority::kRaster);
232  EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
233  THREAD_PRIORITY_ABOVE_NORMAL);
234  return kSuccess;
235  }));
236  // Accessibility updates must do nothing when the embedder engine is mocked
237  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
238  UpdateAccessibilityFeatures,
239  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
240  FlutterAccessibilityFeature flags) { return kSuccess; });
241 
242  // It should send locale info.
243  bool update_locales_called = false;
244  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
245  UpdateLocales,
246  ([&update_locales_called](auto engine, const FlutterLocale** locales,
247  size_t locales_count) {
248  update_locales_called = true;
249 
250  EXPECT_GT(locales_count, 0);
251  EXPECT_NE(locales, nullptr);
252 
253  return kSuccess;
254  }));
255 
256  // And it should send initial settings info.
257  bool settings_message_sent = false;
258  modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
259  SendPlatformMessage,
260  ([&settings_message_sent](auto engine, auto message) {
261  if (std::string(message->channel) == std::string("flutter/settings")) {
262  settings_message_sent = true;
263  }
264 
265  return kSuccess;
266  }));
267 
268  // And it should send display info.
269  bool notify_display_update_called = false;
270 
271  modifier.embedder_api().NotifyDisplayUpdate = MOCK_ENGINE_PROC(
272  NotifyDisplayUpdate,
273  ([&notify_display_update_called](
274  FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
275  const FlutterEngineDisplaysUpdateType update_type,
276  const FlutterEngineDisplay* embedder_displays,
277  size_t display_count) {
278  EXPECT_EQ(update_type, kFlutterEngineDisplaysUpdateTypeStartup);
279  notify_display_update_called = true;
280  return kSuccess;
281  }));
282 
283  // Set the EGL manager to !nullptr to test ANGLE rendering.
284  modifier.SetEGLManager(std::make_unique<egl::MockManager>());
285 
286  engine->Run();
287 
288  EXPECT_TRUE(run_called);
289  EXPECT_TRUE(update_locales_called);
290  EXPECT_TRUE(settings_message_sent);
291  EXPECT_TRUE(notify_display_update_called);
292 
293  // Ensure that deallocation doesn't call the actual Shutdown with the bogus
294  // engine pointer that the overridden Run returned.
295  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
296  modifier.ReleaseEGLManager();
297 }
298 
299 TEST_F(FlutterWindowsEngineTest, ConfiguresFrameVsync) {
300  FlutterWindowsEngineBuilder builder{GetContext()};
301  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
302  EngineModifier modifier(engine.get());
303  bool on_vsync_called = false;
304 
305  modifier.embedder_api().GetCurrentTime =
306  MOCK_ENGINE_PROC(GetCurrentTime, ([]() -> uint64_t { return 1; }));
307  modifier.embedder_api().OnVsync = MOCK_ENGINE_PROC(
308  OnVsync,
309  ([&on_vsync_called, engine_instance = engine.get()](
310  FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton,
311  uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos) {
312  EXPECT_EQ(baton, 1);
313  EXPECT_EQ(frame_start_time_nanos, 16600000);
314  EXPECT_EQ(frame_target_time_nanos, 33200000);
315  on_vsync_called = true;
316  return kSuccess;
317  }));
318  modifier.SetStartTime(0);
319  modifier.SetFrameInterval(16600000);
320 
321  engine->OnVsync(1);
322 
323  EXPECT_TRUE(on_vsync_called);
324 }
325 
326 TEST_F(FlutterWindowsEngineTest, RunSkiaWithoutANGLEUsesSoftware) {
327  FlutterWindowsEngineBuilder builder{GetContext()};
328  builder.SetImpellerSwitch(DisabledImpeller);
329  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
330  EngineModifier modifier(engine.get());
331 
332  modifier.embedder_api().NotifyDisplayUpdate =
333  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
334  ([engine_instance = engine.get()](
335  FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
336  const FlutterEngineDisplaysUpdateType update_type,
337  const FlutterEngineDisplay* embedder_displays,
338  size_t display_count) { return kSuccess; }));
339 
340  // The engine should be run with expected configuration values.
341  bool run_called = false;
342  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
343  Run, ([&run_called, engine_instance = engine.get()](
344  size_t version, const FlutterRendererConfig* config,
345  const FlutterProjectArgs* args, void* user_data,
346  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
347  run_called = true;
348  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
349  // We don't have an EGL Manager, so we should be using software.
350  EXPECT_EQ(config->type, kSoftware);
351  return kSuccess;
352  }));
353  // Accessibility updates must do nothing when the embedder engine is mocked
354  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
355  UpdateAccessibilityFeatures,
356  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
357  FlutterAccessibilityFeature flags) { return kSuccess; });
358 
359  // Stub out UpdateLocales and SendPlatformMessage as we don't have a fully
360  // initialized engine instance.
361  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
362  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
363  size_t locales_count) { return kSuccess; }));
364  modifier.embedder_api().SendPlatformMessage =
365  MOCK_ENGINE_PROC(SendPlatformMessage,
366  ([](auto engine, auto message) { return kSuccess; }));
367 
368  // Set the EGL manager to nullptr to test software fallback path.
369  modifier.SetEGLManager(nullptr);
370 
371  engine->Run();
372 
373  EXPECT_TRUE(run_called);
374 
375  // Ensure that deallocation doesn't call the actual Shutdown with the bogus
376  // engine pointer that the overridden Run returned.
377  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
378 }
379 
380 TEST_F(FlutterWindowsEngineTest, RunWithoutANGLEOnImpellerFailsToStart) {
381  FlutterWindowsEngineBuilder builder{GetContext()};
382  builder.SetSwitches({"--enable-impeller=true"});
383  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
384  EngineModifier modifier(engine.get());
385 
386  modifier.embedder_api().NotifyDisplayUpdate =
387  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
388  ([engine_instance = engine.get()](
389  FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
390  const FlutterEngineDisplaysUpdateType update_type,
391  const FlutterEngineDisplay* embedder_displays,
392  size_t display_count) { return kSuccess; }));
393 
394  // Accessibility updates must do nothing when the embedder engine is mocked
395  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
396  UpdateAccessibilityFeatures,
397  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
398  FlutterAccessibilityFeature flags) { return kSuccess; });
399 
400  // Stub out UpdateLocales and SendPlatformMessage as we don't have a fully
401  // initialized engine instance.
402  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
403  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
404  size_t locales_count) { return kSuccess; }));
405  modifier.embedder_api().SendPlatformMessage =
406  MOCK_ENGINE_PROC(SendPlatformMessage,
407  ([](auto engine, auto message) { return kSuccess; }));
408 
409  // Set the EGL manager to nullptr to test software fallback path.
410  modifier.SetEGLManager(nullptr);
411 
412  EXPECT_FALSE(engine->Run());
413 }
414 
415 TEST_F(FlutterWindowsEngineTest, RunWithDefaultEnablesImpeller) {
416  FlutterWindowsEngineBuilder builder{GetContext()};
417  builder.SetImpellerSwitch(DefaultImpeller);
418  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
419  EngineModifier modifier(engine.get());
420 
421  modifier.embedder_api().NotifyDisplayUpdate =
422  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
423  ([engine_instance = engine.get()](
424  FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
425  const FlutterEngineDisplaysUpdateType update_type,
426  const FlutterEngineDisplay* embedder_displays,
427  size_t display_count) { return kSuccess; }));
428 
429  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
430  UpdateAccessibilityFeatures,
431  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
432  FlutterAccessibilityFeature flags) { return kSuccess; });
433 
434  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
435  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
436  size_t locales_count) { return kSuccess; }));
437 
438  modifier.embedder_api().SendPlatformMessage =
439  MOCK_ENGINE_PROC(SendPlatformMessage,
440  ([](auto engine, auto message) { return kSuccess; }));
441 
442  bool run_called = false;
443  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
444  Run, ([&run_called, engine_instance = engine.get()](
445  size_t version, const FlutterRendererConfig* config,
446  const FlutterProjectArgs* args, void* user_data,
447  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
448  run_called = true;
449  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
450 
451  bool has_impeller_switch = false;
452  bool has_sdf_switch = false;
453  for (int i = 0; i < args->command_line_argc; ++i) {
454  if (strcmp(args->command_line_argv[i], "--enable-impeller") == 0) {
455  has_impeller_switch = true;
456  }
457  if (strcmp(args->command_line_argv[i], "--impeller-use-sdfs=true") ==
458  0) {
459  has_sdf_switch = true;
460  }
461  }
462  EXPECT_TRUE(has_impeller_switch);
463  EXPECT_TRUE(has_sdf_switch);
464  return kSuccess;
465  }));
466 
467  // Set the EGL manager to !nullptr to test ANGLE rendering.
468  modifier.SetEGLManager(std::make_unique<egl::MockManager>());
469 
470  engine->Run();
471 
472  EXPECT_TRUE(run_called);
473 
474  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
475  modifier.ReleaseEGLManager();
476 }
477 
478 TEST_F(FlutterWindowsEngineTest, RunWithProjectFlagEnableImpeller) {
479  FlutterWindowsEngineBuilder builder{GetContext()};
480  builder.SetImpellerSwitch(EnabledImpeller);
481  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
482  EngineModifier modifier(engine.get());
483 
484  modifier.embedder_api().NotifyDisplayUpdate =
485  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
486  ([](FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
487  const FlutterEngineDisplaysUpdateType update_type,
488  const FlutterEngineDisplay* embedder_displays,
489  size_t display_count) { return kSuccess; }));
490 
491  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
492  UpdateAccessibilityFeatures,
493  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
494  FlutterAccessibilityFeature flags) { return kSuccess; });
495 
496  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
497  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
498  size_t locales_count) { return kSuccess; }));
499 
500  modifier.embedder_api().SendPlatformMessage =
501  MOCK_ENGINE_PROC(SendPlatformMessage,
502  ([](auto engine, auto message) { return kSuccess; }));
503 
504  bool run_called = false;
505  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
506  Run, ([&run_called](size_t version, const FlutterRendererConfig* config,
507  const FlutterProjectArgs* args, void* user_data,
508  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
509  run_called = true;
510  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
511 
512  bool has_impeller_switch = false;
513  bool has_sdf_switch = false;
514  for (int i = 0; i < args->command_line_argc; ++i) {
515  if (strcmp(args->command_line_argv[i], "--enable-impeller") == 0) {
516  has_impeller_switch = true;
517  }
518  if (strcmp(args->command_line_argv[i], "--impeller-use-sdfs=true") ==
519  0) {
520  has_sdf_switch = true;
521  }
522  }
523  EXPECT_TRUE(has_impeller_switch);
524  EXPECT_TRUE(has_sdf_switch);
525  return kSuccess;
526  }));
527 
528  // Set the EGL manager to !nullptr to test ANGLE rendering.
529  modifier.SetEGLManager(std::make_unique<egl::MockManager>());
530 
531  engine->Run();
532 
533  EXPECT_TRUE(run_called);
534 
535  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
536  modifier.ReleaseEGLManager();
537 }
538 
539 namespace {
540 // Runs |engine| with Impeller enabled and an EGL manager whose
541 // |surface_origin_is_top_left| returns |top_left|. Returns the command line
542 // switches that were forwarded to the embedder API's |Run|.
543 std::vector<std::string> RunImpellerWithSurfaceOrigin(
544  FlutterWindowsEngine* engine,
545  bool top_left) {
546  EngineModifier modifier(engine);
547  modifier.embedder_api().NotifyDisplayUpdate = MOCK_ENGINE_PROC(
548  NotifyDisplayUpdate, ([](auto engine, auto update_type, auto displays,
549  auto display_count) { return kSuccess; }));
550  modifier.embedder_api().UpdateAccessibilityFeatures =
551  MOCK_ENGINE_PROC(UpdateAccessibilityFeatures,
552  ([](auto engine, auto flags) { return kSuccess; }));
553  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
554  UpdateLocales,
555  ([](auto engine, auto locales, auto locales_count) { return kSuccess; }));
556  modifier.embedder_api().SendPlatformMessage =
557  MOCK_ENGINE_PROC(SendPlatformMessage,
558  ([](auto engine, auto message) { return kSuccess; }));
559 
560  std::vector<std::string> switches;
561  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
562  Run, ([&switches](size_t version, const FlutterRendererConfig* config,
563  const FlutterProjectArgs* args, void* user_data,
564  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
565  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
566  switches.assign(args->command_line_argv,
567  args->command_line_argv + args->command_line_argc);
568  return kSuccess;
569  }));
570 
571  auto egl_manager = std::make_unique<NiceMock<egl::MockManager>>();
572  ON_CALL(*egl_manager, surface_origin_is_top_left())
573  .WillByDefault(Return(top_left));
574  // The manager is intentionally leaked by |ReleaseEGLManager| below.
575  ::testing::Mock::AllowLeak(egl_manager.get());
576  modifier.SetEGLManager(std::move(egl_manager));
577 
578  EXPECT_TRUE(engine->Run());
579 
580  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
581  modifier.ReleaseEGLManager();
582  return switches;
583 }
584 
585 constexpr char kTopLeftOriginSwitch[] =
586  "--impeller-top-left-default-framebuffer-origin";
587 } // namespace
588 
590  RunWithTopLeftSurfaceOriginPassesTopLeftFramebufferSwitch) {
591  FlutterWindowsEngineBuilder builder{GetContext()};
592  builder.SetImpellerSwitch(EnabledImpeller);
593  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
594 
595  std::vector<std::string> switches =
596  RunImpellerWithSurfaceOrigin(engine.get(), /*top_left=*/true);
597 
598  EXPECT_THAT(switches, ::testing::Contains(kTopLeftOriginSwitch));
599 }
600 
602  RunWithBottomLeftSurfaceOriginOmitsTopLeftFramebufferSwitch) {
603  FlutterWindowsEngineBuilder builder{GetContext()};
604  builder.SetImpellerSwitch(EnabledImpeller);
605  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
606 
607  std::vector<std::string> switches =
608  RunImpellerWithSurfaceOrigin(engine.get(), /*top_left=*/false);
609 
610  EXPECT_THAT(switches,
611  ::testing::Not(::testing::Contains(kTopLeftOriginSwitch)));
612 }
613 
614 TEST_F(FlutterWindowsEngineTest, RunWithProjectFlagEnableFlutterGpu) {
615  FlutterWindowsEngineBuilder builder{GetContext()};
616  builder.SetEnableFlutterGpu(true);
617  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
618  EngineModifier modifier(engine.get());
619 
620  modifier.embedder_api().NotifyDisplayUpdate =
621  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
622  ([](FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
623  const FlutterEngineDisplaysUpdateType update_type,
624  const FlutterEngineDisplay* embedder_displays,
625  size_t display_count) { return kSuccess; }));
626 
627  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
628  UpdateAccessibilityFeatures,
629  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
630  FlutterAccessibilityFeature flags) { return kSuccess; });
631 
632  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
633  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
634  size_t locales_count) { return kSuccess; }));
635 
636  modifier.embedder_api().SendPlatformMessage =
637  MOCK_ENGINE_PROC(SendPlatformMessage,
638  ([](auto engine, auto message) { return kSuccess; }));
639 
640  bool run_called = false;
641  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
642  Run, ([&run_called](size_t version, const FlutterRendererConfig* config,
643  const FlutterProjectArgs* args, void* user_data,
644  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
645  run_called = true;
646  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
647 
648  bool has_flutter_gpu_switch = false;
649  for (int i = 0; i < args->command_line_argc; ++i) {
650  if (strcmp(args->command_line_argv[i], "--enable-flutter-gpu") == 0) {
651  has_flutter_gpu_switch = true;
652  }
653  }
654  EXPECT_TRUE(has_flutter_gpu_switch);
655  return kSuccess;
656  }));
657 
658  // Set the EGL manager to !nullptr to test ANGLE rendering.
659  modifier.SetEGLManager(std::make_unique<egl::MockManager>());
660 
661  engine->Run();
662 
663  EXPECT_TRUE(run_called);
664 
665  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
666  modifier.ReleaseEGLManager();
667 }
668 
669 TEST_F(FlutterWindowsEngineTest, RunWithoutProjectFlagEnableFlutterGpu) {
670  FlutterWindowsEngineBuilder builder{GetContext()};
671  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
672  EngineModifier modifier(engine.get());
673 
674  modifier.embedder_api().NotifyDisplayUpdate =
675  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
676  ([](FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
677  const FlutterEngineDisplaysUpdateType update_type,
678  const FlutterEngineDisplay* embedder_displays,
679  size_t display_count) { return kSuccess; }));
680 
681  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
682  UpdateAccessibilityFeatures,
683  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
684  FlutterAccessibilityFeature flags) { return kSuccess; });
685 
686  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
687  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
688  size_t locales_count) { return kSuccess; }));
689 
690  modifier.embedder_api().SendPlatformMessage =
691  MOCK_ENGINE_PROC(SendPlatformMessage,
692  ([](auto engine, auto message) { return kSuccess; }));
693 
694  bool run_called = false;
695  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
696  Run, ([&run_called](size_t version, const FlutterRendererConfig* config,
697  const FlutterProjectArgs* args, void* user_data,
698  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
699  run_called = true;
700  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
701 
702  bool has_flutter_gpu_switch = false;
703  for (int i = 0; i < args->command_line_argc; ++i) {
704  if (strcmp(args->command_line_argv[i], "--enable-flutter-gpu") == 0) {
705  has_flutter_gpu_switch = true;
706  }
707  }
708  EXPECT_FALSE(has_flutter_gpu_switch);
709  return kSuccess;
710  }));
711 
712  // Set the EGL manager to !nullptr to test ANGLE rendering.
713  modifier.SetEGLManager(std::make_unique<egl::MockManager>());
714 
715  engine->Run();
716 
717  EXPECT_TRUE(run_called);
718 
719  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
720  modifier.ReleaseEGLManager();
721 }
722 
723 TEST_F(FlutterWindowsEngineTest, RunWithProjectFlagDisableImpeller) {
724  FlutterWindowsEngineBuilder builder{GetContext()};
725  builder.SetImpellerSwitch(DisabledImpeller);
726  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
727  EngineModifier modifier(engine.get());
728 
729  modifier.embedder_api().NotifyDisplayUpdate =
730  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
731  ([](FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
732  const FlutterEngineDisplaysUpdateType update_type,
733  const FlutterEngineDisplay* embedder_displays,
734  size_t display_count) { return kSuccess; }));
735 
736  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
737  UpdateAccessibilityFeatures,
738  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
739  FlutterAccessibilityFeature flags) { return kSuccess; });
740 
741  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
742  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
743  size_t locales_count) { return kSuccess; }));
744 
745  modifier.embedder_api().SendPlatformMessage =
746  MOCK_ENGINE_PROC(SendPlatformMessage,
747  ([](auto engine, auto message) { return kSuccess; }));
748 
749  bool run_called = false;
750  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
751  Run, ([&run_called](size_t version, const FlutterRendererConfig* config,
752  const FlutterProjectArgs* args, void* user_data,
753  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
754  run_called = true;
755  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
756 
757  bool has_disable_impeller_switch = false;
758  for (int i = 0; i < args->command_line_argc; ++i) {
759  if (strcmp(args->command_line_argv[i], "--enable-impeller=false") ==
760  0) {
761  has_disable_impeller_switch = true;
762  }
763  }
764  EXPECT_TRUE(has_disable_impeller_switch);
765  return kSuccess;
766  }));
767 
768  engine->Run();
769 
770  EXPECT_TRUE(run_called);
771 
772  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
773 }
774 
775 TEST_F(FlutterWindowsEngineTest, RunWithCommandLineDisableImpeller) {
776  FlutterWindowsEngineBuilder builder{GetContext()};
777  builder.SetSwitches({"--enable-impeller=false"});
778  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
779  EngineModifier modifier(engine.get());
780 
781  modifier.embedder_api().NotifyDisplayUpdate =
782  MOCK_ENGINE_PROC(NotifyDisplayUpdate,
783  ([](FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
784  const FlutterEngineDisplaysUpdateType update_type,
785  const FlutterEngineDisplay* embedder_displays,
786  size_t display_count) { return kSuccess; }));
787 
788  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
789  UpdateAccessibilityFeatures,
790  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
791  FlutterAccessibilityFeature flags) { return kSuccess; });
792 
793  modifier.embedder_api().UpdateLocales = MOCK_ENGINE_PROC(
794  UpdateLocales, ([](auto engine, const FlutterLocale** locales,
795  size_t locales_count) { return kSuccess; }));
796 
797  modifier.embedder_api().SendPlatformMessage =
798  MOCK_ENGINE_PROC(SendPlatformMessage,
799  ([](auto engine, auto message) { return kSuccess; }));
800 
801  bool run_called = false;
802  modifier.embedder_api().Run = MOCK_ENGINE_PROC(
803  Run, ([&run_called](size_t version, const FlutterRendererConfig* config,
804  const FlutterProjectArgs* args, void* user_data,
805  FLUTTER_API_SYMBOL(FlutterEngine)* engine_out) {
806  run_called = true;
807  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(1);
808 
809  bool has_disable_impeller_switch = false;
810  for (int i = 0; i < args->command_line_argc; ++i) {
811  if (strcmp(args->command_line_argv[i], "--enable-impeller=false") ==
812  0) {
813  has_disable_impeller_switch = true;
814  }
815  }
816  EXPECT_TRUE(has_disable_impeller_switch);
817  return kSuccess;
818  }));
819 
820  engine->Run();
821 
822  EXPECT_TRUE(run_called);
823 
824  modifier.embedder_api().Shutdown = [](auto engine) { return kSuccess; };
825 }
826 
827 TEST_F(FlutterWindowsEngineTest, SendPlatformMessageWithoutResponse) {
828  FlutterWindowsEngineBuilder builder{GetContext()};
829  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
830  EngineModifier modifier(engine.get());
831 
832  const char* channel = "test";
833  const std::vector<uint8_t> test_message = {1, 2, 3, 4};
834 
835  // Without a response, SendPlatformMessage should be a simple pass-through.
836  bool called = false;
837  modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
838  SendPlatformMessage, ([&called, test_message](auto engine, auto message) {
839  called = true;
840  EXPECT_STREQ(message->channel, "test");
841  EXPECT_EQ(message->message_size, test_message.size());
842  EXPECT_EQ(memcmp(message->message, test_message.data(),
843  message->message_size),
844  0);
845  EXPECT_EQ(message->response_handle, nullptr);
846  return kSuccess;
847  }));
848 
849  engine->SendPlatformMessage(channel, test_message.data(), test_message.size(),
850  nullptr, nullptr);
851  EXPECT_TRUE(called);
852 }
853 
854 TEST_F(FlutterWindowsEngineTest, PlatformMessageRoundTrip) {
855  FlutterWindowsEngineBuilder builder{GetContext()};
856  builder.SetDartEntrypoint("hiPlatformChannels");
857 
858  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
859  EngineModifier modifier(engine.get());
860  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
861 
862  auto binary_messenger =
863  std::make_unique<BinaryMessengerImpl>(engine->messenger());
864 
865  engine->Run();
866  bool did_call_callback = false;
867  bool did_call_reply = false;
868  bool did_call_dart_reply = false;
869  std::string channel = "hi";
870  binary_messenger->SetMessageHandler(
871  channel,
872  [&did_call_callback, &did_call_dart_reply](
873  const uint8_t* message, size_t message_size, BinaryReply reply) {
874  if (message_size == 5) {
875  EXPECT_EQ(message[0], static_cast<uint8_t>('h'));
876  char response[] = {'b', 'y', 'e'};
877  reply(reinterpret_cast<uint8_t*>(response), 3);
878  did_call_callback = true;
879  } else {
880  EXPECT_EQ(message_size, 3);
881  EXPECT_EQ(message[0], static_cast<uint8_t>('b'));
882  did_call_dart_reply = true;
883  }
884  });
885  char payload[] = {'h', 'e', 'l', 'l', 'o'};
886  binary_messenger->Send(
887  channel, reinterpret_cast<uint8_t*>(payload), 5,
888  [&did_call_reply](const uint8_t* reply, size_t reply_size) {
889  EXPECT_EQ(reply_size, 5);
890  EXPECT_EQ(reply[0], static_cast<uint8_t>('h'));
891  did_call_reply = true;
892  });
893  // Rely on timeout mechanism in CI.
894  while (!did_call_callback || !did_call_reply || !did_call_dart_reply) {
895  engine->task_runner()->ProcessTasks();
896  }
897 }
898 
899 TEST_F(FlutterWindowsEngineTest, PlatformMessageRespondOnDifferentThread) {
900  FlutterWindowsEngineBuilder builder{GetContext()};
901  builder.SetDartEntrypoint("hiPlatformChannels");
902 
903  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
904 
905  EngineModifier modifier(engine.get());
906  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
907 
908  auto binary_messenger =
909  std::make_unique<BinaryMessengerImpl>(engine->messenger());
910 
911  engine->Run();
912  bool did_call_callback = false;
913  bool did_call_reply = false;
914  bool did_call_dart_reply = false;
915  std::string channel = "hi";
916  std::unique_ptr<std::thread> reply_thread;
917  binary_messenger->SetMessageHandler(
918  channel,
919  [&did_call_callback, &did_call_dart_reply, &reply_thread](
920  const uint8_t* message, size_t message_size, BinaryReply reply) {
921  if (message_size == 5) {
922  EXPECT_EQ(message[0], static_cast<uint8_t>('h'));
923  reply_thread.reset(new std::thread([reply = std::move(reply)]() {
924  char response[] = {'b', 'y', 'e'};
925  reply(reinterpret_cast<uint8_t*>(response), 3);
926  }));
927  did_call_callback = true;
928  } else {
929  EXPECT_EQ(message_size, 3);
930  EXPECT_EQ(message[0], static_cast<uint8_t>('b'));
931  did_call_dart_reply = true;
932  }
933  });
934  char payload[] = {'h', 'e', 'l', 'l', 'o'};
935  binary_messenger->Send(
936  channel, reinterpret_cast<uint8_t*>(payload), 5,
937  [&did_call_reply](const uint8_t* reply, size_t reply_size) {
938  EXPECT_EQ(reply_size, 5);
939  EXPECT_EQ(reply[0], static_cast<uint8_t>('h'));
940  did_call_reply = true;
941  });
942  // Rely on timeout mechanism in CI.
943  while (!did_call_callback || !did_call_reply || !did_call_dart_reply) {
944  engine->task_runner()->ProcessTasks();
945  }
946  ASSERT_TRUE(reply_thread);
947  reply_thread->join();
948 }
949 
950 TEST_F(FlutterWindowsEngineTest, SendPlatformMessageWithResponse) {
951  FlutterWindowsEngineBuilder builder{GetContext()};
952  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
953  EngineModifier modifier(engine.get());
954 
955  const char* channel = "test";
956  const std::vector<uint8_t> test_message = {1, 2, 3, 4};
957  auto* dummy_response_handle =
958  reinterpret_cast<FlutterPlatformMessageResponseHandle*>(5);
959  const FlutterDesktopBinaryReply reply_handler = [](auto... args) {};
960  void* reply_user_data = reinterpret_cast<void*>(6);
961 
962  // When a response is requested, a handle should be created, passed as part
963  // of the message, and then released.
964  bool create_response_handle_called = false;
965  modifier.embedder_api().PlatformMessageCreateResponseHandle =
966  MOCK_ENGINE_PROC(
967  PlatformMessageCreateResponseHandle,
968  ([&create_response_handle_called, &reply_handler, reply_user_data,
969  dummy_response_handle](auto engine, auto reply, auto user_data,
970  auto response_handle) {
971  create_response_handle_called = true;
972  EXPECT_EQ(reply, reply_handler);
973  EXPECT_EQ(user_data, reply_user_data);
974  EXPECT_NE(response_handle, nullptr);
975  *response_handle = dummy_response_handle;
976  return kSuccess;
977  }));
978  bool release_response_handle_called = false;
979  modifier.embedder_api().PlatformMessageReleaseResponseHandle =
980  MOCK_ENGINE_PROC(
981  PlatformMessageReleaseResponseHandle,
982  ([&release_response_handle_called, dummy_response_handle](
983  auto engine, auto response_handle) {
984  release_response_handle_called = true;
985  EXPECT_EQ(response_handle, dummy_response_handle);
986  return kSuccess;
987  }));
988  bool send_message_called = false;
989  modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
990  SendPlatformMessage, ([&send_message_called, test_message,
991  dummy_response_handle](auto engine, auto message) {
992  send_message_called = true;
993  EXPECT_STREQ(message->channel, "test");
994  EXPECT_EQ(message->message_size, test_message.size());
995  EXPECT_EQ(memcmp(message->message, test_message.data(),
996  message->message_size),
997  0);
998  EXPECT_EQ(message->response_handle, dummy_response_handle);
999  return kSuccess;
1000  }));
1001 
1002  engine->SendPlatformMessage(channel, test_message.data(), test_message.size(),
1003  reply_handler, reply_user_data);
1004  EXPECT_TRUE(create_response_handle_called);
1005  EXPECT_TRUE(release_response_handle_called);
1006  EXPECT_TRUE(send_message_called);
1007 }
1008 
1009 TEST_F(FlutterWindowsEngineTest, DispatchSemanticsAction) {
1010  FlutterWindowsEngineBuilder builder{GetContext()};
1011  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1012  EngineModifier modifier(engine.get());
1013 
1014  bool called = false;
1015  std::string message = "Hello";
1016  modifier.embedder_api().SendSemanticsAction = MOCK_ENGINE_PROC(
1017  SendSemanticsAction, ([&called, &message](auto engine, auto info) {
1018  called = true;
1019  EXPECT_EQ(info->view_id, 456);
1020  EXPECT_EQ(info->node_id, 42);
1021  EXPECT_EQ(info->action, kFlutterSemanticsActionDismiss);
1022  EXPECT_EQ(memcmp(info->data, message.c_str(), message.size()), 0);
1023  EXPECT_EQ(info->data_length, message.size());
1024  return kSuccess;
1025  }));
1026 
1027  auto data = fml::MallocMapping::Copy(message.c_str(), message.size());
1028  engine->DispatchSemanticsAction(456, 42, kFlutterSemanticsActionDismiss,
1029  std::move(data));
1030  EXPECT_TRUE(called);
1031 }
1032 
1033 TEST_F(FlutterWindowsEngineTest, SetsThreadPriority) {
1034  WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kBackground);
1035  EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
1036  THREAD_PRIORITY_BELOW_NORMAL);
1037 
1038  WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kDisplay);
1039  EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
1040  THREAD_PRIORITY_ABOVE_NORMAL);
1041 
1042  WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kRaster);
1043  EXPECT_EQ(GetThreadPriority(GetCurrentThread()),
1044  THREAD_PRIORITY_ABOVE_NORMAL);
1045 
1046  // FlutterThreadPriority::kNormal does not change thread priority, reset to 0
1047  // here.
1048  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
1049 
1050  WindowsPlatformThreadPrioritySetter(FlutterThreadPriority::kNormal);
1051  EXPECT_EQ(GetThreadPriority(GetCurrentThread()), THREAD_PRIORITY_NORMAL);
1052 }
1053 
1054 TEST_F(FlutterWindowsEngineTest, AddPluginRegistrarDestructionCallback) {
1055  FlutterWindowsEngineBuilder builder{GetContext()};
1056  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1057  EngineModifier modifier(engine.get());
1058 
1059  MockEmbedderApiForKeyboard(modifier,
1060  std::make_shared<MockKeyResponseController>());
1061 
1062  engine->Run();
1063 
1064  // Verify that destruction handlers don't overwrite each other.
1065  int result1 = 0;
1066  int result2 = 0;
1067  engine->AddPluginRegistrarDestructionCallback(
1069  auto result = reinterpret_cast<int*>(ref);
1070  *result = 1;
1071  },
1072  reinterpret_cast<FlutterDesktopPluginRegistrarRef>(&result1));
1073  engine->AddPluginRegistrarDestructionCallback(
1075  auto result = reinterpret_cast<int*>(ref);
1076  *result = 2;
1077  },
1078  reinterpret_cast<FlutterDesktopPluginRegistrarRef>(&result2));
1079 
1080  engine->Stop();
1081  EXPECT_EQ(result1, 1);
1082  EXPECT_EQ(result2, 2);
1083 }
1084 
1086  FlutterWindowsEngineBuilder builder{GetContext()};
1087  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1088  EngineModifier modifier(engine.get());
1089 
1090  bool called = false;
1091  modifier.embedder_api().ScheduleFrame =
1092  MOCK_ENGINE_PROC(ScheduleFrame, ([&called](auto engine) {
1093  called = true;
1094  return kSuccess;
1095  }));
1096 
1097  engine->ScheduleFrame();
1098  EXPECT_TRUE(called);
1099 }
1100 
1101 TEST_F(FlutterWindowsEngineTest, SetNextFrameCallback) {
1102  FlutterWindowsEngineBuilder builder{GetContext()};
1103  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1104  EngineModifier modifier(engine.get());
1105 
1106  bool called = false;
1107  modifier.embedder_api().SetNextFrameCallback = MOCK_ENGINE_PROC(
1108  SetNextFrameCallback, ([&called](auto engine, auto callback, auto data) {
1109  called = true;
1110  return kSuccess;
1111  }));
1112 
1113  engine->SetNextFrameCallback([]() {});
1114  EXPECT_TRUE(called);
1115 }
1116 
1117 TEST_F(FlutterWindowsEngineTest, GetExecutableName) {
1118  FlutterWindowsEngineBuilder builder{GetContext()};
1119  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1120  EXPECT_EQ(engine->GetExecutableName(), "flutter_windows_unittests.exe");
1121 }
1122 
1123 // Ensure that after setting or resetting the high contrast feature,
1124 // the corresponding status flag can be retrieved from the engine.
1125 TEST_F(FlutterWindowsEngineTest, UpdateHighContrastFeature) {
1126  auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
1127  EXPECT_CALL(*windows_proc_table, GetHighContrastEnabled)
1128  .WillOnce(Return(true))
1129  .WillOnce(Return(false));
1130 
1131  FlutterWindowsEngineBuilder builder{GetContext()};
1132  builder.SetWindowsProcTable(windows_proc_table);
1133  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1134  EngineModifier modifier(engine.get());
1135 
1136  std::optional<FlutterAccessibilityFeature> engine_flags;
1137  modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
1138  UpdateAccessibilityFeatures, ([&engine_flags](auto engine, auto flags) {
1139  engine_flags = flags;
1140  return kSuccess;
1141  }));
1142  modifier.embedder_api().SendPlatformMessage = MOCK_ENGINE_PROC(
1143  SendPlatformMessage,
1144  [](auto engine, const auto message) { return kSuccess; });
1145 
1146  // 1: High contrast is enabled.
1147  engine->UpdateHighContrastMode();
1148 
1149  EXPECT_TRUE(engine->high_contrast_enabled());
1150  EXPECT_TRUE(engine_flags.has_value());
1151  EXPECT_TRUE(
1152  engine_flags.value() &
1153  FlutterAccessibilityFeature::kFlutterAccessibilityFeatureHighContrast);
1154 
1155  // 2: High contrast is disabled.
1156  engine_flags.reset();
1157  engine->UpdateHighContrastMode();
1158 
1159  EXPECT_FALSE(engine->high_contrast_enabled());
1160  EXPECT_TRUE(engine_flags.has_value());
1161  EXPECT_FALSE(
1162  engine_flags.value() &
1163  FlutterAccessibilityFeature::kFlutterAccessibilityFeatureHighContrast);
1164 }
1165 
1166 TEST_F(FlutterWindowsEngineTest, PostRasterThreadTask) {
1167  FlutterWindowsEngineBuilder builder{GetContext()};
1168  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1169  EngineModifier modifier(engine.get());
1170 
1171  modifier.embedder_api().PostRenderThreadTask = MOCK_ENGINE_PROC(
1172  PostRenderThreadTask, ([](auto engine, auto callback, auto context) {
1173  callback(context);
1174  return kSuccess;
1175  }));
1176 
1177  bool called = false;
1178  engine->PostRasterThreadTask([&called]() { called = true; });
1179 
1180  EXPECT_TRUE(called);
1181 }
1182 
1183 class MockFlutterWindowsView : public FlutterWindowsView {
1184  public:
1186  std::unique_ptr<WindowBindingHandler> wbh)
1188  engine,
1189  std::move(wbh),
1190  false,
1191  BoxConstraints()) {}
1193 
1195  NotifyWinEventWrapper,
1196  (ui::AXPlatformNodeWin*, ax::mojom::Event),
1197  (override));
1198  MOCK_METHOD(HWND, GetWindowHandle, (), (const, override));
1199  MOCK_METHOD(bool, Focus, (), (override));
1200 
1201  private:
1202  FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsView);
1203 };
1204 
1205 // Verify the view is notified of accessibility announcements.
1206 TEST_F(FlutterWindowsEngineTest, AccessibilityAnnouncement) {
1207  auto& context = GetContext();
1208  WindowsConfigBuilder builder{context};
1209  builder.SetDartEntrypoint("sendAccessibilityAnnouncement");
1210 
1211  bool done = false;
1212  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
1213  context.AddFfiNativeFunction("Signal", native_entry);
1214 
1215  EnginePtr engine{builder.RunHeadless()};
1216  ASSERT_NE(engine, nullptr);
1217 
1218  ui::AXPlatformNodeDelegateBase parent_delegate;
1219  AlertPlatformNodeDelegate delegate{parent_delegate};
1220 
1221  auto window_binding_handler =
1222  std::make_unique<NiceMock<MockWindowBindingHandler>>();
1223  EXPECT_CALL(*window_binding_handler, GetAlertDelegate)
1224  .WillOnce(Return(&delegate));
1225 
1226  auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
1227  MockFlutterWindowsView view{windows_engine,
1228  std::move(window_binding_handler)};
1229  EngineModifier modifier{windows_engine};
1230  modifier.SetImplicitView(&view);
1231 
1232  windows_engine->UpdateSemanticsEnabled(true);
1233 
1234  EXPECT_CALL(view, NotifyWinEventWrapper).Times(1);
1235 
1236  // Rely on timeout mechanism in CI.
1237  while (!done) {
1238  windows_engine->task_runner()->ProcessTasks();
1239  }
1240 }
1241 
1242 // Verify the app can send accessibility announcements while in headless mode.
1243 TEST_F(FlutterWindowsEngineTest, AccessibilityAnnouncementHeadless) {
1244  auto& context = GetContext();
1245  WindowsConfigBuilder builder{context};
1246  builder.SetDartEntrypoint("sendAccessibilityAnnouncement");
1247 
1248  bool done = false;
1249  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
1250  context.AddFfiNativeFunction("Signal", native_entry);
1251 
1252  EnginePtr engine{builder.RunHeadless()};
1253  ASSERT_NE(engine, nullptr);
1254 
1255  auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
1256  windows_engine->UpdateSemanticsEnabled(true);
1257 
1258  // Rely on timeout mechanism in CI.
1259  while (!done) {
1260  windows_engine->task_runner()->ProcessTasks();
1261  }
1262 }
1263 
1264 // Verify the engine does not crash if it receives an accessibility event
1265 // it does not support yet.
1266 TEST_F(FlutterWindowsEngineTest, AccessibilityTooltip) {
1267  fml::testing::LogCapture log_capture;
1268 
1269  auto& context = GetContext();
1270  WindowsConfigBuilder builder{context};
1271  builder.SetDartEntrypoint("sendAccessibilityTooltipEvent");
1272 
1273  bool done = false;
1274  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
1275  context.AddFfiNativeFunction("Signal", native_entry);
1276 
1277  ViewControllerPtr controller{builder.Run()};
1278  ASSERT_NE(controller, nullptr);
1279 
1280  auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
1281  auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine);
1282  windows_engine->UpdateSemanticsEnabled(true);
1283 
1284  // Rely on timeout mechanism in CI.
1285  while (!done) {
1286  windows_engine->task_runner()->ProcessTasks();
1287  }
1288 
1289  // Verify no error was logged.
1290  // Regression test for:
1291  // https://github.com/flutter/flutter/issues/144274
1292  EXPECT_EQ(log_capture.str().find("tooltip"), std::string::npos);
1293 }
1294 
1296  public:
1298  : WindowsLifecycleManager(engine) {}
1300 
1302  void,
1303  Quit,
1304  (std::optional<HWND>, std::optional<WPARAM>, std::optional<LPARAM>, UINT),
1305  (override));
1306  MOCK_METHOD(void, DispatchMessage, (HWND, UINT, WPARAM, LPARAM), (override));
1307  MOCK_METHOD(bool, IsLastWindowOfProcess, (), (override));
1309 
1310  void BeginProcessingLifecycle() override {
1314  }
1315  }
1316 
1317  std::function<void()> begin_processing_callback = nullptr;
1318 };
1319 
1321  FlutterWindowsEngineBuilder builder{GetContext()};
1322  builder.SetDartEntrypoint("exitTestExit");
1323  bool finished = false;
1324 
1325  auto engine = builder.Build();
1326  auto window_binding_handler =
1327  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1328  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1329 
1330  EngineModifier modifier(engine.get());
1331  modifier.SetImplicitView(&view);
1332  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1333  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1334  EXPECT_CALL(*handler, Quit)
1335  .WillOnce([&finished](std::optional<HWND> hwnd,
1336  std::optional<WPARAM> wparam,
1337  std::optional<LPARAM> lparam,
1338  UINT exit_code) { finished = exit_code == 0; });
1339  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillRepeatedly(Return(true));
1340  modifier.SetLifecycleManager(std::move(handler));
1341 
1343 
1344  engine->Run();
1345 
1346  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1347  0);
1348 
1349  // The test will only succeed when this while loop exits. Otherwise it will
1350  // timeout.
1351  while (!finished) {
1352  engine->task_runner()->ProcessTasks();
1353  }
1354 }
1355 
1357  FlutterWindowsEngineBuilder builder{GetContext()};
1358  builder.SetDartEntrypoint("exitTestCancel");
1359  bool did_call = false;
1360 
1361  auto engine = builder.Build();
1362  auto window_binding_handler =
1363  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1364  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1365 
1366  EngineModifier modifier(engine.get());
1367  modifier.SetImplicitView(&view);
1368  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1369  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1370  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillRepeatedly(Return(true));
1371  EXPECT_CALL(*handler, Quit).Times(0);
1372  modifier.SetLifecycleManager(std::move(handler));
1374 
1375  auto binary_messenger =
1376  std::make_unique<BinaryMessengerImpl>(engine->messenger());
1377  binary_messenger->SetMessageHandler(
1378  "flutter/platform", [&did_call](const uint8_t* message,
1379  size_t message_size, BinaryReply reply) {
1380  std::string contents(message, message + message_size);
1381  EXPECT_NE(contents.find("\"method\":\"System.exitApplication\""),
1382  std::string::npos);
1383  EXPECT_NE(contents.find("\"type\":\"required\""), std::string::npos);
1384  EXPECT_NE(contents.find("\"exitCode\":0"), std::string::npos);
1385  did_call = true;
1386  char response[] = "";
1387  reply(reinterpret_cast<uint8_t*>(response), 0);
1388  });
1389 
1390  engine->Run();
1391 
1392  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1393  0);
1394 
1395  while (!did_call) {
1396  engine->task_runner()->ProcessTasks();
1397  }
1398 }
1399 
1400 // Flutter consumes the first WM_CLOSE message to allow the app to cancel the
1401 // exit. If the app does not cancel the exit, Flutter synthesizes a second
1402 // WM_CLOSE message.
1403 TEST_F(FlutterWindowsEngineTest, TestExitSecondCloseMessage) {
1404  FlutterWindowsEngineBuilder builder{GetContext()};
1405  builder.SetDartEntrypoint("exitTestExit");
1406  bool second_close = false;
1407 
1408  auto engine = builder.Build();
1409  auto window_binding_handler =
1410  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1411  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1412 
1413  EngineModifier modifier(engine.get());
1414  modifier.SetImplicitView(&view);
1415  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1416  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1417  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(true));
1418  EXPECT_CALL(*handler, Quit)
1419  .WillOnce([handler_ptr = handler.get()](
1420  std::optional<HWND> hwnd, std::optional<WPARAM> wparam,
1421  std::optional<LPARAM> lparam, UINT exit_code) {
1422  handler_ptr->WindowsLifecycleManager::Quit(hwnd, wparam, lparam,
1423  exit_code);
1424  });
1425  EXPECT_CALL(*handler, DispatchMessage)
1426  .WillRepeatedly(
1427  [&engine](HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
1428  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(
1429  hwnd, msg, wparam, lparam);
1430  });
1431  modifier.SetLifecycleManager(std::move(handler));
1433 
1434  engine->Run();
1435 
1436  // This delegate will be registered after the lifecycle manager, so it will be
1437  // called only when a message is not consumed by the lifecycle manager. This
1438  // should be called on the second, synthesized WM_CLOSE message that the
1439  // lifecycle manager posts.
1441  [](HWND hwnd, UINT message, WPARAM wpar, LPARAM lpar, void* user_data,
1442  LRESULT* result) {
1443  switch (message) {
1444  case WM_CLOSE: {
1445  bool* called = reinterpret_cast<bool*>(user_data);
1446  *called = true;
1447  return true;
1448  }
1449  }
1450  return false;
1451  },
1452  reinterpret_cast<void*>(&second_close));
1453 
1454  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1455  0);
1456 
1457  while (!second_close) {
1458  engine->task_runner()->ProcessTasks();
1459  }
1460 }
1461 
1462 TEST_F(FlutterWindowsEngineTest, TestExitCloseMultiWindow) {
1463  FlutterWindowsEngineBuilder builder{GetContext()};
1464  builder.SetDartEntrypoint("exitTestExit");
1465  bool finished = false;
1466 
1467  auto engine = builder.Build();
1468  auto window_binding_handler =
1469  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1470  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1471 
1472  EngineModifier modifier(engine.get());
1473  modifier.SetImplicitView(&view);
1474  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1475  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1476  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce([&finished]() {
1477  finished = true;
1478  return false;
1479  });
1480  // Quit should not be called when there is more than one window.
1481  EXPECT_CALL(*handler, Quit).Times(0);
1482  modifier.SetLifecycleManager(std::move(handler));
1484 
1485  engine->Run();
1486 
1487  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1488  0);
1489 
1490  while (!finished) {
1491  engine->task_runner()->ProcessTasks();
1492  }
1493 }
1494 
1495 TEST_F(FlutterWindowsEngineTest, LifecycleManagerDisabledByDefault) {
1496  FlutterWindowsEngineBuilder builder{GetContext()};
1497 
1498  auto engine = builder.Build();
1499  auto window_binding_handler =
1500  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1501  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1502 
1503  EngineModifier modifier(engine.get());
1504  modifier.SetImplicitView(&view);
1505  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1506  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1507  EXPECT_CALL(*handler, IsLastWindowOfProcess).Times(0);
1508  modifier.SetLifecycleManager(std::move(handler));
1509 
1510  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1511  0);
1512 }
1513 
1514 TEST_F(FlutterWindowsEngineTest, EnableApplicationLifecycle) {
1515  FlutterWindowsEngineBuilder builder{GetContext()};
1516 
1517  auto engine = builder.Build();
1518  auto window_binding_handler =
1519  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1520  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1521 
1522  EngineModifier modifier(engine.get());
1523  modifier.SetImplicitView(&view);
1524  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1525  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1526  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(false));
1527  modifier.SetLifecycleManager(std::move(handler));
1529 
1530  engine->window_proc_delegate_manager()->OnTopLevelWindowProc(0, WM_CLOSE, 0,
1531  0);
1532 }
1533 
1534 TEST_F(FlutterWindowsEngineTest, ApplicationLifecycleExternalWindow) {
1535  FlutterWindowsEngineBuilder builder{GetContext()};
1536 
1537  auto engine = builder.Build();
1538  auto window_binding_handler =
1539  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1540  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1541 
1542  EngineModifier modifier(engine.get());
1543  modifier.SetImplicitView(&view);
1544  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1545  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1546  EXPECT_CALL(*handler, IsLastWindowOfProcess).WillOnce(Return(false));
1547  modifier.SetLifecycleManager(std::move(handler));
1549 
1550  engine->lifecycle_manager()->ExternalWindowMessage(0, WM_CLOSE, 0, 0);
1551 }
1552 
1553 TEST_F(FlutterWindowsEngineTest, LifecycleStateTransition) {
1554  FlutterWindowsEngineBuilder builder{GetContext()};
1555 
1556  auto engine = builder.Build();
1557  auto window_binding_handler =
1558  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1559  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1560 
1561  EngineModifier modifier(engine.get());
1562  modifier.SetImplicitView(&view);
1563  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1564  engine->Run();
1565 
1567  (HWND)1, WM_SIZE, SIZE_RESTORED, 0);
1568 
1569  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1570  PumpMessage();
1571  }
1572 
1573  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1575 
1576  engine->lifecycle_manager()->OnWindowStateEvent((HWND)1,
1578 
1579  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1580  PumpMessage();
1581  }
1582 
1583  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1585 
1587  (HWND)1, WM_SIZE, SIZE_MINIMIZED, 0);
1588 
1589  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1590  PumpMessage();
1591  }
1592 
1593  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1595 
1597  (HWND)1, WM_SIZE, SIZE_RESTORED, 0);
1598 
1599  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1600  PumpMessage();
1601  }
1602 
1603  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1605 }
1606 
1607 TEST_F(FlutterWindowsEngineTest, ExternalWindowMessage) {
1608  FlutterWindowsEngineBuilder builder{GetContext()};
1609 
1610  auto engine = builder.Build();
1611  auto window_binding_handler =
1612  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1613  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1614 
1615  EngineModifier modifier(engine.get());
1616  modifier.SetImplicitView(&view);
1617  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1618  // Sets lifecycle state to resumed.
1619  engine->Run();
1620 
1621  // Ensure HWND(1) is in the set of visible windows before hiding it.
1622  engine->ProcessExternalWindowMessage(reinterpret_cast<HWND>(1), WM_SHOWWINDOW,
1623  TRUE, NULL);
1624  engine->ProcessExternalWindowMessage(reinterpret_cast<HWND>(1), WM_SHOWWINDOW,
1625  FALSE, NULL);
1626 
1627  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1628  PumpMessage();
1629  }
1630 
1631  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1633 }
1634 
1635 TEST_F(FlutterWindowsEngineTest, InnerWindowHidden) {
1636  FlutterWindowsEngineBuilder builder{GetContext()};
1637  HWND outer = reinterpret_cast<HWND>(1);
1638  HWND inner = reinterpret_cast<HWND>(2);
1639 
1640  auto engine = builder.Build();
1641  auto window_binding_handler =
1642  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1643  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1644  ON_CALL(view, GetWindowHandle).WillByDefault([=]() { return inner; });
1645 
1646  EngineModifier modifier(engine.get());
1647  modifier.SetImplicitView(&view);
1648  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1649  // Sets lifecycle state to resumed.
1650  engine->Run();
1651 
1652  // Show both top-level and Flutter window.
1654  outer, WM_SHOWWINDOW, TRUE, NULL);
1655  view.OnWindowStateEvent(inner, WindowStateEvent::kShow);
1656  view.OnWindowStateEvent(inner, WindowStateEvent::kFocus);
1657 
1658  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1659  PumpMessage();
1660  }
1661 
1662  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1664 
1665  // Hide Flutter window, but not top level window.
1666  view.OnWindowStateEvent(inner, WindowStateEvent::kHide);
1667 
1668  while (engine->lifecycle_manager()->IsUpdateStateScheduled()) {
1669  PumpMessage();
1670  }
1671 
1672  // The top-level window is still visible, so we ought not enter hidden state.
1673  EXPECT_EQ(engine->lifecycle_manager()->GetLifecycleState(),
1675 }
1676 
1677 TEST_F(FlutterWindowsEngineTest, EnableLifecycleState) {
1678  FlutterWindowsEngineBuilder builder{GetContext()};
1679  builder.SetDartEntrypoint("enableLifecycleTest");
1680  bool finished = false;
1681 
1682  auto engine = builder.Build();
1683  auto window_binding_handler =
1684  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1685  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1686 
1687  EngineModifier modifier(engine.get());
1688  modifier.SetImplicitView(&view);
1689  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1690  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1691  EXPECT_CALL(*handler, SetLifecycleState)
1692  .WillRepeatedly([handler_ptr = handler.get()](AppLifecycleState state) {
1693  handler_ptr->WindowsLifecycleManager::SetLifecycleState(state);
1694  });
1695  modifier.SetLifecycleManager(std::move(handler));
1696 
1697  auto binary_messenger =
1698  std::make_unique<BinaryMessengerImpl>(engine->messenger());
1699  // Mark the test only as completed on receiving an inactive state message.
1700  binary_messenger->SetMessageHandler(
1701  "flutter/unittest", [&finished](const uint8_t* message,
1702  size_t message_size, BinaryReply reply) {
1703  std::string contents(message, message + message_size);
1704  EXPECT_NE(contents.find("AppLifecycleState.inactive"),
1705  std::string::npos);
1706  finished = true;
1707  char response[] = "";
1708  reply(reinterpret_cast<uint8_t*>(response), 0);
1709  });
1710 
1711  engine->Run();
1712 
1713  // Test that setting the state before enabling lifecycle does nothing.
1714  HWND hwnd = reinterpret_cast<HWND>(1);
1715  view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
1716  view.OnWindowStateEvent(hwnd, WindowStateEvent::kHide);
1717  EXPECT_FALSE(finished);
1718 
1719  // Test that we can set the state afterwards.
1720 
1722  view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
1723 
1724  while (!finished) {
1725  engine->task_runner()->ProcessTasks();
1726  }
1727 }
1728 
1729 TEST_F(FlutterWindowsEngineTest, LifecycleStateToFrom) {
1730  FlutterWindowsEngineBuilder builder{GetContext()};
1731  builder.SetDartEntrypoint("enableLifecycleToFrom");
1732  bool enabled_lifecycle = false;
1733  bool dart_responded = false;
1734 
1735  auto engine = builder.Build();
1736  auto window_binding_handler =
1737  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1738  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1739 
1740  EngineModifier modifier(engine.get());
1741  modifier.SetImplicitView(&view);
1742  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1743  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1744  EXPECT_CALL(*handler, SetLifecycleState)
1745  .WillRepeatedly([handler_ptr = handler.get()](AppLifecycleState state) {
1746  handler_ptr->WindowsLifecycleManager::SetLifecycleState(state);
1747  });
1748  handler->begin_processing_callback = [&]() { enabled_lifecycle = true; };
1749  modifier.SetLifecycleManager(std::move(handler));
1750 
1751  auto binary_messenger =
1752  std::make_unique<BinaryMessengerImpl>(engine->messenger());
1753  binary_messenger->SetMessageHandler(
1754  "flutter/unittest",
1755  [&](const uint8_t* message, size_t message_size, BinaryReply reply) {
1756  std::string contents(message, message + message_size);
1757  EXPECT_NE(contents.find("AppLifecycleState."), std::string::npos);
1758  dart_responded = true;
1759  char response[] = "";
1760  reply(reinterpret_cast<uint8_t*>(response), 0);
1761  });
1762 
1763  engine->Run();
1764 
1765  while (!enabled_lifecycle) {
1766  engine->task_runner()->ProcessTasks();
1767  }
1768 
1769  HWND hwnd = reinterpret_cast<HWND>(1);
1770  view.OnWindowStateEvent(hwnd, WindowStateEvent::kShow);
1771  view.OnWindowStateEvent(hwnd, WindowStateEvent::kHide);
1772 
1773  while (!dart_responded) {
1774  engine->task_runner()->ProcessTasks();
1775  }
1776 }
1777 
1778 TEST_F(FlutterWindowsEngineTest, ChannelListenedTo) {
1779  FlutterWindowsEngineBuilder builder{GetContext()};
1780  builder.SetDartEntrypoint("enableLifecycleToFrom");
1781 
1782  auto engine = builder.Build();
1783  auto window_binding_handler =
1784  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1785  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1786 
1787  EngineModifier modifier(engine.get());
1788  modifier.SetImplicitView(&view);
1789  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1790 
1791  bool lifecycle_began = false;
1792  auto handler = std::make_unique<MockWindowsLifecycleManager>(engine.get());
1793  handler->begin_processing_callback = [&]() { lifecycle_began = true; };
1794  modifier.SetLifecycleManager(std::move(handler));
1795 
1796  engine->Run();
1797 
1798  while (!lifecycle_began) {
1799  engine->task_runner()->ProcessTasks();
1800  }
1801 }
1802 
1803 TEST_F(FlutterWindowsEngineTest, ReceivePlatformViewMessage) {
1804  FlutterWindowsEngineBuilder builder{GetContext()};
1805  builder.SetDartEntrypoint("sendCreatePlatformViewMethod");
1806  auto engine = builder.Build();
1807 
1808  EngineModifier modifier{engine.get()};
1809  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1810 
1811  bool received_call = false;
1812 
1813  auto manager = std::make_unique<MockPlatformViewManager>(engine.get());
1814  EXPECT_CALL(*manager, AddPlatformView)
1815  .WillOnce([&](PlatformViewId id, std::string_view type_name) {
1816  received_call = true;
1817  return true;
1818  });
1819  modifier.SetPlatformViewPlugin(std::move(manager));
1820 
1821  engine->Run();
1822 
1823  while (!received_call) {
1824  engine->task_runner()->ProcessTasks();
1825  }
1826 }
1827 
1828 TEST_F(FlutterWindowsEngineTest, AddViewFailureDoesNotHang) {
1829  FlutterWindowsEngineBuilder builder{GetContext()};
1830  auto engine = builder.Build();
1831 
1832  EngineModifier modifier{engine.get()};
1833 
1834  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1835  modifier.embedder_api().AddView = MOCK_ENGINE_PROC(
1836  AddView,
1837  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
1838  const FlutterAddViewInfo* info) { return kInternalInconsistency; });
1839 
1840  ASSERT_TRUE(engine->Run());
1841 
1842  // Create the first view. This is the implicit view and isn't added to the
1843  // engine.
1844  auto implicit_window = std::make_unique<NiceMock<MockWindowBindingHandler>>();
1845 
1846  std::unique_ptr<FlutterWindowsView> implicit_view =
1847  engine->CreateView(std::move(implicit_window),
1848  /*is_sized_to_content=*/false, BoxConstraints(),
1849  /*allow_implicit_view=*/true);
1850 
1851  EXPECT_TRUE(implicit_view);
1852 
1853  // Create a second view. The embedder attempts to add it to the engine.
1854  auto second_window = std::make_unique<NiceMock<MockWindowBindingHandler>>();
1855 
1856  EXPECT_DEBUG_DEATH(
1857  engine->CreateView(std::move(second_window),
1858  /*is_sized_to_content=*/false, BoxConstraints(),
1859  /*allow_implicit_view=*/false),
1860  "FlutterEngineAddView returned an unexpected result");
1861 }
1862 
1863 TEST_F(FlutterWindowsEngineTest, RemoveViewFailureDoesNotHang) {
1864  FlutterWindowsEngineBuilder builder{GetContext()};
1865  builder.SetDartEntrypoint("sendCreatePlatformViewMethod");
1866  auto engine = builder.Build();
1867 
1868  EngineModifier modifier{engine.get()};
1869 
1870  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1871  modifier.embedder_api().RemoveView = MOCK_ENGINE_PROC(
1872  RemoveView,
1873  [](FLUTTER_API_SYMBOL(FlutterEngine) engine,
1874  const FlutterRemoveViewInfo* info) { return kInternalInconsistency; });
1875 
1876  ASSERT_TRUE(engine->Run());
1877  EXPECT_DEBUG_DEATH(engine->RemoveView(123),
1878  "FlutterEngineRemoveView returned an unexpected result");
1879 }
1880 
1882  auto& context = GetContext();
1883  WindowsConfigBuilder builder{context};
1884  builder.SetDartEntrypoint("mergedUIThread");
1885  builder.SetUIThreadPolicy(FlutterDesktopUIThreadPolicy::RunOnPlatformThread);
1886 
1887  std::optional<std::thread::id> ui_thread_id;
1888 
1889  auto native_entry =
1890  CREATE_FFI_LAMBDA([&]() { ui_thread_id = std::this_thread::get_id(); });
1891  context.AddFfiNativeFunction("Signal", native_entry);
1892 
1893  EnginePtr engine{builder.RunHeadless()};
1894  while (!ui_thread_id) {
1895  PumpMessage();
1896  }
1897  ASSERT_EQ(*ui_thread_id, std::this_thread::get_id());
1898 }
1899 
1900 TEST_F(FlutterWindowsEngineTest, OnViewFocusChangeRequest) {
1901  FlutterWindowsEngineBuilder builder{GetContext()};
1902  std::unique_ptr<FlutterWindowsEngine> engine = builder.Build();
1903  auto window_binding_handler =
1904  std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>();
1905  MockFlutterWindowsView view(engine.get(), std::move(window_binding_handler));
1906 
1907  EngineModifier modifier(engine.get());
1908  modifier.SetImplicitView(&view);
1909 
1910  FlutterViewFocusChangeRequest request;
1911  request.view_id = kImplicitViewId;
1912 
1913  EXPECT_CALL(view, Focus()).WillOnce(Return(true));
1914  modifier.OnViewFocusChangeRequest(&request);
1915 }
1916 
1917 TEST_F(FlutterWindowsEngineTest, UpdateSemanticsMultiView) {
1918  auto& context = GetContext();
1919  WindowsConfigBuilder builder{context};
1920  builder.SetDartEntrypoint("sendSemanticsTreeInfo");
1921 
1922  // Setup: a signal for when we have send out all of our semantics updates
1923  bool done = false;
1924  auto native_entry = CREATE_FFI_LAMBDA([&]() { done = true; });
1925  context.AddFfiNativeFunction("Signal", native_entry);
1926 
1927  // Setup: Create the engine and two views + enable semantics
1928  EnginePtr engine{builder.RunHeadless()};
1929  ASSERT_NE(engine, nullptr);
1930 
1931  auto window_binding_handler1 =
1932  std::make_unique<NiceMock<MockWindowBindingHandler>>();
1933  auto window_binding_handler2 =
1934  std::make_unique<NiceMock<MockWindowBindingHandler>>();
1935 
1936  // The following mocks are required by
1937  // FlutterWindowsView::CreateWindowMetricsEvent so that we create a valid
1938  // view.
1939  EXPECT_CALL(*window_binding_handler1, GetPhysicalWindowBounds)
1940  .WillRepeatedly(testing::Return(PhysicalWindowBounds{100, 100}));
1941  EXPECT_CALL(*window_binding_handler1, GetDpiScale)
1942  .WillRepeatedly(testing::Return(96.0));
1943  EXPECT_CALL(*window_binding_handler2, GetPhysicalWindowBounds)
1944  .WillRepeatedly(testing::Return(PhysicalWindowBounds{200, 200}));
1945  EXPECT_CALL(*window_binding_handler2, GetDpiScale)
1946  .WillRepeatedly(testing::Return(96.0));
1947 
1948  auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
1949  EngineModifier modifier{windows_engine};
1950  modifier.embedder_api().RunsAOTCompiledDartCode = []() { return false; };
1951 
1952  // We want to avoid adding an implicit view as the first view
1953  modifier.SetNextViewId(kImplicitViewId + 1);
1954 
1955  auto view1 = windows_engine->CreateView(std::move(window_binding_handler1),
1956  /*is_sized_to_content=*/false,
1957  BoxConstraints(),
1958  /*allow_implicit_view=*/false);
1959  auto view2 = windows_engine->CreateView(std::move(window_binding_handler2),
1960  /*is_sized_to_content=*/false,
1961  BoxConstraints(),
1962  /*allow_implicit_view=*/false);
1963 
1964  // Act: UpdateSemanticsEnabled will trigger the semantics updates
1965  // to get sent.
1966  windows_engine->UpdateSemanticsEnabled(true);
1967 
1968  while (!done) {
1969  windows_engine->task_runner()->ProcessTasks();
1970  }
1971 
1972  auto accessibility_bridge1 = view1->accessibility_bridge().lock();
1973  auto accessibility_bridge2 = view2->accessibility_bridge().lock();
1974 
1975  // Expect: that the semantics trees are updated with their
1976  // respective nodes.
1977  while (
1978  !accessibility_bridge1->GetPlatformNodeFromTree(view1->view_id() + 1)) {
1979  windows_engine->task_runner()->ProcessTasks();
1980  }
1981 
1982  while (
1983  !accessibility_bridge2->GetPlatformNodeFromTree(view2->view_id() + 1)) {
1984  windows_engine->task_runner()->ProcessTasks();
1985  }
1986 
1987  // Rely on timeout mechanism in CI.
1988  auto tree1 = accessibility_bridge1->GetTree();
1989  auto tree2 = accessibility_bridge2->GetTree();
1990  EXPECT_NE(tree1->GetFromId(view1->view_id() + 1), nullptr);
1991  EXPECT_NE(tree2->GetFromId(view2->view_id() + 1), nullptr);
1992 }
1993 
1994 } // namespace testing
1995 } // namespace flutter
FlutterDesktopMessengerRef messenger()
WindowsLifecycleManager * lifecycle_manager()
WindowProcDelegateManager * window_proc_delegate_manager()
std::optional< LRESULT > ProcessExternalWindowMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
std::unique_ptr< FlutterWindowsView > CreateView(std::unique_ptr< WindowBindingHandler > window, bool is_sized_to_content, const BoxConstraints &box_constraints, bool allow_implicit_view, FlutterWindowsViewSizingDelegate *sizing_delegate=nullptr)
virtual void RemoveView(FlutterViewId view_id)
std::chrono::nanoseconds ProcessTasks()
Definition: task_runner.cc:25
std::optional< LRESULT > OnTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) const
void RegisterTopLevelWindowProcDelegate(FlutterDesktopWindowProcCallback callback, void *user_data)
virtual void OnWindowStateEvent(HWND hwnd, WindowStateEvent event)
std::optional< LRESULT > ExternalWindowMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
virtual void Quit(std::optional< HWND > window, std::optional< WPARAM > wparam, std::optional< LPARAM > lparam, UINT exit_code)
virtual void DispatchMessage(HWND window, UINT msg, WPARAM wparam, LPARAM lparam)
virtual void SetLifecycleState(AppLifecycleState state)
MOCK_METHOD(bool, Focus,(),(override))
MOCK_METHOD(void, NotifyWinEventWrapper,(ui::AXPlatformNodeWin *, ax::mojom::Event),(override))
MockFlutterWindowsView(FlutterWindowsEngine *engine, std::unique_ptr< WindowBindingHandler > wbh)
MOCK_METHOD(HWND, GetWindowHandle,(),(const, override))
MOCK_METHOD(void, DispatchMessage,(HWND, UINT, WPARAM, LPARAM),(override))
MOCK_METHOD(void, Quit,(std::optional< HWND >, std::optional< WPARAM >, std::optional< LPARAM >, UINT),(override))
MOCK_METHOD(void, SetLifecycleState,(AppLifecycleState),(override))
MOCK_METHOD(bool, IsLastWindowOfProcess,(),(override))
std::vector< FlutterEngineDisplay > * displays
void(* FlutterDesktopBinaryReply)(const uint8_t *data, size_t data_size, void *user_data)
FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine(FlutterDesktopViewControllerRef ref)
@ RunOnPlatformThread
@ DefaultImpeller
@ EnabledImpeller
@ DisabledImpeller
int64_t PlatformViewId
FlutterDesktopBinaryReply callback
Win32Message message
TEST_F(AccessibilityPluginTest, DirectAnnounceCall)
UINT GetDpiForMonitor(HMONITOR monitor)
Definition: dpi_utils.cc:132
std::function< void(const uint8_t *reply, size_t reply_size)> BinaryReply
static void WindowsPlatformThreadPrioritySetter(FlutterThreadPriority priority)
constexpr FlutterViewId kImplicitViewId