File: omnibox_popup_view_views.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (715 lines) | stat: -rw-r--r-- 26,253 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// Copyright 2012 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/omnibox/omnibox_popup_view_views.h"

#include <memory>
#include <numeric>
#include <optional>
#include <string_view>
#include <utility>

#include "base/auto_reset.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_header_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_result_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_row_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
#include "chrome/browser/ui/views/omnibox/rounded_omnibox_results_frame.h"
#include "chrome/browser/ui/views/theme_copying_widget.h"
#include "components/omnibox/browser/omnibox_controller.h"
#include "components/omnibox/browser/omnibox_edit_model.h"
#include "components/omnibox/common/omnibox_features.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/closure_animation_observer.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/image/image.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/cascading_property.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
// TODO(crbug.com/365733574): used for debugging the misplaced bubble issue on
// mac fullscreen.
#if BUILDFLAG(IS_MAC)
#include "chrome/browser/platform_util.h"
#endif  // BUILDFLAG(IS_MAC)

namespace {

#if BUILDFLAG(IS_MAC)
// Returns true if the browser is in fullscreen. This depends on the fact in mac
// fullscreen the topchrome UI is hosted in an overlay widget.
// TODO(crbug.com/365733574): used for debugging the misplaced bubble issue on
// mac fullscreen.
bool IsInFullscreen(views::Widget* topchrome_host_widget) {
  CHECK(topchrome_host_widget);
  return topchrome_host_widget->GetName() == "mac-fullscreen-overlay";
}
#endif  // BUILDFLAG(IS_MAC)

}  // namespace

class OmniboxPopupViewViews::AutocompletePopupWidget final
    : public ThemeCopyingWidget {
 public:
  // TODO(tapted): Remove |role_model| when the omnibox is completely decoupled
  // from NativeTheme.
  explicit AutocompletePopupWidget(views::Widget* role_model)
      : ThemeCopyingWidget(role_model) {}

  AutocompletePopupWidget(const AutocompletePopupWidget&) = delete;
  AutocompletePopupWidget& operator=(const AutocompletePopupWidget&) = delete;

  ~AutocompletePopupWidget() override = default;

  void InitOmniboxPopup(const views::Widget* parent_widget) {
    views::Widget::InitParams params(
        views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET,
        views::Widget::InitParams::TYPE_POPUP);
#if BUILDFLAG(IS_WIN)
    // On Windows use the software compositor to ensure that we don't block
    // the UI thread during command buffer creation. We can revert this change
    // once http://crbug.com/125248 is fixed.
    params.force_software_compositing = true;
#endif
    params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
    params.parent = parent_widget->GetNativeView();
    params.context = parent_widget->GetNativeWindow();

    RoundedOmniboxResultsFrame::OnBeforeWidgetInit(&params, this);

    Init(std::move(params));
  }

  void SetPopupContentsView(OmniboxPopupViewViews* contents) {
    SetContentsView(std::make_unique<RoundedOmniboxResultsFrame>(
        contents, contents->location_bar_view_));
  }

  void SetTargetBounds(const gfx::Rect& bounds) {
    base::AutoReset<bool> reset(&is_setting_popup_bounds_, true);
    SetBounds(bounds);
#if BUILDFLAG(IS_MAC)
    // TODO(crbug.com/365733574): debug for the misplaced bubble issue on mac
    // fullscreen.
    if (IsInFullscreen(parent())) {
      base::UmaHistogramSparse("Mac.Fullscreen.OmniboxPopupTargetScreenY",
                               bounds.y());
    }
#endif  // BUILDFLAG(IS_MAC)
  }

  void ShowAnimated() {
    // Set the initial opacity to 0 and ease into fully opaque.
    GetLayer()->SetOpacity(0.0);
    ShowInactive();

    const auto scoped_settings = GetScopedAnimationSettings();
    GetLayer()->SetOpacity(1.0);
  }

  void CloseAnimated() {
    // If the opening or shrinking animations still running, abort them, as the
    // popup is closing. This is an edge case for superhumanly fast users.
    GetLayer()->GetAnimator()->AbortAllAnimations();

    auto scoped_settings = GetScopedAnimationSettings();
    GetLayer()->SetOpacity(0.0);
    is_animating_closed_ = true;

    // Destroy the popup when done. The observer deletes itself on completion.
    scoped_settings->AddObserver(new ui::ClosureAnimationObserver(
        base::BindOnce(&AutocompletePopupWidget::Close, AsWeakPtr())));
  }

  void OnWidgetDestroying(views::Widget* widget) override {
    // ThemeCopyingWidget observation is set on the role_model widget, which in
    // the case of `AutocompletePopupWidget` is the hosting parent widget.
    CHECK_NE(widget, this);
    ThemeCopyingWidget::OnWidgetDestroying(widget);

    // In the case the host widget is destroyed, close the popup widget
    // synchronously. This is necessary as the popup widget's contents view has
    // dependencies on the hosting widget's BrowserView (see
    // `SetPopupContentsView()` above). Since the popup widget is owned by its
    // NativeWidget there is a risk of dangling pointers if it is not destroyed
    // synchronously with its parent.
    // TODO(crbug.com/40232479): Once this is migrated to CLIENT_OWNS_WIDGET
    // this will no longer be necessary.
    CloseNow();
  }

  void OnMouseEvent(ui::MouseEvent* event) override {
    // Ignore mouse events if the popup is closed or animating closed.
    if (IsClosed() || is_animating_closed_) {
      if (event->cancelable()) {
        event->SetHandled();
      }
      return;
    }

    ThemeCopyingWidget::OnMouseEvent(event);
  }

  void OnGestureEvent(ui::GestureEvent* event) override {
    // Ignore gesture events if the popup is closed or animating closed.
    // However, just like the base class, we do not capture the event, so
    // multiple widgets may get tap events at the same time.
    if (IsClosed() || is_animating_closed_) {
      return;
    }

    ThemeCopyingWidget::OnGestureEvent(event);
  }

  bool is_setting_popup_bounds() const { return is_setting_popup_bounds_; }

  base::WeakPtr<AutocompletePopupWidget> AsWeakPtr() {
    return weak_ptr_factory_.GetWeakPtr();
  }

 private:
  std::unique_ptr<ui::ScopedLayerAnimationSettings>
  GetScopedAnimationSettings() {
    auto settings = std::make_unique<ui::ScopedLayerAnimationSettings>(
        GetLayer()->GetAnimator());

    settings->SetTweenType(gfx::Tween::Type::FAST_OUT_SLOW_IN);

    constexpr base::TimeDelta kPopupOpacityAnimationDuration =
        base::Milliseconds(82);
    settings->SetTransitionDuration(kPopupOpacityAnimationDuration);

    return settings;
  }

  // True if the popup is in the process of closing via animation.
  bool is_animating_closed_ = false;

  // True if the popup's bounds are currently being set.
  bool is_setting_popup_bounds_ = false;

  base::WeakPtrFactory<AutocompletePopupWidget> weak_ptr_factory_{this};
};

OmniboxPopupViewViews::OmniboxPopupViewViews(OmniboxViewViews* omnibox_view,
                                             OmniboxController* controller,
                                             LocationBarView* location_bar_view)
    : OmniboxPopupView(controller),
      omnibox_view_(omnibox_view),
      location_bar_view_(location_bar_view) {
  model()->set_popup_view(this);

  if (omnibox_view_) {
    GetViewAccessibility().SetPopupForId(
        omnibox_view_->GetViewAccessibility().GetUniqueId());
  }

  // The contents is owned by the LocationBarView.
  set_owned_by_client(OwnedByClientPassKey());

  SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical));

  GetViewAccessibility().SetRole(ax::mojom::Role::kListBox);
  UpdateAccessibleStates();
  UpdateAccessibleControlIds();
  UpdateAccessibleActiveDescendantForInvokingView();
}

OmniboxPopupViewViews::~OmniboxPopupViewViews() {
  // We don't need to close or delete |popup_| here. The OS either has already
  // closed the window, in which case it's been deleted, or it will soon.
  if (popup_) {
    popup_->RemoveObserver(this);
  }
  CHECK(!IsInObserverList());
  model()->set_popup_view(nullptr);
  UpdateAccessibleControlIds();
}

gfx::Image OmniboxPopupViewViews::GetMatchIcon(
    const AutocompleteMatch& match,
    SkColor vector_icon_color) const {
  bool dark_mode = false;
  auto* color_provider = GetColorProvider();
  if (color_provider) {
    dark_mode = color_utils::IsDark(
        color_provider->GetColor(kColorOmniboxResultsBackground));
  }
  return model()->GetMatchIcon(match, vector_icon_color, dark_mode);
}

void OmniboxPopupViewViews::SetSelectedIndex(size_t index) {
  DCHECK(HasMatchAt(index));

  if (index != model()->GetPopupSelection().line) {
    OmniboxPopupSelection::LineState line_state = OmniboxPopupSelection::NORMAL;
    model()->SetPopupSelection(OmniboxPopupSelection(index, line_state));
    OnPropertyChanged(model(), views::kPropertyEffectsNone);
  }
}

size_t OmniboxPopupViewViews::GetSelectedIndex() const {
  return GetSelection().line;
}

OmniboxPopupSelection OmniboxPopupViewViews::GetSelection() const {
  return model()->GetPopupSelection();
}

bool OmniboxPopupViewViews::IsOpen() const {
  return popup_ != nullptr;
}

void OmniboxPopupViewViews::InvalidateLine(size_t line) {
  // TODO(tommycli): This is weird, but https://crbug.com/1063071 shows that
  // crashes like this have happened, so we add this to avoid it for now.
  if (line >= children().size()) {
    return;
  }

  static_cast<OmniboxRowView*>(children()[line])->OnSelectionStateChanged();
}

void OmniboxPopupViewViews::OnSelectionChanged(
    OmniboxPopupSelection old_selection,
    OmniboxPopupSelection new_selection) {
  // Do not invalidate the same line twice, in order to avoid redundant
  // accessibility events.
  if (old_selection.line != OmniboxPopupSelection::kNoMatch &&
      old_selection.line != new_selection.line) {
    InvalidateLine(old_selection.line);
  }

  if (new_selection.line != OmniboxPopupSelection::kNoMatch) {
    InvalidateLine(new_selection.line);
  }
  UpdateAccessibleActiveDescendantForInvokingView();
}

void OmniboxPopupViewViews::UpdatePopupAppearance() {
  const auto* autocomplete_controller = controller()->autocomplete_controller();
  if (autocomplete_controller->result().empty() ||
      omnibox_view_->IsImeShowingPopup()) {
    // No matches or the IME is showing a popup window which may overlap
    // the omnibox popup window.  Close any existing popup.
    if (popup_) {
      // Check whether omnibox should be not closed according to the UI
      // DevTools settings.
      if (!popup_->ShouldHandleNativeWidgetActivationChanged(false)) {
        return;
      }
      popup_->CloseAnimated();  // This will eventually delete the popup.
      popup_->RemoveObserver(this);
      popup_.reset();
      UpdateAccessibleStates();
      UpdateAccessibleControlIds();
      // The active descendant should be cleared when the popup closes.
      UpdateAccessibleActiveDescendantForInvokingView();
      FireAXEventsForNewActiveDescendant(nullptr);
    }
    return;
  }

  // Ensure that we have an existing popup widget prior to creating the result
  // views to ensure the proper initialization of the views hierarchy.
  bool popup_created = false;
  if (!popup_) {
    views::Widget* popup_parent = location_bar_view_->GetWidget();

    // If the popup is currently closed, we need to create it.
    popup_create_start_time_ = base::TimeTicks::Now();
    popup_ = (new AutocompletePopupWidget(popup_parent))->AsWeakPtr();
    popup_->InitOmniboxPopup(popup_parent);
    // Third-party software such as DigitalPersona identity verification can
    // hook the underlying window creation methods and use SendMessage to
    // synchronously change focus/activation, resulting in the popup being
    // destroyed by the time control returns here.  Bail out in this case to
    // avoid a nullptr dereference.
    if (!popup_) {
      return;
    }

    popup_->SetVisibilityAnimationTransition(views::Widget::ANIMATE_NONE);
    popup_->SetPopupContentsView(this);
    popup_->AddObserver(this);

    popup_created = true;
  }

  // Update the match cached by each row, in the process of doing so make sure
  // we have enough row views.
  const size_t result_size = autocomplete_controller->result().size();
  std::u16string previous_row_header = u"";
  for (size_t i = 0; i < result_size; ++i) {
    // Create child views lazily.  Since especially the first result view may
    // be expensive to create due to loading font data, this saves time and
    // memory during browser startup. https://crbug.com/1021323
    if (children().size() == i) {
      AddChildView(std::make_unique<OmniboxRowView>(i, /*popup_view=*/this));
    }

    OmniboxRowView* const row_view =
        static_cast<OmniboxRowView*>(children()[i]);
    row_view->SetVisible(true);

    const AutocompleteMatch& match = GetMatchAtIndex(i);
    std::u16string current_row_header =
        model()->GetSuggestionGroupHeaderText(match.suggestion_group_id);
    // Show the header if it's distinct from the previous match's header.
    if (!current_row_header.empty() &&
        current_row_header != previous_row_header) {
      row_view->ShowHeader(current_row_header);
    } else {
      row_view->HideHeader();
    }
    previous_row_header = current_row_header;

    OmniboxResultView* const result_view = row_view->result_view();
    result_view->SetMatch(match);
    // Set visibility of the result view based on whether the row is hidden.
    result_view->SetVisible(!controller()->IsSuggestionHidden(match));
    result_view->UpdateAccessibilityProperties();

    const SkBitmap* bitmap = model()->GetPopupRichSuggestionBitmap(i);
    if (bitmap) {
      result_view->SetRichSuggestionImage(
          gfx::ImageSkia::CreateFrom1xBitmap(*bitmap));
    }
  }
  // If we have more views than matches, hide the surplus ones.
  for (auto i = children().begin() + result_size; i != children().end(); ++i) {
    (*i)->SetVisible(false);
  }

  popup_->SetTargetBounds(GetTargetBounds());

  if (popup_created) {
    popup_->ShowAnimated();

    // Popup is now expanded and first item will be selected.
    UpdateAccessibleStates();
    UpdateAccessibleControlIds();
    UpdateAccessibleActiveDescendantForInvokingView();
    OmniboxResultView* result_view = result_view_at(0);
    if (result_view) {
      result_view->GetViewAccessibility().SetIsSelected(true);
      FireAXEventsForNewActiveDescendant(result_view);
    }

    NotifyOpenListeners();
  }
  InvalidateLayout();
}

void OmniboxPopupViewViews::ProvideButtonFocusHint(size_t line) {
  DCHECK(GetSelection().IsButtonFocused());

  views::View* active_button = static_cast<OmniboxRowView*>(children()[line])
                                   ->GetActiveAuxiliaryButtonForAccessibility();
  // TODO(tommycli): |active_button| can sometimes be nullptr, because the
  // suggestion button row is not completely implemented.
  if (active_button) {
    // The accessible selection cannot be in both the button and the result
    // view. When the button gets selected and is active, remove the selected
    // state from the result view. This is so that if a subsequent action
    // creates a OmniboxPopupSelection::NORMAL we fire the event.
    result_view_at(line)->GetViewAccessibility().SetIsSelected(false);
    FireAXEventsForNewActiveDescendant(active_button);
  }
}

void OmniboxPopupViewViews::OnMatchIconUpdated(size_t match_index) {
  if (OmniboxResultView* result_view = result_view_at(match_index)) {
    result_view->OnMatchIconUpdated();
  }
}

void OmniboxPopupViewViews::OnDragCanceled() {
  SetMouseAndGestureHandler(nullptr);
}

void OmniboxPopupViewViews::GetPopupAccessibleNodeData(
    ui::AXNodeData* node_data) const {
  return GetViewAccessibility().GetAccessibleNodeData(node_data);
}

std::u16string_view OmniboxPopupViewViews::GetAccessibleButtonTextForResult(
    size_t line) const {
  if (const OmniboxResultView* result_view = result_view_at(line)) {
    return static_cast<const views::LabelButton*>(
               result_view->GetActiveAuxiliaryButtonForAccessibility())
        ->GetText();
  }
  return std::u16string_view();
}

bool OmniboxPopupViewViews::OnMouseDragged(const ui::MouseEvent& event) {
  const size_t index = GetIndexForPoint(event.location());

  // If the drag event is over the bounds of one of the result views, pass
  // control to that view.
  if (HasMatchAt(index)) {
    SetMouseAndGestureHandler(result_view_at(index));
    return false;
  }

  // If the drag event is not over any of the result views, that means that it
  // has passed outside the bounds of the popup view. Return true to keep
  // receiving the drag events, as the drag may return in which case we will
  // want to respond to it again.
  return true;
}

void OmniboxPopupViewViews::OnGestureEvent(ui::GestureEvent* event) {
  const size_t index = GetIndexForPoint(event->location());
  if (!HasMatchAt(index)) {
    return;
  }

  switch (event->type()) {
    case ui::EventType::kGestureTapDown:
    case ui::EventType::kGestureScrollBegin:
    case ui::EventType::kGestureScrollUpdate:
      SetSelectedIndex(index);
      break;
    case ui::EventType::kGestureTap:
    case ui::EventType::kGestureScrollEnd: {
      DCHECK(HasMatchAt(index));
      model()->OpenSelection(OmniboxPopupSelection(index), event->time_stamp());
      break;
    }
    default:
      return;
  }
  event->SetHandled();
}

void OmniboxPopupViewViews::FireAXEventsForNewActiveDescendant(
    View* descendant_view) {
  // Selected children changed is fired on the popup.
  NotifyAccessibilityEventDeprecated(ax::mojom::Event::kSelectedChildrenChanged,
                                     true);
}

void OmniboxPopupViewViews::OnWidgetBoundsChanged(views::Widget* widget,
                                                  const gfx::Rect& new_bounds) {
  // Because we don't directly control the lifetime of the widget, gracefully
  // handle "stale" notifications by ignoring them. https://crbug.com/1108762
  if (!popup_ || popup_.get() != widget) {
    return;
  }

  // This is called on rotation or device scale change. We have to re-align to
  // the new location bar location.

  // Ignore cases when we are internally updating the popup bounds.
  if (popup_->is_setting_popup_bounds()) {
    return;
  }

  UpdatePopupAppearance();
}

void OmniboxPopupViewViews::OnWidgetVisibilityChanged(views::Widget* widget,
                                                      bool visible) {
  if (!popup_ || widget != popup_.get()) {
    return;
  }

  if (visible && popup_create_start_time_.has_value()) {
    // Use the popup's compositor. The next presentation time will correspond to
    // the first visual presentation of the bubble's content after the Widget
    // has been created.
    popup_->GetCompositor()->RequestSuccessfulPresentationTimeForNextFrame(
        base::BindOnce(
            [](base::TimeTicks popup_create_start_time,
               const viz::FrameTimingDetails& frame_timing_details) {
              base::TimeTicks presentation_timestamp =
                  frame_timing_details.presentation_feedback.timestamp;
              base::UmaHistogramTimes(
                  "Omnibox.Views.PopupFirstPaint",
                  presentation_timestamp - popup_create_start_time);
            },
            popup_create_start_time_.value()));
    popup_create_start_time_.reset();
  }
}

void OmniboxPopupViewViews::OnWidgetDestroying(views::Widget* widget) {
  CHECK_EQ(widget, popup_.get());
  if (popup_) {
    popup_->RemoveObserver(this);
    popup_ = nullptr;
  }
  UpdateAccessibleStates();
}

gfx::Rect OmniboxPopupViewViews::GetTargetBounds() const {
  int popup_height = 0;
  const auto* autocomplete_controller = controller()->autocomplete_controller();
  DCHECK_GE(children().size(), autocomplete_controller->result().size());
  popup_height = std::accumulate(
      children().cbegin(),
      children().cbegin() + autocomplete_controller->result().size(), 0,
      [](int height, const views::View* v) {
        return height + v->GetPreferredSize().height();
      });

  // Add 8dp at the bottom for aesthetic reasons. https://crbug.com/1076646
  // It's expected that this space is dead unclickable/unhighlightable space.
  // This extra padding is not added if the results section has no height
  // (result set is empty or all results are hidden).
  if (popup_height != 0) {
    constexpr int kExtraBottomPadding = 8;
    popup_height += kExtraBottomPadding;
  }

  // Add enough space on the top and bottom so it looks like there is the same
  // amount of space between the text and the popup border as there is in the
  // interior between each row of text.
  popup_height += RoundedOmniboxResultsFrame::GetNonResultSectionHeight();

  // The rounded popup is always offset the same amount from the omnibox.
  gfx::Rect content_rect = location_bar_view_->GetBoundsInScreen();

#if BUILDFLAG(IS_MAC)
  // TODO(crbug.com/365733574): debug for the misplaced bubble issue on mac
  // fullscreen.
  views::Widget* topchrome_host_widget = location_bar_view_->GetWidget();
  if (IsInFullscreen(topchrome_host_widget)) {
    base::UmaHistogramSparse(
        "Mac.Fullscreen.OverlayWidgetScreenY",
        topchrome_host_widget->GetWindowBoundsInScreen().y());
    base::UmaHistogramSparse("Mac.Fullscreen.OverlayNSWindowScreenY",
                             platform_util::GetWindowScreenBounds(
                                 topchrome_host_widget->GetNativeWindow())
                                 .y());
    base::UmaHistogramSparse("Mac.Fullscreen.LocationBarViewScreenY",
                             content_rect.y());
  }
#endif  // BUILDFLAG(IS_MAC)

  content_rect.Inset(
      -RoundedOmniboxResultsFrame::GetLocationBarAlignmentInsets());
  content_rect.set_height(popup_height);

  // Finally, expand the widget to accommodate the custom-drawn shadows.
  content_rect.Inset(-RoundedOmniboxResultsFrame::GetShadowInsets());
  return content_rect;
}

OmniboxHeaderView* OmniboxPopupViewViews::header_view_at(size_t i) {
  if (i >= children().size()) {
    return nullptr;
  }

  return static_cast<OmniboxRowView*>(children()[i])->header_view();
}

OmniboxResultView* OmniboxPopupViewViews::result_view_at(size_t i) {
  return const_cast<OmniboxResultView*>(std::as_const(*this).result_view_at(i));
}

const OmniboxResultView* OmniboxPopupViewViews::result_view_at(size_t i) const {
  if (i >= children().size()) {
    return nullptr;
  }

  return static_cast<OmniboxRowView*>(children()[i])->result_view();
}

bool OmniboxPopupViewViews::HasMatchAt(size_t index) const {
  return index < controller()->autocomplete_controller()->result().size();
}

const AutocompleteMatch& OmniboxPopupViewViews::GetMatchAtIndex(
    size_t index) const {
  return controller()->autocomplete_controller()->result().match_at(index);
}

size_t OmniboxPopupViewViews::GetIndexForPoint(const gfx::Point& point) const {
  if (!HitTestPoint(point)) {
    return OmniboxPopupSelection::kNoMatch;
  }

  size_t nb_match = controller()->autocomplete_controller()->result().size();
  DCHECK_LE(nb_match, children().size());
  for (size_t i = 0; i < nb_match; ++i) {
    views::View* child = children()[i];
    gfx::Point point_in_child_coords(point);
    View::ConvertPointToTarget(this, child, &point_in_child_coords);
    if (child->GetVisible() && child->HitTestPoint(point_in_child_coords)) {
      return i;
    }
  }
  return OmniboxPopupSelection::kNoMatch;
}

void OmniboxPopupViewViews::UpdateAccessibleStates() const {
  if (IsOpen()) {
    GetViewAccessibility().SetIsExpanded();
    GetViewAccessibility().SetIsInvisible(false);
  } else {
    GetViewAccessibility().SetIsCollapsed();
    GetViewAccessibility().SetIsInvisible(true);
  }
}

void OmniboxPopupViewViews::UpdateAccessibleControlIds() {
  if (!omnibox_view_) {
    return;
  }

  // Establish a "CONTROLS" relationship between the omnibox and the
  // the popup. This allows a screen reader to understand the relationship
  // between the omnibox and the list of suggestions, and determine which
  // suggestion is currently selected, even though focus remains here on
  // the omnibox.
  if (IsOpen()) {
    int32_t popup_view_id = GetViewAccessibility().GetUniqueId();
    omnibox_view_->GetViewAccessibility().SetControlIds({popup_view_id});
  } else {
    omnibox_view_->GetViewAccessibility().RemoveControlIds();
  }
}

void OmniboxPopupViewViews::UpdateAccessibleActiveDescendantForInvokingView() {
  if (!omnibox_view_) {
    return;
  }

  // This logic aims to update the "active descendant" accessibility
  // property of the omnibox text field (`omnibox_view_`).
  //
  // This property tells assistive technologies (like screen readers) which
  // element within the popup should be considered the currently "active" or
  // "focused" item, even though the actual keyboard focus remains on the
  // text field.
  OmniboxPopupSelection selection = GetSelection();
  if (IsOpen() && selection.line != OmniboxPopupSelection::kNoMatch) {
    if (OmniboxResultView* result_view = result_view_at(selection.line)) {
      omnibox_view_->GetViewAccessibility().SetActiveDescendant(*result_view);
    } else {
      omnibox_view_->GetViewAccessibility().ClearActiveDescendant();
    }
  } else {
    omnibox_view_->GetViewAccessibility().ClearActiveDescendant();
  }
}

BEGIN_METADATA(OmniboxPopupViewViews)
ADD_PROPERTY_METADATA(size_t, SelectedIndex)
ADD_READONLY_PROPERTY_METADATA(gfx::Rect, TargetBounds)
END_METADATA