File: embedded_permission_prompt_base_view.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 (439 lines) | stat: -rw-r--r-- 16,484 bytes parent folder | download | duplicates (5)
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright 2023 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/views/permissions/embedded_permission_prompt_base_view.h"

#include "base/functional/callback_helpers.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_widget_sublevel.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "components/permissions/features.h"
#include "components/permissions/permission_util.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "third_party/blink/public/common/features_generated.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/mojom/dialog_button.mojom.h"
#include "ui/base/ui_base_features.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/vector_icon_types.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/throbber.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"

DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(EmbeddedPermissionPromptBaseView,
                                      kMainViewId);
DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(EmbeddedPermissionPromptBaseView,
                                      kLabelViewId1);
DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(EmbeddedPermissionPromptBaseView,
                                      kLabelViewId2);
DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(EmbeddedPermissionPromptBaseView,
                                      kTitleViewId);

using permissions::feature_params::PermissionElementPromptPosition;

namespace {

constexpr int BODY_TOP_MARGIN = 10;
constexpr int DISTANCE_BUTTON_VERTICAL = 8;

void AddElementIdentifierToLabel(views::Label& label, size_t index) {
  ui::ElementIdentifier id;
  switch (index) {
    case 0:
      id = EmbeddedPermissionPromptBaseView::kLabelViewId1;
      break;
    case 1:
      id = EmbeddedPermissionPromptBaseView::kLabelViewId2;
      break;
    default:
      return;
  }

  label.SetProperty(views::kElementIdentifierKey, id);
}

std::unique_ptr<views::View> AddSpacer() {
  ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();

  auto spacer = std::make_unique<views::View>();
  spacer->SetPreferredSize(
      gfx::Size(provider->GetDistanceMetric(
                    DISTANCE_PERMISSION_PROMPT_HORIZONTAL_ICON_LABEL_PADDING),
                /*height=*/1));
  return spacer;
}

int GetPermissionIconSize() {
  return 20;
}

float GetScreenScaleFactor(Browser* browser) {
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
  return browser_view ? display::Screen::GetScreen()
                            ->GetPreferredScaleFactorForWindow(
                                browser_view->GetNativeWindow())
                            .value_or(1.0f)
                      : 1.0f;
}

views::View* GetContentsWebView(Browser* browser) {
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
  return browser_view ? browser_view->contents_web_view() : nullptr;
}

}  // namespace

EmbeddedPermissionPromptBaseView::EmbeddedPermissionPromptBaseView(
    Browser* browser,
    base::WeakPtr<EmbeddedPermissionPromptViewDelegate> delegate)
    : PermissionPromptBaseView(browser,
                               delegate->GetPermissionPromptDelegate()),
      delegate_(delegate) {
  SetProperty(views::kElementIdentifierKey, kMainViewId);

  CHECK_GT(delegate_->Requests().size(), 0u);
  element_rect_ = delegate_->Requests()[0]->GetAnchorElementPosition().value_or(
      gfx::Rect());

  // Convert the element position to root coordinate space (in case the element
  // was inside cross-origin frame).
  content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
      delegate_->Requests()[0]->get_requesting_frame_id());
  if (rfh && rfh->GetView()) {
    element_rect_ = gfx::Rect(
        rfh->GetView()->TransformPointToRootCoordSpace(element_rect_.origin()),
        element_rect_.size());
  }

  // Scale the element position according to the device scale factor.
  element_rect_ = gfx::ScaleToEnclosedRect(element_rect_,
                                           1.f / GetScreenScaleFactor(browser));

  // Convert the position into screen coordinates.
  auto* content_view = GetContentsWebView(browser);
  views::View::ConvertRectToScreen(content_view, &element_rect_);
}

EmbeddedPermissionPromptBaseView::~EmbeddedPermissionPromptBaseView() {
  permissions::PermissionUmaUtil::RecordBrowserAlwaysActiveWhilePrompting(
      request_type(), /*embedded_permission_element_initiated*/ true,
      record_browser_always_active_value());
}

void EmbeddedPermissionPromptBaseView::Show() {
  permissions::PermissionUmaUtil::RecordPromptShownInActiveBrowser(
      request_type(), /*embedded_permission_element_initiated*/ true,
      record_browser_always_active_value());
  CreateWidget();
  ShowWidget();
}

const gfx::VectorIcon& EmbeddedPermissionPromptBaseView::GetIcon() const {
  return gfx::VectorIcon::EmptyIcon();
}

bool EmbeddedPermissionPromptBaseView::ShowLoadingIcon() const {
  return false;
}

void EmbeddedPermissionPromptBaseView::CreateWidget() {
  DCHECK(browser()->window());
  views::Widget* widget = views::BubbleDialogDelegateView::CreateBubble(this);

  widget->SetZOrderSublevel(ChromeWidgetSublevel::kSublevelSecurity);
}

std::unique_ptr<views::FlexLayoutView>
EmbeddedPermissionPromptBaseView::CreateLoadingIcon() {
  auto throbber_container = std::make_unique<views::FlexLayoutView>();
  throbber_container->SetMainAxisAlignment(views::LayoutAlignment::kStart);
  throbber_container->SetOrientation(views::LayoutOrientation::kVertical);
  auto throbber = std::make_unique<views::Throbber>();
  throbber->SetPreferredSize(
      gfx::Size(GetPermissionIconSize(), GetPermissionIconSize()));

  throbber->Start();
  throbber_container->AddChildView(std::move(throbber));

  // Also add a filler view to fill in vertical space below the throbber.
  auto filler = std::make_unique<views::View>();
  throbber_container->AddChildView(std::move(filler));
  return throbber_container;
}

void EmbeddedPermissionPromptBaseView::AddedToWidget() {
  StartTrackingPictureInPictureOcclusion();

  auto title_container = std::make_unique<views::FlexLayoutView>();
  title_container->SetOrientation(views::LayoutOrientation::kHorizontal);

  const gfx::VectorIcon& vector_icon = GetIcon();

  if (!vector_icon.is_empty()) {
    auto icon =
        std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon(
            vector_icon, ui::kColorIcon, GetPermissionIconSize()));
    icon->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
    title_container->AddChildView(std::move(icon));

    // Add space between the icon and the text.
    title_container->AddChildView(AddSpacer());
  }

  auto label = std::make_unique<views::Label>(
      GetWindowTitle(), views::style::CONTEXT_DIALOG_TITLE);
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  label->SetCollapseWhenHidden(true);
  label->SetMultiLine(true);
  label->SetAllowCharacterBreak(true);
  label->SetProperty(
      views::kFlexBehaviorKey,
      views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToZero,
                               views::MaximumFlexSizeRule::kScaleToMaximum,
                               /*adjust_height_for_width=*/true));
  label->SetProperty(views::kElementIdentifierKey,
                     EmbeddedPermissionPromptBaseView::kTitleViewId);

  if (ShowLoadingIcon()) {
    title_container->AddChildView(CreateLoadingIcon());

    // Add space between the icon and the text.
    title_container->AddChildView(AddSpacer());
  }

  title_container->AddChildView(std::move(label));

  GetBubbleFrameView()->SetTitleView(std::move(title_container));
}

void EmbeddedPermissionPromptBaseView::ClosingPermission() {
  if (delegate()) {
    delegate()->Dismiss();
  }
}

void EmbeddedPermissionPromptBaseView::PrepareToClose() {
  DialogDelegate::SetCloseCallback(base::DoNothing());
}

PermissionElementPromptPosition
EmbeddedPermissionPromptBaseView::GetPromptPosition() const {
  CHECK(base::FeatureList::IsEnabled(blink::features::kPermissionElement));
  if (!base::FeatureList::IsEnabled(
          permissions::features::kPermissionElementPromptPositioning)) {
    return PermissionElementPromptPosition::kWindowMiddle;
  }

  if (permissions::feature_params::kPermissionElementPromptPositioningParam
              .Get() == PermissionElementPromptPosition::kNearElement &&
      element_rect_.IsEmpty()) {
    return PermissionElementPromptPosition::kWindowMiddle;
  }

  return permissions::feature_params::kPermissionElementPromptPositioningParam
      .Get();
}

void EmbeddedPermissionPromptBaseView::ShowWidget() {
  GetWidget()->Show();
}

void EmbeddedPermissionPromptBaseView::UpdateAnchor(views::Widget* widget) {
  if (GetPromptPosition() == PermissionElementPromptPosition::kLegacyPrompt) {
    AnchorToPageInfoOrChip();
    return;
  }
  SetAnchorView(widget->GetContentsView());
  set_parent_window(
      platform_util::GetViewForWindow(browser()->window()->GetNativeWindow()));

  SetArrow(views::BubbleBorder::Arrow::BOTTOM_LEFT);
}

bool EmbeddedPermissionPromptBaseView::ShouldShowCloseButton() const {
  return true;
}

void EmbeddedPermissionPromptBaseView::Init() {
  SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical, gfx::Insets(),
      DISTANCE_BUTTON_VERTICAL));

  set_close_on_deactivate(false);
  set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric(
      views::DISTANCE_BUBBLE_PREFERRED_WIDTH));

  DialogDelegate::SetCloseCallback(
      base::BindOnce(&EmbeddedPermissionPromptBaseView::ClosingPermission,
                     base::Unretained(this)));

  auto requests_configuration = GetRequestLinesConfiguration();
  int index = 0;
  for (auto& request : requests_configuration) {
    AddRequestLine(request, index++);
  }

  SetButtons(static_cast<int>(ui::mojom::DialogButton::kNone));

  auto buttons_container = std::make_unique<views::View>();
  buttons_container->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical, gfx::Insets(),
      DISTANCE_BUTTON_VERTICAL));

  auto buttons_configuration = GetButtonsConfiguration();

  for (auto& button : buttons_configuration) {
    AddButton(*buttons_container, button);
  }

  views::LayoutProvider* const layout_provider = views::LayoutProvider::Get();
  buttons_container->SetPreferredSize(gfx::Size(
      layout_provider->GetDistanceMetric(
          views::DISTANCE_BUBBLE_PREFERRED_WIDTH) -
          layout_provider->GetInsetsMetric(views::INSETS_DIALOG_BUTTON_ROW)
              .width(),
      buttons_container->GetPreferredSize().height()));

  SetExtraView(std::move(buttons_container));
}

void EmbeddedPermissionPromptBaseView::AddRequestLine(
    const RequestLineConfiguration& line,
    std::size_t index) {
  ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();

  auto* line_container = AddChildViewAt(std::make_unique<views::View>(), index);
  line_container->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kHorizontal,
      gfx::Insets::VH(0, provider->GetDistanceMetric(
                             DISTANCE_SUBSECTION_HORIZONTAL_INDENT)),
      provider->GetDistanceMetric(
          DISTANCE_PERMISSION_PROMPT_HORIZONTAL_ICON_LABEL_PADDING)));

  if (line.icon) {
    auto* icon = line_container->AddChildView(
        std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon(
            *line.icon, ui::kColorIcon, GetPermissionIconSize())));
    icon->SetVerticalAlignment(views::ImageView::Alignment::kCenter);
  }

  auto* label = line_container->AddChildView(
      std::make_unique<views::Label>(line.message));
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  label->SetMultiLine(true);
  AddElementIdentifierToLabel(*label, index);

  label->SetTextStyle(views::style::STYLE_BODY_3);
  label->SetEnabledColor(kColorPermissionPromptRequestText);

  line_container->SetProperty(views::kMarginsKey,
                              gfx::Insets().set_top(BODY_TOP_MARGIN));
}

void EmbeddedPermissionPromptBaseView::AddButton(
    views::View& buttons_container,
    const ButtonConfiguration& button) {
  auto button_view = std::make_unique<views::MdTextButton>(
      base::BindRepeating(&EmbeddedPermissionPromptBaseView::
                              FilterUnintenedEventsAndRunCallbacks,
                          base::Unretained(this), GetViewId(button.type)),
      button.label);
  button_view->SetID(GetViewId(button.type));

  button_view->SetStyle(button.style);

  button_view->SetProperty(views::kElementIdentifierKey, button.identifier);

  buttons_container.AddChildView(std::move(button_view));
}

gfx::Rect EmbeddedPermissionPromptBaseView::GetBubbleBounds() {
  if (GetPromptPosition() == PermissionElementPromptPosition::kLegacyPrompt ||
      !delegate_) {
    return views::BubbleDialogDelegateView::GetBubbleBounds();
  }

  gfx::Rect default_bounds = views::BubbleDialogDelegateView::GetBubbleBounds();

  content::WebContents* web_contents =
      delegate_->GetPermissionPromptDelegate()->GetAssociatedWebContents();

  gfx::Rect container_bounds = web_contents->GetContainerBounds();
  gfx::Rect prompt_bounds;

  if (GetPromptPosition() == PermissionElementPromptPosition::kNearElement) {
    // First, attempt to position the prompt below the PEPC, if it would not
    // overflow the container bounds.
    prompt_bounds = gfx::Rect(
        element_rect_.bottom_center().x() - default_bounds.width() / 2,
        element_rect_.bottom_center().y(), default_bounds.width(),
        default_bounds.height());

    if (prompt_bounds.x() < container_bounds.x()) {
      // Align the prompt on the left side of the element.
      prompt_bounds.set_x(element_rect_.x());
    } else if (prompt_bounds.right() > container_bounds.right()) {
      // Align the prompt on the right side of the element.
      prompt_bounds.set_x(element_rect_.right() - default_bounds.width());
    }

    if (container_bounds.Contains(prompt_bounds)) {
      return prompt_bounds;
    }

    // Second, attempt to position the prompt above the PEPC, if it would not
    // overflow the container bounds.
    prompt_bounds =
        gfx::Rect(element_rect_.top_center().x() - default_bounds.width() / 2,
                  element_rect_.top_center().y() - default_bounds.height(),
                  default_bounds.width(), default_bounds.height());

    if (prompt_bounds.x() < container_bounds.x()) {
      // Align the prompt on the left side of the element.
      prompt_bounds.set_x(element_rect_.x());
    } else if (prompt_bounds.right() > container_bounds.right()) {
      // Align the prompt on the right side of the element.
      prompt_bounds.set_x(element_rect_.right() - default_bounds.width());
    }

    if (container_bounds.Contains(prompt_bounds)) {
      return prompt_bounds;
    }
    // Otherwise, default to kWindowMiddle placement logic.
  }

  // At this point we're either in the kWindowMiddle case or the kNearElement
  // case after failing to place the prompt near the element.
  prompt_bounds = gfx::Rect(
      container_bounds.CenterPoint().x() - default_bounds.width() / 2,
      container_bounds.CenterPoint().y() - default_bounds.height() / 2,
      default_bounds.width(), default_bounds.height());

  // Do not allow the prompt to be positioned above the container bounds as it
  // can overlap and potentially obfuscate browser UI.
  if (prompt_bounds.y() < container_bounds.y()) {
    prompt_bounds.set_y(container_bounds.y());
  }

  return prompt_bounds;
}

BEGIN_METADATA(EmbeddedPermissionPromptBaseView)
END_METADATA