Flutter Windows Embedder
host_window.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 
11 
12 #include <dwmapi.h>
13 
21 
22 namespace {
23 
24 constexpr wchar_t kWindowClassName[] = L"FLUTTER_HOST_WINDOW";
25 
26 // Clamps |size| to the size of the virtual screen. Both the parameter and
27 // return size are in physical coordinates.
28 flutter::Size ClampToVirtualScreen(flutter::Size size) {
29  double const virtual_screen_width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
30  double const virtual_screen_height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
31 
32  return flutter::Size(std::clamp(size.width(), 0.0, virtual_screen_width),
33  std::clamp(size.height(), 0.0, virtual_screen_height));
34 }
35 
36 // Retrieves the calling thread's last-error code message as a string,
37 // or a fallback message if the error message cannot be formatted.
38 std::string GetLastErrorAsString() {
39  LPWSTR message_buffer = nullptr;
40 
41  if (DWORD const size = FormatMessage(
42  FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
43  FORMAT_MESSAGE_IGNORE_INSERTS,
44  nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
45  reinterpret_cast<LPTSTR>(&message_buffer), 0, nullptr)) {
46  std::wstring const wide_message(message_buffer, size);
47  LocalFree(message_buffer);
48  message_buffer = nullptr;
49 
50  if (int const buffer_size =
51  WideCharToMultiByte(CP_UTF8, 0, wide_message.c_str(), -1, nullptr,
52  0, nullptr, nullptr)) {
53  std::string message(buffer_size, 0);
54  WideCharToMultiByte(CP_UTF8, 0, wide_message.c_str(), -1, &message[0],
55  buffer_size, nullptr, nullptr);
56  return message;
57  }
58  }
59 
60  if (message_buffer) {
61  LocalFree(message_buffer);
62  }
63  std::ostringstream oss;
64  oss << "Format message failed with 0x" << std::hex << std::setfill('0')
65  << std::setw(8) << GetLastError();
66  return oss.str();
67 }
68 
69 // Checks whether the window class of name |class_name| is registered for the
70 // current application.
71 bool IsClassRegistered(LPCWSTR class_name) {
72  WNDCLASSEX window_class = {};
73  return GetClassInfoEx(GetModuleHandle(nullptr), class_name, &window_class) !=
74  0;
75 }
76 
77 // Window attribute that enables dark mode window decorations.
78 //
79 // Redefined in case the developer's machine has a Windows SDK older than
80 // version 10.0.22000.0.
81 // See:
82 // https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
83 #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
84 #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
85 #endif
86 
87 // Updates the window frame's theme to match the system theme.
88 void UpdateTheme(HWND window) {
89  // Registry key for app theme preference.
90  const wchar_t kGetPreferredBrightnessRegKey[] =
91  L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
92  const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
93 
94  // A value of 0 indicates apps should use dark mode. A non-zero or missing
95  // value indicates apps should use light mode.
96  DWORD light_mode;
97  DWORD light_mode_size = sizeof(light_mode);
98  LSTATUS const result =
99  RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
100  kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD, nullptr,
101  &light_mode, &light_mode_size);
102 
103  if (result == ERROR_SUCCESS) {
104  BOOL enable_dark_mode = light_mode == 0;
105  DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
106  &enable_dark_mode, sizeof(enable_dark_mode));
107  }
108 }
109 
110 // Inserts |content| into the window tree.
111 void SetChildContent(HWND content, HWND window) {
112  SetParent(content, window);
113  RECT client_rect;
114  GetClientRect(window, &client_rect);
115  MoveWindow(content, client_rect.left, client_rect.top,
116  client_rect.right - client_rect.left,
117  client_rect.bottom - client_rect.top, true);
118 }
119 
120 // Adjusts a 1D segment (defined by origin and size) to fit entirely within
121 // a destination segment. If the segment is larger than the destination, it is
122 // first shrunk to fit. Then, it's shifted to be within the bounds.
123 //
124 // Let the destination be "{...}" and the segment to adjust be "[...]".
125 //
126 // Case 1: The segment sticks out to the right.
127 //
128 // Before: {------[----}------]
129 // After: {------[----]}
130 //
131 // Case 2: The segment sticks out to the left.
132 //
133 // Before: [------{----]------}
134 // After: {[----]------}
135 void AdjustAlongAxis(LONG dst_origin, LONG dst_size, LONG* origin, LONG* size) {
136  *size = std::min(dst_size, *size);
137  if (*origin < dst_origin)
138  *origin = dst_origin;
139  else
140  *origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
141 }
142 
143 RECT AdjustToFit(const RECT& parent, const RECT& child) {
144  auto new_x = child.left;
145  auto new_y = child.top;
146  auto new_width = flutter::RectWidth(child);
147  auto new_height = flutter::RectHeight(child);
148  AdjustAlongAxis(parent.left, flutter::RectWidth(parent), &new_x, &new_width);
149  AdjustAlongAxis(parent.top, flutter::RectHeight(parent), &new_y, &new_height);
150  RECT result;
151  result.left = new_x;
152  result.right = new_x + new_width;
153  result.top = new_y;
154  result.bottom = new_y + new_height;
155  return result;
156 }
157 
158 flutter::BoxConstraints FromWindowConstraints(
159  const flutter::WindowConstraints& preferred_constraints) {
160  std::optional<flutter::Size> smallest, biggest;
161  if (preferred_constraints.has_view_constraints) {
162  smallest = flutter::Size(preferred_constraints.view_min_width,
163  preferred_constraints.view_min_height);
164  if (preferred_constraints.view_max_width > 0 &&
165  preferred_constraints.view_max_height > 0) {
166  biggest = flutter::Size(preferred_constraints.view_max_width,
167  preferred_constraints.view_max_height);
168  }
169  }
170 
171  return flutter::BoxConstraints(smallest, biggest);
172 }
173 
174 } // namespace
175 
176 namespace flutter {
177 
178 std::unique_ptr<HostWindow> HostWindow::CreateRegularWindow(
179  WindowManager* window_manager,
180  FlutterWindowsEngine* engine,
181  const WindowSizeRequest& preferred_size,
182  const WindowConstraints& preferred_constraints,
183  LPCWSTR title,
184  bool sized_to_content,
185  bool resizable) {
186  return std::unique_ptr<HostWindow>(
187  new HostWindowRegular(window_manager, engine, preferred_size,
188  FromWindowConstraints(preferred_constraints), title,
189  sized_to_content, resizable));
190 }
191 
192 std::unique_ptr<HostWindow> HostWindow::CreateDialogWindow(
193  WindowManager* window_manager,
194  FlutterWindowsEngine* engine,
195  const WindowSizeRequest& preferred_size,
196  const WindowConstraints& preferred_constraints,
197  LPCWSTR title,
198  HWND parent,
199  bool sized_to_content,
200  bool resizable) {
201  return std::unique_ptr<HostWindow>(new HostWindowDialog(
202  window_manager, engine, preferred_size,
203  FromWindowConstraints(preferred_constraints), title,
204  parent ? parent : std::optional<HWND>(), sized_to_content, resizable));
205 }
206 
207 std::unique_ptr<HostWindow> HostWindow::CreateTooltipWindow(
208  WindowManager* window_manager,
209  FlutterWindowsEngine* engine,
210  const WindowConstraints& preferred_constraints,
211  GetWindowPositionCallback get_position_callback,
212  HWND parent) {
213  return std::unique_ptr<HostWindowTooltip>(new HostWindowTooltip(
214  window_manager, engine, FromWindowConstraints(preferred_constraints),
215  get_position_callback, parent));
216 }
217 
218 std::unique_ptr<HostWindow> HostWindow::CreatePopupWindow(
219  WindowManager* window_manager,
220  FlutterWindowsEngine* engine,
221  const WindowConstraints& preferred_constraints,
222  GetWindowPositionCallback get_position_callback,
223  HWND parent) {
224  return std::unique_ptr<HostWindowPopup>(new HostWindowPopup(
225  window_manager, engine, FromWindowConstraints(preferred_constraints),
226  get_position_callback, parent));
227 }
228 
229 std::unique_ptr<HostWindow> HostWindow::CreateSatelliteWindow(
230  WindowManager* window_manager,
231  FlutterWindowsEngine* engine,
232  const WindowSizeRequest& preferred_size,
233  const WindowConstraints& preferred_constraints,
234  GetWindowPositionCallback get_position_callback,
235  HWND parent,
236  LPCWSTR title,
237  bool sized_to_content,
238  bool resizable) {
239  return std::unique_ptr<HostWindowSatellite>(new HostWindowSatellite(
240  window_manager, engine, preferred_size,
241  FromWindowConstraints(preferred_constraints), get_position_callback,
242  parent, title, sized_to_content, resizable));
243 }
244 
246  FlutterWindowsEngine* engine)
247  : window_manager_(window_manager), engine_(engine) {}
248 
250  HostWindowInitializationParams const& params) {
251  // Set up the view.
252  auto view_window = std::make_unique<FlutterWindow>(
253  params.initial_window_rect.width(), params.initial_window_rect.height(),
255 
256  std::unique_ptr<FlutterWindowsView> view =
257  engine_->CreateView(std::move(view_window), params.is_sized_to_content,
258  params.box_constraints, /*allow_implicit_view=*/false,
259  params.sizing_delegate);
260  FML_CHECK(view != nullptr);
261 
263  std::make_unique<FlutterWindowsViewController>(nullptr, std::move(view));
264  FML_CHECK(engine_->running());
265  // The Windows embedder listens to accessibility updates using the
266  // view's HWND. The embedder's accessibility features may be stale if
267  // the app was in headless mode.
269 
270  // Register the window class.
271  if (!IsClassRegistered(kWindowClassName)) {
272  auto const idi_app_icon = 101;
273  WNDCLASSEX window_class = {};
274  window_class.cbSize = sizeof(WNDCLASSEX);
275  window_class.style = CS_HREDRAW | CS_VREDRAW;
276  window_class.lpfnWndProc = HostWindow::WndProc;
277  window_class.hInstance = GetModuleHandle(nullptr);
278  window_class.hIcon =
279  LoadIcon(window_class.hInstance, MAKEINTRESOURCE(idi_app_icon));
280  if (!window_class.hIcon) {
281  window_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
282  }
283  window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
284  window_class.lpszClassName = kWindowClassName;
285 
286  FML_CHECK(RegisterClassEx(&window_class));
287  }
288 
289  // Create the native window.
290  window_handle_ = CreateWindowEx(
291  params.extended_window_style, kWindowClassName, params.title,
292  params.window_style, params.initial_window_rect.left(),
293  params.initial_window_rect.top(), params.initial_window_rect.width(),
294  params.initial_window_rect.height(),
295  params.owner_window ? *params.owner_window : nullptr, nullptr,
296  GetModuleHandle(nullptr), engine_->windows_proc_table().get());
297  FML_CHECK(window_handle_ != nullptr);
298 
299  // Adjust the window position so its origin aligns with the top-left corner
300  // of the window frame, not the window rectangle (which includes the
301  // drop-shadow). This adjustment must be done post-creation since the frame
302  // rectangle is only available after the window has been created.
304 
305  UpdateTheme(window_handle_);
306 
307  SetChildContent(view_controller_->view()->GetWindowHandle(), window_handle_);
308 
309  // Defer showing the window until the first frame is rendered so the user
310  // doesn't see a blank window. Each view has its own first-frame callback,
311  // so this works correctly for multi-window apps.
312  view_controller_->view()->SetFirstFrameCallback(
313  [this, weak_alive = std::weak_ptr<int>(alive_), hwnd = window_handle_,
314  cmd_show = params.nCmdShow]() {
315  if (weak_alive.expired() || !::IsWindow(hwnd)) {
316  return;
317  }
318  OnFirstFrame();
319  ShowWindow(hwnd, cmd_show);
320  });
321  archetype_ = params.archetype;
322  SetWindowLongPtr(window_handle_, GWLP_USERDATA,
323  reinterpret_cast<LONG_PTR>(this));
324 }
325 
326 void HostWindow::OnFirstFrame() {}
327 
328 void HostWindow::AlignOriginWithFrame() {
329  RECT frame_rect;
330  if (FAILED(DwmGetWindowAttribute(window_handle_, DWMWA_EXTENDED_FRAME_BOUNDS,
331  &frame_rect, sizeof(frame_rect)))) {
332  return;
333  }
334  RECT window_rect;
335  if (!GetWindowRect(window_handle_, &window_rect)) {
336  return;
337  }
338 
339  LONG const left_dropshadow_width = frame_rect.left - window_rect.left;
340  LONG const top_dropshadow_height = window_rect.top - frame_rect.top;
341  if (left_dropshadow_width == 0 && top_dropshadow_height == 0) {
342  return;
343  }
344 
345  SetWindowPos(window_handle_, nullptr,
346  window_rect.left - left_dropshadow_width,
347  window_rect.top - top_dropshadow_height, 0, 0,
348  SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE);
349 }
350 
351 HostWindow::~HostWindow() {
352  if (view_controller_) {
353  // Unregister the window class. Fail silently if other windows are still
354  // using the class, as only the last window can successfully unregister it.
355  if (!UnregisterClass(kWindowClassName, GetModuleHandle(nullptr))) {
356  // Clear the error state after the failed unregistration.
357  SetLastError(ERROR_SUCCESS);
358  }
359  }
360 }
361 
362 HostWindow* HostWindow::GetThisFromHandle(HWND hwnd) {
363  wchar_t class_name[256];
364  if (!GetClassName(hwnd, class_name, sizeof(class_name) / sizeof(wchar_t))) {
365  FML_LOG(ERROR) << "Failed to get class name for window handle " << hwnd
366  << ": " << GetLastErrorAsString();
367  return nullptr;
368  }
369  // Ignore window handles that do not match the expected class name.
370  if (wcscmp(class_name, kWindowClassName) != 0) {
371  return nullptr;
372  }
373 
374  return reinterpret_cast<HostWindow*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
375 }
376 
377 HWND HostWindow::GetWindowHandle() const {
378  return window_handle_;
379 }
380 
381 HWND HostWindow::GetFlutterViewWindowHandle() const {
382  return view_controller_->view()->GetWindowHandle();
383 }
384 
385 void HostWindow::FocusRootViewOf(HostWindow* window) {
386  auto child_content = window->view_controller_->view()->GetWindowHandle();
387  if (window != nullptr && child_content != nullptr) {
388  SetFocus(child_content);
389  }
390 };
391 
392 void HostWindow::HandleWindowActivation(HWND hwnd, WPARAM wparam) {
393  if (LOWORD(wparam) == WA_INACTIVE) {
394  // The window is being deactivated; leave focus untouched. Focusing this
395  // window's view would call SetFocus on its content, which reactivates the
396  // window (SetFocus activates the parent of the focused window) and pulls it
397  // back to the top of the z-order, taking activation from the window that is
398  // being activated.
399  return;
400  }
401 
402  if (!IsWindowEnabled(hwnd)) {
403  // Prevent a disabled window (e.g. the owner of a modal dialog) from being
404  // activated using the task switcher by redirecting focus and activation to
405  // the first enabled descendant.
406  if (HostWindow* const enabled_descendant = FindFirstEnabledDescendant()) {
407  SetActiveWindow(enabled_descendant->GetWindowHandle());
408  FocusRootViewOf(this);
409  }
410  return;
411  }
412 
413  FocusRootViewOf(this);
414 }
415 
416 LRESULT HostWindow::WndProc(HWND hwnd,
417  UINT message,
418  WPARAM wparam,
419  LPARAM lparam) {
420  if (message == WM_NCCREATE) {
421  auto* const create_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
422  auto* const windows_proc_table =
423  static_cast<WindowsProcTable*>(create_struct->lpCreateParams);
424  windows_proc_table->EnableNonClientDpiScaling(hwnd);
425  } else if (HostWindow* const window = GetThisFromHandle(hwnd)) {
426  return window->HandleMessage(hwnd, message, wparam, lparam);
427  }
428 
429  return DefWindowProc(hwnd, message, wparam, lparam);
430 }
431 
432 LRESULT HostWindow::HandleMessage(HWND hwnd,
433  UINT message,
434  WPARAM wparam,
435  LPARAM lparam) {
436  auto result = engine_->window_proc_delegate_manager()->OnTopLevelWindowProc(
437  window_handle_, message, wparam, lparam);
438  if (result) {
439  return *result;
440  }
441 
442  switch (message) {
443  case WM_DESTROY:
444  is_being_destroyed_ = true;
445  break;
446 
447  case WM_NCLBUTTONDOWN: {
448  // Fix for 500ms hang after user clicks on the title bar, but before
449  // moving mouse. Reference:
450  // https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
451  if (SendMessage(window_handle_, WM_NCHITTEST, wparam, lparam) ==
452  HTCAPTION) {
453  POINT cursorPos;
454  // Get the current cursor position and synthesize WM_MOUSEMOVE to
455  // unblock default window proc implementation for WM_NCLBUTTONDOWN at
456  // HTCAPTION.
457  GetCursorPos(&cursorPos);
458  ScreenToClient(window_handle_, &cursorPos);
459  PostMessage(window_handle_, WM_MOUSEMOVE, 0,
460  MAKELPARAM(cursorPos.x, cursorPos.y));
461  }
462  break;
463  }
464 
465  case WM_DPICHANGED: {
466  auto* const new_scaled_window_rect = reinterpret_cast<RECT*>(lparam);
467  LONG const width =
468  new_scaled_window_rect->right - new_scaled_window_rect->left;
469  LONG const height =
470  new_scaled_window_rect->bottom - new_scaled_window_rect->top;
471  SetWindowPos(hwnd, nullptr, new_scaled_window_rect->left,
472  new_scaled_window_rect->top, width, height,
473  SWP_NOZORDER | SWP_NOACTIVATE);
474  return 0;
475  }
476 
477  case WM_GETMINMAXINFO: {
478  RECT window_rect;
479  GetWindowRect(hwnd, &window_rect);
480  RECT client_rect;
481  GetClientRect(hwnd, &client_rect);
482  LONG const non_client_width = (window_rect.right - window_rect.left) -
483  (client_rect.right - client_rect.left);
484  LONG const non_client_height = (window_rect.bottom - window_rect.top) -
485  (client_rect.bottom - client_rect.top);
486 
487  UINT const dpi = flutter::GetDpiForHWND(hwnd);
488  double const scale_factor =
489  static_cast<double>(dpi) / USER_DEFAULT_SCREEN_DPI;
490 
491  MINMAXINFO* info = reinterpret_cast<MINMAXINFO*>(lparam);
492  Size const min_physical_size = ClampToVirtualScreen(Size(
493  box_constraints_.smallest().width() * scale_factor + non_client_width,
494  box_constraints_.smallest().height() * scale_factor +
495  non_client_height));
496 
497  info->ptMinTrackSize.x = min_physical_size.width();
498  info->ptMinTrackSize.y = min_physical_size.height();
499  Size const max_physical_size = ClampToVirtualScreen(Size(
500  box_constraints_.biggest().width() * scale_factor + non_client_width,
501  box_constraints_.biggest().height() * scale_factor +
502  non_client_height));
503 
504  info->ptMaxTrackSize.x = max_physical_size.width();
505  info->ptMaxTrackSize.y = max_physical_size.height();
506  return 0;
507  }
508 
509  case WM_SIZE: {
510  auto child_content = view_controller_->view()->GetWindowHandle();
511  if (child_content != nullptr) {
512  // Resize and reposition the child content window.
513  RECT client_rect;
514  GetClientRect(hwnd, &client_rect);
515  MoveWindow(child_content, client_rect.left, client_rect.top,
516  client_rect.right - client_rect.left,
517  client_rect.bottom - client_rect.top, TRUE);
518  }
519  return 0;
520  }
521 
522  case WM_ACTIVATE:
523  HandleWindowActivation(hwnd, wparam);
524  return 0;
525 
526  case WM_WINDOWPOSCHANGED: {
527  // Satellites are anchored to this window's client area, which can move
528  // even if the window itself does not (e.g. when a DPI change resizes the
529  // title bar).
530  auto const* const window_pos = reinterpret_cast<WINDOWPOS*>(lparam);
531  UINT const kNoClientChange = SWP_NOMOVE | SWP_NOSIZE;
532  if (window_pos &&
533  ((window_pos->flags & kNoClientChange) != kNoClientChange ||
534  (window_pos->flags & SWP_FRAMECHANGED))) {
535  for (HostWindow* const owned : GetOwnedWindows()) {
536  if (owned->GetArchetype() == WindowArchetype::kSatellite) {
537  static_cast<HostWindowSatellite*>(owned)->OnParentMoved();
538  }
539  }
540  }
541  break;
542  }
543 
544  case WM_DWMCOLORIZATIONCOLORCHANGED:
545  UpdateTheme(hwnd);
546  return 0;
547 
548  default:
549  break;
550  }
551 
552  if (!view_controller_) {
553  return 0;
554  }
555 
556  return DefWindowProc(hwnd, message, wparam, lparam);
557 }
558 
559 void HostWindow::SetContentSize(const WindowSizeRequest& size) {
560  if (!size.has_preferred_view_size) {
561  return;
562  }
563 
564  if (GetFullscreen()) {
565  std::optional<Size> const window_size = GetWindowSizeForClientSize(
566  *engine_->windows_proc_table(),
568  box_constraints_.smallest(), box_constraints_.biggest(),
569  saved_window_info_.style, saved_window_info_.ex_style, nullptr);
570  if (!window_size) {
571  return;
572  }
573 
574  saved_window_info_.client_size =
576  .height = size.preferred_view_height};
577  saved_window_info_.rect.right =
578  saved_window_info_.rect.left + static_cast<LONG>(window_size->width());
579  saved_window_info_.rect.bottom =
580  saved_window_info_.rect.top + static_cast<LONG>(window_size->height());
581  } else {
582  WINDOWINFO window_info = {.cbSize = sizeof(WINDOWINFO)};
583  GetWindowInfo(window_handle_, &window_info);
584 
585  std::optional<Size> const window_size = GetWindowSizeForClientSize(
586  *engine_->windows_proc_table(),
588  box_constraints_.smallest(), box_constraints_.biggest(),
589  window_info.dwStyle, window_info.dwExStyle, nullptr);
590 
591  if (!window_size) {
592  return;
593  }
594 
595  SetWindowPos(window_handle_, NULL, 0, 0, window_size->width(),
596  window_size->height(),
597  SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
598  }
599 }
600 
601 void HostWindow::SetConstraints(const WindowConstraints& constraints) {
602  box_constraints_ = FromWindowConstraints(constraints);
603 
604  if (GetFullscreen()) {
605  std::optional<Size> const window_size = GetWindowSizeForClientSize(
606  *engine_->windows_proc_table(),
607  Size(saved_window_info_.client_size.width,
608  saved_window_info_.client_size.height),
609  box_constraints_.smallest(), box_constraints_.biggest(),
610  saved_window_info_.style, saved_window_info_.ex_style, nullptr);
611  if (!window_size) {
612  return;
613  }
614 
615  saved_window_info_.rect.right =
616  saved_window_info_.rect.left + static_cast<LONG>(window_size->width());
617  saved_window_info_.rect.bottom =
618  saved_window_info_.rect.top + static_cast<LONG>(window_size->height());
619  } else {
620  auto const client_size = GetWindowContentSize(window_handle_);
621  auto const current_size = Size(client_size.width, client_size.height);
622  WINDOWINFO window_info = {.cbSize = sizeof(WINDOWINFO)};
623  GetWindowInfo(window_handle_, &window_info);
624  std::optional<Size> const window_size = GetWindowSizeForClientSize(
625  *engine_->windows_proc_table(), current_size,
626  box_constraints_.smallest(), box_constraints_.biggest(),
627  window_info.dwStyle, window_info.dwExStyle, nullptr);
628 
629  if (window_size && current_size != window_size) {
630  SetWindowPos(window_handle_, NULL, 0, 0, window_size->width(),
631  window_size->height(),
632  SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
633  }
634  }
635 }
636 
637 // The fullscreen method is largely adapted from the method found in chromium:
638 // See:
639 //
640 // * https://chromium.googlesource.com/chromium/src/+/refs/heads/main/ui/views/win/fullscreen_handler.h
641 // * https://chromium.googlesource.com/chromium/src/+/refs/heads/main/ui/views/win/fullscreen_handler.cc
642 void HostWindow::SetFullscreen(
643  bool fullscreen,
644  std::optional<FlutterEngineDisplayId> display_id) {
645  if (fullscreen == GetFullscreen()) {
646  return;
647  }
648 
649  if (fullscreen) {
650  WINDOWINFO window_info = {.cbSize = sizeof(WINDOWINFO)};
651  GetWindowInfo(window_handle_, &window_info);
652  saved_window_info_.style = window_info.dwStyle;
653  saved_window_info_.ex_style = window_info.dwExStyle;
654  // Store the original window rect, DPI, and monitor info to detect changes
655  // and more accurately restore window placements when exiting fullscreen.
656  ::GetWindowRect(window_handle_, &saved_window_info_.rect);
657  saved_window_info_.client_size = GetWindowContentSize(window_handle_);
658  saved_window_info_.dpi = GetDpiForHWND(window_handle_);
659  saved_window_info_.monitor =
660  MonitorFromWindow(window_handle_, MONITOR_DEFAULTTONEAREST);
661  saved_window_info_.monitor_info.cbSize =
662  sizeof(saved_window_info_.monitor_info);
663  GetMonitorInfo(saved_window_info_.monitor,
664  &saved_window_info_.monitor_info);
665  }
666 
667  if (fullscreen) {
668  // Next, get the raw HMONITOR that we want to be fullscreened on
669  HMONITOR monitor =
670  MonitorFromWindow(window_handle_, MONITOR_DEFAULTTONEAREST);
671  if (display_id) {
672  if (auto const display =
673  engine_->display_manager()->FindById(display_id.value())) {
674  monitor = reinterpret_cast<HMONITOR>(display->display_id);
675  }
676  }
677 
678  MONITORINFO monitor_info;
679  monitor_info.cbSize = sizeof(monitor_info);
680  if (!GetMonitorInfo(monitor, &monitor_info)) {
681  FML_LOG(ERROR) << "Cannot set window fullscreen because the monitor info "
682  "was not found";
683  }
684 
685  auto const width = RectWidth(monitor_info.rcMonitor);
686  auto const height = RectHeight(monitor_info.rcMonitor);
687  WINDOWINFO window_info = {.cbSize = sizeof(WINDOWINFO)};
688  GetWindowInfo(window_handle_, &window_info);
689 
690  // Set new window style and size.
691  SetWindowLong(window_handle_, GWL_STYLE,
692  saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME));
693  SetWindowLong(
694  window_handle_, GWL_EXSTYLE,
695  saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE |
696  WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
697 
698  // We call SetWindowPos first to set the window flags immediately. This
699  // makes it so that the WM_GETMINMAXINFO gets called with the correct window
700  // and content sizes.
701  SetWindowPos(window_handle_, NULL, 0, 0, 0, 0,
702  SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
703 
704  SetWindowPos(window_handle_, nullptr, monitor_info.rcMonitor.left,
705  monitor_info.rcMonitor.top, width, height,
706  SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
707  } else {
708  // Restore the window style and bounds saved prior to entering fullscreen.
709  // Use WS_VISIBLE for windows shown after SetFullscreen: crbug.com/1062251.
710  // Making multiple window adjustments here is ugly, but if SetWindowPos()
711  // doesn't redraw, the taskbar won't be repainted.
712  SetWindowLong(window_handle_, GWL_STYLE,
713  saved_window_info_.style | WS_VISIBLE);
714  SetWindowLong(window_handle_, GWL_EXSTYLE, saved_window_info_.ex_style);
715 
716  // We call SetWindowPos first to set the window flags immediately. This
717  // makes it so that the WM_GETMINMAXINFO gets called with the correct window
718  // and content sizes.
719  SetWindowPos(window_handle_, NULL, 0, 0, 0, 0,
720  SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
721 
722  HMONITOR monitor =
723  MonitorFromRect(&saved_window_info_.rect, MONITOR_DEFAULTTONEAREST);
724  MONITORINFO monitor_info;
725  monitor_info.cbSize = sizeof(monitor_info);
726  GetMonitorInfo(monitor, &monitor_info);
727 
728  auto window_rect = saved_window_info_.rect;
729 
730  // Adjust the window bounds to restore, if displays were disconnected,
731  // virtually rearranged, or otherwise changed metrics during fullscreen.
732  if (monitor != saved_window_info_.monitor ||
733  !AreRectsEqual(saved_window_info_.monitor_info.rcWork,
734  monitor_info.rcWork)) {
735  window_rect = AdjustToFit(monitor_info.rcWork, window_rect);
736  }
737 
738  auto const fullscreen_dpi = GetDpiForHWND(window_handle_);
739  SetWindowPos(window_handle_, nullptr, window_rect.left, window_rect.top,
740  RectWidth(window_rect), RectHeight(window_rect),
741  SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
742  auto const final_dpi = GetDpiForHWND(window_handle_);
743  if (final_dpi != saved_window_info_.dpi || final_dpi != fullscreen_dpi) {
744  // Reissue SetWindowPos if the DPI changed from saved or fullscreen DPIs.
745  // The first call may misinterpret bounds spanning displays, if the
746  // fullscreen display's DPI does not match the target display's DPI.
747  //
748  // Scale and clamp the bounds if the final DPI changed from the saved DPI.
749  // This more accurately matches the original placement, while avoiding
750  // unexpected offscreen placement in a recongifured multi-screen space.
751  if (final_dpi != saved_window_info_.dpi) {
752  auto const scale =
753  final_dpi / static_cast<float>(saved_window_info_.dpi);
754  auto const width = static_cast<LONG>(scale * RectWidth(window_rect));
755  auto const height = static_cast<LONG>(scale * RectHeight(window_rect));
756  window_rect.right = window_rect.left + width;
757  window_rect.bottom = window_rect.top + height;
758  window_rect = AdjustToFit(monitor_info.rcWork, window_rect);
759  }
760 
761  SetWindowPos(window_handle_, nullptr, window_rect.left, window_rect.top,
762  RectWidth(window_rect), RectHeight(window_rect),
763  SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
764  }
765  }
766 
767  if (!task_bar_list_) {
768  HRESULT hr =
769  ::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER,
770  IID_PPV_ARGS(&task_bar_list_));
771  if (SUCCEEDED(hr) && FAILED(task_bar_list_->HrInit())) {
772  task_bar_list_ = nullptr;
773  }
774  }
775 
776  // As per MSDN marking the window as fullscreen should ensure that the
777  // taskbar is moved to the bottom of the Z-order when the fullscreen window
778  // is activated. If the window is not fullscreen, the Shell falls back to
779  // heuristics to determine how the window should be treated, which means
780  // that it could still consider the window as fullscreen. :(
781  if (task_bar_list_) {
782  task_bar_list_->MarkFullscreenWindow(window_handle_, !!fullscreen);
783  }
784 
785  is_fullscreen_ = fullscreen;
786 }
787 
788 bool HostWindow::GetFullscreen() const {
789  return is_fullscreen_;
790 }
791 
792 ActualWindowSize HostWindow::GetWindowContentSize(HWND hwnd) {
793  RECT rect;
794  GetClientRect(hwnd, &rect);
795  double const dpr = FlutterDesktopGetDpiForHWND(hwnd) /
796  static_cast<double>(USER_DEFAULT_SCREEN_DPI);
797  double const width = rect.right / dpr;
798  double const height = rect.bottom / dpr;
799  return {
800  .width = rect.right / dpr,
801  .height = rect.bottom / dpr,
802  };
803 }
804 
805 std::optional<Size> HostWindow::GetWindowSizeForClientSize(
806  WindowsProcTable const& win32,
807  Size const& client_size,
808  std::optional<Size> smallest,
809  std::optional<Size> biggest,
810  DWORD window_style,
811  DWORD extended_window_style,
812  std::optional<HWND> const& owner_hwnd) {
813  UINT const dpi = GetDpiForHWND(owner_hwnd ? *owner_hwnd : nullptr);
814  double const scale_factor =
815  static_cast<double>(dpi) / USER_DEFAULT_SCREEN_DPI;
816  RECT rect = {
817  .right = static_cast<LONG>(client_size.width() * scale_factor),
818  .bottom = static_cast<LONG>(client_size.height() * scale_factor)};
819 
820  if (!win32.AdjustWindowRectExForDpi(&rect, window_style, FALSE,
821  extended_window_style, dpi)) {
822  FML_LOG(ERROR) << "Failed to run AdjustWindowRectExForDpi: "
823  << GetLastErrorAsString();
824  return std::nullopt;
825  }
826 
827  double width = static_cast<double>(rect.right - rect.left);
828  double height = static_cast<double>(rect.bottom - rect.top);
829 
830  // Apply size constraints.
831  double const non_client_width = width - (client_size.width() * scale_factor);
832  double const non_client_height =
833  height - (client_size.height() * scale_factor);
834  if (smallest) {
835  flutter::Size min_physical_size = ClampToVirtualScreen(
836  flutter::Size(smallest->width() * scale_factor + non_client_width,
837  smallest->height() * scale_factor + non_client_height));
838  width = std::max(width, min_physical_size.width());
839  height = std::max(height, min_physical_size.height());
840  }
841  if (biggest) {
842  flutter::Size max_physical_size = ClampToVirtualScreen(
843  flutter::Size(biggest->width() * scale_factor + non_client_width,
844  biggest->height() * scale_factor + non_client_height));
845  width = std::min(width, max_physical_size.width());
846  height = std::min(height, max_physical_size.height());
847  }
848 
849  return flutter::Size{width, height};
850 }
851 
852 std::optional<Size> HostWindow::GetInitialWindowSize(
853  FlutterWindowsEngine* engine,
854  const WindowSizeRequest& preferred_size,
855  const BoxConstraints& constraints,
856  DWORD window_style,
857  DWORD extended_window_style,
858  std::optional<HWND> const& owner_window,
859  bool sized_to_content) {
860  double client_width;
861  double client_height;
862  if (sized_to_content) {
863  // Use the minimum constraint as the initial window size. The window will
864  // be resized to match the rendered content after the first frame.
865  client_width = std::max(1.0, constraints.smallest().width());
866  client_height = std::max(1.0, constraints.smallest().height());
867  } else {
868  client_width = preferred_size.preferred_view_width;
869  client_height = preferred_size.preferred_view_height;
870  }
871 
872  return GetWindowSizeForClientSize(
873  *engine->windows_proc_table(), Size(client_width, client_height),
874  constraints.smallest(), constraints.biggest(), window_style,
875  extended_window_style, owner_window);
876 }
877 
878 void HostWindow::EnableRecursively(bool enable) {
879  EnableWindow(window_handle_, enable);
880 
881  for (HostWindow* const owned : GetOwnedWindows()) {
882  owned->EnableRecursively(enable);
883  }
884 }
885 
886 HostWindow* HostWindow::FindFirstEnabledDescendant() const {
887  if (IsWindowEnabled(window_handle_)) {
888  return const_cast<HostWindow*>(this);
889  }
890 
891  for (HostWindow* const owned : GetOwnedWindows()) {
892  if (HostWindow* const result = owned->FindFirstEnabledDescendant()) {
893  return result;
894  }
895  }
896 
897  return nullptr;
898 }
899 
900 std::vector<HostWindow*> HostWindow::GetOwnedWindows() const {
901  std::vector<HostWindow*> owned_windows;
902  struct EnumData {
903  HWND owner_window_handle;
904  std::vector<HostWindow*>* owned_windows;
905  } data{window_handle_, &owned_windows};
906 
907  EnumWindows(
908  [](HWND hwnd, LPARAM lparam) -> BOOL {
909  auto* const data = reinterpret_cast<EnumData*>(lparam);
910  if (GetWindow(hwnd, GW_OWNER) == data->owner_window_handle) {
911  HostWindow* const window = GetThisFromHandle(hwnd);
912  if (window && !window->is_being_destroyed_) {
913  data->owned_windows->push_back(window);
914  }
915  }
916  return TRUE;
917  },
918  reinterpret_cast<LPARAM>(&data));
919 
920  return owned_windows;
921 }
922 
923 HostWindow* HostWindow::GetOwnerWindow() const {
924  if (HWND const owner_window_handle = GetWindow(GetWindowHandle(), GW_OWNER)) {
925  return GetThisFromHandle(owner_window_handle);
926  }
927  return nullptr;
928 };
929 
930 void HostWindow::DisableRecursively() {
931  // Disable the window itself.
932  EnableWindow(window_handle_, false);
933 
934  for (HostWindow* const owned : GetOwnedWindows()) {
935  owned->DisableRecursively();
936  }
937 }
938 
939 void HostWindow::UpdateModalStateLayer() {
940  auto children = GetOwnedWindows();
941 
942  if (children.empty()) {
943  // Leaf window in the active path, enable it.
944  EnableWindow(window_handle_, true);
945  } else {
946  // Non-leaf window in the active path, disable it and process children.
947  EnableWindow(window_handle_, false);
948 
949  // On same level of window hierarchy the most recently created window
950  // will remain enabled.
951  auto latest_child = *std::max_element(
952  children.begin(), children.end(), [](HostWindow* a, HostWindow* b) {
953  return a->view_controller_->view()->view_id() <
954  b->view_controller_->view()->view_id();
955  });
956 
957  for (HostWindow* const child : children) {
958  if (child == latest_child) {
959  child->UpdateModalStateLayer();
960  } else {
961  child->DisableRecursively();
962  }
963  }
964  }
965 }
966 
967 } // namespace flutter
std::shared_ptr< WindowsProcTable > windows_proc_table()
std::shared_ptr< DisplayManagerWin32 > display_manager()
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)
HWND GetWindowHandle() const
Definition: host_window.cc:377
static std::unique_ptr< HostWindow > CreatePopupWindow(WindowManager *window_manager, FlutterWindowsEngine *engine, const WindowConstraints &preferred_constraints, GetWindowPositionCallback get_position_callback, HWND parent)
Definition: host_window.cc:218
static std::unique_ptr< HostWindow > CreateDialogWindow(WindowManager *window_manager, FlutterWindowsEngine *engine, const WindowSizeRequest &preferred_size, const WindowConstraints &preferred_constraints, LPCWSTR title, HWND parent, bool sized_to_content, bool resizable)
Definition: host_window.cc:192
virtual void OnFirstFrame()
Definition: host_window.cc:326
void InitializeFlutterView(HostWindowInitializationParams const &params)
Definition: host_window.cc:249
std::unique_ptr< FlutterWindowsViewController > view_controller_
Definition: host_window.h:314
static LRESULT WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
Definition: host_window.cc:416
static std::unique_ptr< HostWindow > CreateTooltipWindow(WindowManager *window_manager, FlutterWindowsEngine *engine, const WindowConstraints &preferred_constraints, GetWindowPositionCallback get_position_callback, HWND parent)
Definition: host_window.cc:207
static std::unique_ptr< HostWindow > CreateSatelliteWindow(WindowManager *window_manager, FlutterWindowsEngine *engine, const WindowSizeRequest &preferred_size, const WindowConstraints &preferred_constraints, GetWindowPositionCallback get_position_callback, HWND parent, LPCWSTR title, bool sized_to_content, bool resizable)
Definition: host_window.cc:229
static std::unique_ptr< HostWindow > CreateRegularWindow(WindowManager *window_manager, FlutterWindowsEngine *engine, const WindowSizeRequest &preferred_size, const WindowConstraints &preferred_constraints, LPCWSTR title, bool sized_to_content, bool resizable)
Definition: host_window.cc:178
FlutterWindowsEngine * engine_
Definition: host_window.h:309
HostWindow(WindowManager *window_manager, FlutterWindowsEngine *engine)
Definition: host_window.cc:245
std::shared_ptr< int > alive_
Definition: host_window.h:319
HostWindow * FindFirstEnabledDescendant() const
Definition: host_window.cc:886
virtual BOOL AdjustWindowRectExForDpi(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi) const
virtual BOOL EnableNonClientDpiScaling(HWND hwnd) const
UINT FlutterDesktopGetDpiForHWND(HWND hwnd)
#define DWMWA_USE_IMMERSIVE_DARK_MODE
Definition: host_window.cc:84
union flutter::testing::@108::KeyboardChange::@0 content
Win32Message message
UINT GetDpiForHWND(HWND hwnd)
Definition: dpi_utils.cc:128
void(* GetWindowPositionCallback)(const WindowSize &child_size, const WindowRect &parent_rect, const WindowRect &display_rect, WindowRect &output_rect)
LONG RectWidth(const RECT &r)
Definition: rect_helper.h:11
bool AreRectsEqual(const RECT &a, const RECT &b)
Definition: rect_helper.h:19
LONG RectHeight(const RECT &r)
Definition: rect_helper.h:15
FlutterWindowsViewSizingDelegate * sizing_delegate
Definition: host_window.h:188