File: tab_dialog_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (407 lines) | stat: -rw-r--r-- 15,413 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/tabs/public/tab_dialog_manager.h"

#include <algorithm>
#include <memory>

#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/scoped_observation.h"
#include "chrome/browser/ui/browser_window/public/browser_window_interface.h"
#include "chrome/browser/ui/browser_window/public/desktop_browser_window_capabilities.h"
#include "chrome/browser/ui/tabs/public/tab_features.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "components/back_forward_cache/back_forward_cache_disable.h"
#include "components/tabs/public/tab_interface.h"
#include "components/web_modal/modal_dialog_host.h"
#include "components/web_modal/web_contents_modal_dialog_host.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/navigation_handle.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "ui/base/base_window.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/widget/native_widget.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/views/window/dialog_delegate.h"

#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#endif

namespace constrained_window {
extern const void* kConstrainedWindowWidgetIdentifier;
}  // namespace constrained_window

namespace tabs {

class TabDialogWidgetObserver : public views::WidgetObserver {
 public:
  TabDialogWidgetObserver(TabDialogManager* tab_dialog_manager,
                          views::Widget* widget);
  TabDialogWidgetObserver(const TabDialogWidgetObserver&) = delete;
  TabDialogWidgetObserver& operator=(const TabDialogWidgetObserver&) = delete;
  ~TabDialogWidgetObserver() override = default;

 private:
  // Overridden from WidgetObserver:
  void OnWidgetDestroyed(views::Widget* widget) override;

  raw_ptr<TabDialogManager> tab_dialog_manager_ = nullptr;
  base::ScopedObservation<views::Widget, views::WidgetObserver>
      tab_dialog_scoped_observation_{this};
};

TabDialogWidgetObserver::TabDialogWidgetObserver(
    TabDialogManager* tab_dialog_manager,
    views::Widget* widget)
    : tab_dialog_manager_(tab_dialog_manager) {
  tab_dialog_scoped_observation_.Observe(widget);
}

void TabDialogWidgetObserver::OnWidgetDestroyed(views::Widget* widget) {
  tab_dialog_scoped_observation_.Reset();
  tab_dialog_manager_->WidgetDestroyed(widget);
}

namespace {

bool SupportsGlobalScreenCoordinates() {
#if !BUILDFLAG(IS_OZONE)
  return true;
#else
  return ui::OzonePlatform::GetInstance()
      ->GetPlatformProperties()
      .supports_global_screen_coordinates;
#endif
}

bool PlatformClipsChildrenToViewport() {
#if BUILDFLAG(IS_LINUX)
  return true;
#else
  return false;
#endif
}

gfx::Rect GetModalDialogBounds(views::Widget* widget,
                               BrowserWindowInterface* host_browser_window,
                               const gfx::Size& size) {
  gfx::Point position =
      host_browser_window->GetWebContentsModalDialogHostForWindow()
          ->GetDialogPosition(size);

  if (widget->non_client_view()) {
    // Align the first row of pixels inside the border. This is the apparent top
    // of the dialog.
    position.set_y(position.y() -
                  widget->non_client_view()->frame_view()->GetInsets().top());
  }

  gfx::Rect dialog_bounds(position, size);

  if (widget->is_top_level() && SupportsGlobalScreenCoordinates()) {
    views::Widget* const host_widget =
        host_browser_window->TopContainer()->GetWidget();
    gfx::Rect dialog_screen_bounds =
        dialog_bounds +
        host_widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
    const gfx::Rect host_screen_bounds = host_widget->GetWindowBoundsInScreen();

    // The requested dialog bounds should never fall outside the bounds of the
    // transient parent.
    DCHECK(dialog_screen_bounds.Intersects(host_screen_bounds));

    // Adjust the dialog bound to ensure it remains visible on the display.
    const gfx::Rect display_work_area =
        host_widget->GetNearestDisplay().value().work_area();
    if (!display_work_area.Contains(dialog_screen_bounds)) {
      dialog_screen_bounds.AdjustToFit(display_work_area);
    }

    // For platforms that clip transient children to the viewport we must
    // maximize its bounds on the display whilst keeping it within the host
    // bounds to avoid viewport clipping.
    // In the case that the host window bounds do not have sufficient overlap
    // with the display, and the dialog cannot be shown in its entirety, this is
    // a recoverable state as users are still able to reposition the host window
    // back onto the display.
    if (PlatformClipsChildrenToViewport() &&
        !host_screen_bounds.Contains(dialog_screen_bounds)) {
      dialog_screen_bounds.AdjustToFit(host_screen_bounds);
    }

    // Readjust the position of the dialog.
    dialog_bounds.set_origin(dialog_screen_bounds.origin());
  }
  return dialog_bounds;
}

void UpdateModalDialogPosition(views::Widget* widget,
                               BrowserWindowInterface* host_browser_window,
                               const gfx::Size& size) {
  // Do not forcibly update the dialog widget position if it is being dragged.
  if (widget->HasCapture()) {
    return;
  }

  auto* host_view_widget = host_browser_window->TopContainer()->GetWidget();

  // If the host view's widget is minimized, don't update any positions.
  if (host_view_widget && host_view_widget->IsMinimized()) {
    return;
  }

  // If the host view is not backed by a Views::Widget, just update the widget
  // size. This can happen on MacViews under the Cocoa browser where the window
  // modal dialogs are displayed as sheets, and their position is managed by a
  // ConstrainedWindowSheetController instance.
  if (!host_view_widget) {
    widget->SetSize(size);
    return;
  }

  widget->SetBounds(GetModalDialogBounds(widget, host_browser_window, size));
}

void ConfigureDesiredBoundsDelegate(
    views::Widget* widget,
    BrowserWindowInterface* host_browser_window) {
  views::WidgetDelegate* delegate = widget->widget_delegate();
  // TODO(kylixrd): Audit other usages of this API and determine whether to make
  // it exclusive for use here. Currently used in BubbleDialogDelegate and
  // shouldn't ever be used for a tab-modal dialog.
  delegate->set_desired_bounds_delegate(base::BindRepeating(
      [](views::Widget* widget,
         BrowserWindowInterface* host_browser_window) -> gfx::Rect {
        return GetModalDialogBounds(
            widget, host_browser_window,
            widget->GetRootView()->GetPreferredSize({}));
      },
      widget, host_browser_window));
}

// The dialog widget should be visible if and only if the tab is in the
// foreground and activated, and the host window is not minimized.
bool GetDialogWidgetVisibility(bool activated, bool minimized) {
  return activated && !minimized;
}

}  // namespace

// Applies positioning changes from the browser window widget to the tracked
// Widget. This class relies on the assumption that it is scoped to the lifetime
// of a single tab, in a single browser, and that it will be destroyed
// before the tab moves between browser windows.
class BrowserWindowWidgetObserver : public views::WidgetObserver {
 public:
  BrowserWindowWidgetObserver(TabInterface* tab_interface,
                              views::Widget* dialog_widget)
      : tab_(tab_interface), dialog_widget_(dialog_widget) {
    CHECK(dialog_widget_);
    browser_window_widget_observation_.Observe(
        tab_->GetBrowserWindowInterface()->TopContainer()->GetWidget());
  }
  BrowserWindowWidgetObserver(const BrowserWindowWidgetObserver&) = delete;
  BrowserWindowWidgetObserver& operator=(const BrowserWindowWidgetObserver&) =
      delete;
  ~BrowserWindowWidgetObserver() override = default;

  // WidgetObserver:
  void OnWidgetBoundsChanged(views::Widget* widget,
                             const gfx::Rect& new_bounds) override {
    if (dialog_widget_->IsVisible()) {
      UpdateModalDialogPosition(
          dialog_widget_, tab_->GetBrowserWindowInterface(),
          dialog_widget_->GetRootView()->GetPreferredSize({}));
    }
  }

  void OnWidgetShowStateChanged(views::Widget* widget) override {
    bool minimized = widget->IsMinimized();
    bool activated = tab_->IsActivated();
    dialog_widget_->SetVisible(GetDialogWidgetVisibility(activated, minimized));
  }

 private:
  // The tab that owns this dialog manager.
  raw_ptr<TabInterface> tab_;

  // The widget being tracked.
  raw_ptr<views::Widget> dialog_widget_;

  base::ScopedObservation<views::Widget, views::WidgetObserver>
      browser_window_widget_observation_{this};
};

TabDialogManager::TabDialogManager(TabInterface* tab_interface)
    : content::WebContentsObserver(tab_interface->GetContents()),
      tab_interface_(tab_interface) {
  tab_did_enter_foreground_subscription_ =
      tab_interface_->RegisterDidActivate(base::BindRepeating(
          &TabDialogManager::TabDidEnterForeground, base::Unretained(this)));
  tab_will_enter_background_subscription_ =
      tab_interface_->RegisterWillDeactivate(base::BindRepeating(
          &TabDialogManager::TabWillEnterBackground, base::Unretained(this)));
  tab_will_detach_subscription_ =
      tab_interface_->RegisterWillDetach(base::BindRepeating(
          &TabDialogManager::TabWillDetach, base::Unretained(this)));
}

TabDialogManager::~TabDialogManager() = default;

std::unique_ptr<views::Widget> TabDialogManager::CreateTabScopedDialog(
    views::DialogDelegate* delegate) {
  DCHECK_EQ(ui::mojom::ModalType::kChild, delegate->GetModalType());
  views::Widget* host = GetHostWidget();
  CHECK(host);
  return base::WrapUnique(views::DialogDelegate::CreateDialogWidget(
      delegate, gfx::NativeWindow(), host->GetNativeView()));
}

void TabDialogManager::ShowDialog(views::Widget* widget,
                                  std::unique_ptr<Params> params) {
  widget_ = widget;
  params_ = std::move(params);
  auto* browser_window_interface = tab_interface_->GetBrowserWindowInterface();
  ConfigureDesiredBoundsDelegate(widget_.get(), browser_window_interface);
  UpdateModalDialogPosition(widget_.get(), browser_window_interface,
                            widget_->GetRootView()->GetPreferredSize({}));
  widget_->SetNativeWindowProperty(
      views::kWidgetIdentifierKey,
      const_cast<void*>(
          constrained_window::kConstrainedWindowWidgetIdentifier));
  if (params_->disable_input) {
    scoped_ignore_input_events_ =
        tab_interface_->GetContents()->IgnoreInputEvents(std::nullopt);
    tab_interface_->GetBrowserWindowInterface()
        ->capabilities()
        ->SetWebContentsBlocked(tab_interface_->GetContents(),
                                /*blocked=*/true);
  }
  tab_dialog_widget_observer_ =
      std::make_unique<TabDialogWidgetObserver>(this, widget_.get());
  showing_modal_ui_ = tab_interface_->ShowModalUI();
  browser_window_widget_observer_ =
      std::make_unique<BrowserWindowWidgetObserver>(tab_interface_,
                                                    widget_.get());
  bool minimized = browser_window_interface->GetWindow()->IsMinimized();
  bool activated = tab_interface_->IsActivated();
  widget_->Show();
  widget_->SetVisible(GetDialogWidgetVisibility(activated, minimized));
}

std::unique_ptr<views::Widget> TabDialogManager::CreateAndShowDialog(
    views::DialogDelegate* delegate,
    std::unique_ptr<Params> params) {
  auto widget = CreateTabScopedDialog(delegate);
  ShowDialog(widget.get(), std::move(params));
  return widget;
}

void TabDialogManager::CloseDialog() {
  if (widget_) {
    views::Widget* widget = widget_;

    // First reset all state tracked by this class.
    WidgetDestroyed(widget_);

    // Now destroy the Widget. We don't know whether destruction will be
    // synchronous or asynchronous, but we no longer hold any state at this
    // point so it doesn't matter.
    widget->Close();
  }
}

void TabDialogManager::WidgetDestroyed(views::Widget* widget) {
  CHECK_EQ(widget, widget_.get());
  widget_ = nullptr;
  showing_modal_ui_.reset();
  tab_dialog_widget_observer_.reset();
  scoped_ignore_input_events_.reset();
  browser_window_widget_observer_.reset();
  tab_interface_->GetBrowserWindowInterface()
      ->capabilities()
      ->SetWebContentsBlocked(tab_interface_->GetContents(), /*blocked=*/false);
}

views::Widget* TabDialogManager::GetHostWidget() const {
  return tab_interface_->GetBrowserWindowInterface()
      ->TopContainer()
      ->GetWidget();
}

void TabDialogManager::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!widget_) {
    return;
  }

  if (!navigation_handle->IsInPrimaryMainFrame() ||
      !navigation_handle->HasCommitted()) {
    return;
  }

  // Disable BFCache for the page which had any modal dialog open.
  // This prevents the page which has print, confirm form resubmission, http
  // password dialogs, etc. to go in to BFCache. We can't simply dismiss the
  // dialogs in the case, since they are requesting meaningful input from the
  // user that affects the loading or display of the content.
  content::BackForwardCache::DisableForRenderFrameHost(
      navigation_handle->GetPreviousRenderFrameHostId(),
      back_forward_cache::DisabledReason(
          back_forward_cache::DisabledReasonId::kModalDialog));

  // Close modal dialogs if necessary.
  bool different_site_navigation =
      !net::registry_controlled_domains::SameDomainOrHost(
          navigation_handle->GetPreviousPrimaryMainFrameURL(),
          navigation_handle->GetURL(),
          net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
  if (params_->close_on_navigate && different_site_navigation) {
    CloseDialog();
  }
}

void TabDialogManager::TabDidEnterForeground(TabInterface* tab_interface) {
  if (widget_) {
    UpdateModalDialogPosition(widget_.get(),
                              tab_interface_->GetBrowserWindowInterface(),
                              widget_->GetRootView()->GetPreferredSize({}));
    browser_window_widget_observer_ =
        std::make_unique<BrowserWindowWidgetObserver>(tab_interface_,
                                                      widget_.get());
    // Check if the tab was detached and dragged to a new browser window. This
    // ensures the widget is properly reparented.
    auto* parent_widget = GetHostWidget();
    if (parent_widget != widget_->parent()) {
      widget_->Reparent(parent_widget);
    }
    widget_->SetVisible(
        GetDialogWidgetVisibility(/*activated=*/true, widget_->IsMinimized()));
  }
}

void TabDialogManager::TabWillEnterBackground(TabInterface* tab_interface) {
  if (widget_) {
    widget_->SetVisible(false);
    browser_window_widget_observer_.reset();
  }
}

void TabDialogManager::TabWillDetach(TabInterface* tab_interface,
                                     TabInterface::DetachReason reason) {
  if (widget_ && params_->close_on_detach) {
    CloseDialog();
  }
}

}  // namespace tabs