File: omnibox_suggestion_button_row_view.cc

package info (click to toggle)
chromium 140.0.7339.127-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,192,880 kB
  • sloc: cpp: 35,093,808; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,797; asm: 949,904; xml: 747,503; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (656 lines) | stat: -rw-r--r-- 26,885 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
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
// Copyright 2020 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_suggestion_button_row_view.h"

#include <algorithm>

#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/omnibox/omnibox_theme.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_typography.h"
#include "chrome/browser/ui/views/location_bar/location_bar_util.h"
#include "chrome/browser/ui/views/location_bar/selected_keyword_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_popup_view_views.h"
#include "components/omnibox/browser/actions/omnibox_action.h"
#include "components/omnibox/browser/autocomplete_match_type.h"
#include "components/omnibox/browser/omnibox_controller.h"
#include "components/omnibox/browser/omnibox_edit_model.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/browser/vector_icons.h"
#include "components/omnibox/common/omnibox_feature_configs.h"
#include "components/strings/grit/components_strings.h"
#include "components/vector_icons/vector_icons.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/window_open_disposition.h"
#include "ui/base/window_open_disposition_utils.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/painter.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_utils.h"

// A chip, like the history embeddings chip. Contains icon & text. Can not be
// focused or selected.
class OmniboxSuggestionRowChip : public views::MdTextButton {
  METADATA_HEADER(OmniboxSuggestionRowChip, views::MdTextButton)

 public:
  OmniboxSuggestionRowChip(const std::u16string& text,
                           const gfx::VectorIcon& icon)
      : MdTextButton({},
                     text,
                     CONTEXT_OMNIBOX_POPUP_ROW_CHIP,
                     /*use_text_color_for_icon=*/true),
        icon_(&icon) {
    // Default margin of the suggestion row's children is (0, 4, 0, 8). Remove
    // the left margin for chips per UX decision.
    SetProperty(
        views::kMarginsKey,
        gfx::Insets::TLBR(0, 0, 0,
                          ChromeLayoutProvider::Get()->GetDistanceMetric(
                              views::DISTANCE_RELATED_BUTTON_HORIZONTAL)));

    SetImageLabelSpacing(5);
    SetCustomPadding(gfx::Insets::VH(0, 7));
    SetCornerRadius(100);  // Large number to ensure 100% rounded.

    views::InkDrop::Get(this)->GetInkDrop()->SetShowHighlightOnHover(false);
  }

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

  ~OmniboxSuggestionRowChip() override = default;

  void SetThemeState(OmniboxPartState theme_state) {
    if (theme_state_ == theme_state) {
      return;
    }
    theme_state_ = theme_state;
    OnThemeChanged();
  }

  void OnThemeChanged() override {
    MdTextButton::OnThemeChanged();
    // We can't use colors from NativeTheme as the omnibox theme might be
    // different (for example, if the NTP colors are customized).
    const auto* const color_provider = GetColorProvider();
    SetImageModel(
        views::Button::STATE_NORMAL,
        ui::ImageModel::FromVectorIcon(*icon_, kColorOmniboxResultsIcon, 10));
    SetEnabledTextColors(
        color_provider->GetColor(ui::kColorSysOnSurfaceSubtle));
  }

  void UpdateBackgroundColor() override {
    const auto* const color_provider = GetColorProvider();
    const SkColor color =
        color_provider->GetColor(kColorOmniboxResultsChipBackground);
    SetBackground(views::CreateRoundedRectBackground(color, GetCornerRadii()));
  }

 private:
  raw_ptr<const gfx::VectorIcon> icon_;
  OmniboxPartState theme_state_ = OmniboxPartState::NORMAL;
};

BEGIN_METADATA(OmniboxSuggestionRowChip)
END_METADATA

class OmniboxSuggestionButtonRowLayout : public views::LayoutManager {
 public:
  OmniboxSuggestionButtonRowLayout() = default;
  ~OmniboxSuggestionButtonRowLayout() override = default;

  gfx::Size GetMinimumSize(const views::View* host) const override {
    return CalculateSize(host, [](const views::View* v) {
      return v->GetMinimumSize();
    });
  }

  gfx::Size GetPreferredSize(const views::View* host) const override {
    return CalculateSize(host, [](const views::View* v) {
      return v->GetPreferredSize({});
    });
  }

  gfx::Size GetPreferredSize(
      const views::View* host,
      const views::SizeBounds& available_size) const override {
    return GetPreferredSize(host);
  }

  // This layout is similar to a `FlexLayout` with `kPreferredSnapToZero`, with
  // a priority to give children their preferred size from left to right. With
  // the additional constraint that once there is not enough space to expand a
  // child to its preferred size, all remaining children after it are forced to
  // be displayed at their minimum sizes. The goal is to collapse the children
  // to their minimum sizes from right to left as the available space decreases,
  // strictly in that order.
  //
  // If there is space to show all children at their preferred sizes, the layout
  // will look like this:
  // +--------------------------------------------------------------+
  // |  preferred_size_1  |  preferred_size_2  |  preferred_size_3  |
  // +--------------------------------------------------------------+
  // But as the available space decreases, the layout will look like this:
  // +---------------------------------------------------+
  // |  preferred_size_1  |  preferred_size_2  |  min_3  |
  // +---------------------------------------------------+
  // And then this:
  // +----------------------------------------+
  // |  preferred_size_1  |  min_2  |  min_3  |
  // +----------------------------------------+
  // And finally this:
  // +-----------------------------+
  // |  min_1  |  min_2  |  min_3  |
  // +-----------------------------+
  //
  // `FlexLayout` cannot be used because, if there is room to expand any of the
  // children, it will always do so regardless of child order or weight values.
  // Which leads to the following undesired behavior, where the children are
  // collapsed from right to left, according their order values:
  // +--------------------------------------------+
  // |  big_preferred_size_1  |  min_2  |  min_3  |
  // +--------------------------------------------+
  // But then when there is not enough space to show the first child at its
  // preferred size, if the child in the middle has a smaller preferred size
  // than the first child, it is expanded to fill the remaining space, resulting
  // in the following:
  // +----------------------------------------+
  // |  min_1  |  preferred_size_2  |  min_3  |
  // +----------------------------------------+
  // Which violates our requirement to strictly collapse in order, from right to
  // left.
  void Layout(views::View* host) override {
    const gfx::Size& host_size = host->bounds().size();

    // The total width used is, at a minimum, the minimum width of the host
    // view, which is the sum of the minimum widths of all children plus insets.
    // In the loop below, we will accumulate any additional width required to
    // show children at their preferred width, for those children that are
    // allowed to expand.
    int total_width_used = GetMinimumSize(host).width();

    const int y = row_insets_.top() + button_insets_.top();
    int current_x = row_insets_.left();
    bool allow_expansion = true;
    // This loop positions the visible children one by one, checking to see if
    // the additional width required to display them at their preferred width is
    // available. If it is, the child is allocated its preferred width with
    // `SetBoundsRect()`. If not, the child is allocated its minimum width and
    // `allow_expansion` is set to false to force the remaining children to also
    // be allocated only their minimum widths.
    for (views::View* child : host->children()) {
      if (!child->GetVisible()) {
        continue;
      }

      const gfx::Size& child_minimum_size = child->GetMinimumSize();
      const gfx::Size& child_preferred_size = child->GetPreferredSize({});
      int additional_width_for_preferred =
          child_preferred_size.width() - child_minimum_size.width();
      // This is the key element of logic for this layout. Here we check to see
      // if all the width used so far plus the additional width for this child's
      // preferred width is less than or equal to the total width available (the
      // host width).
      bool preferred_width_available =
          total_width_used + additional_width_for_preferred <=
          host_size.width();
      allow_expansion = allow_expansion && preferred_width_available;
      int child_allocated_width = allow_expansion ? child_preferred_size.width()
                                                  : child_minimum_size.width();

      child->SetBoundsRect(
          {{current_x + button_insets_.left(), y},
           {child_allocated_width, child_preferred_size.height()}});
      total_width_used += allow_expansion ? additional_width_for_preferred : 0;
      current_x += child_allocated_width + button_insets_.width();
    }
  }

 private:
  // Both `GetMinimumSize()` and `GetPreferredSize()` require identical logic,
  // but based on the host's children's minimum or preferred sizes,
  // respectively. This function captures that common logic and accepts a lambda
  // to get the minimum or preferred size from each child.
  template <typename ChildSizeGetter>
  gfx::Size CalculateSize(const views::View* host,
                          ChildSizeGetter get_child_size) const {
    const auto& children = host->children();

    int width = 0;
    int height = 0;
    // Accumulate the total width and biggest height of all visible children.
    for (const views::View* child : children) {
      if (!child->GetVisible()) {
        continue;
      }
      const gfx::Size child_size = get_child_size(child);
      width += child_size.width() + button_insets_.width();
      height = std::max(height, child_size.height() + button_insets_.height());
    }
    // Add in the button row insets.
    // NOTE: This logic does not include any option for the "collapse margins"
    // behavior that FlexLayout offers. If it's required in the future, it could
    // be added here.
    width += row_insets_.width();
    height += row_insets_.height();

    return {width, height};
  }

  // TODO(crbug.com/422549792): These insets need to be adjusted to be larger on
  //   right and left in order to show more space when the suggestion text/view
  //   is not visible. Which will then require coordination with the insets of
  //   the suggestion text/view. Additionally, the values here were selected to
  //   produce the designed layout, but they should either be explained further
  //   here or specified with `ChromeLayoutProvider`.
  gfx::Insets row_insets_ = gfx::Insets::TLBR(6, 4, 6, 0);
  gfx::Insets button_insets_ =
      gfx::Insets::TLBR(0, 0, 0,
                        ChromeLayoutProvider::Get()->GetDistanceMetric(
                            views::DISTANCE_RELATED_BUTTON_HORIZONTAL));
};

// A button, like the switch-to-tab or keyword buttons. Contains icon & text.
// Can be focused and selected.
class OmniboxSuggestionRowButton : public views::MdTextButton {
  METADATA_HEADER(OmniboxSuggestionRowButton, views::MdTextButton)

 public:
  OmniboxSuggestionRowButton(PressedCallback callback,
                             int context,
                             const gfx::VectorIcon& icon,
                             const gfx::Image& image,
                             OmniboxPopupViewViews* popup_view,
                             OmniboxPopupSelection selection)
      : MdTextButton(std::move(callback),
                     u"",
                     context,
                     /*use_text_color_for_icon=*/false),
        icon_(&icon),
        image_(image),
        popup_view_(popup_view),
        selection_(selection) {
    SetTriggerableEventFlags(GetTriggerableEventFlags() |
                             ui::EF_MIDDLE_MOUSE_BUTTON);
    views::InstallPillHighlightPathGenerator(this);

    SetImageLabelSpacing(8);
    SetCustomPadding(ChromeLayoutProvider::Get()->GetInsetsMetric(
        INSETS_OMNIBOX_PILL_BUTTON));
    SetCornerRadius(GetLayoutConstant(TOOLBAR_CORNER_RADIUS));

    auto* const ink_drop = views::InkDrop::Get(this);
    SetAnimationDuration(base::TimeDelta());
    ink_drop->GetInkDrop()->SetHoverHighlightFadeDuration(base::TimeDelta());

    auto* const focus_ring = views::FocusRing::Get(this);
    focus_ring->SetHasFocusPredicate(base::BindRepeating([](const View* view) {
      const auto* v = views::AsViewClass<OmniboxSuggestionRowButton>(view);
      CHECK(v);
      return v->GetVisible() && v->popup_view_->GetSelection() == v->selection_;
    }));
    focus_ring->SetColorId(kColorOmniboxResultsFocusIndicator);

    GetViewAccessibility().SetRole(ax::mojom::Role::kListBoxOption);
    GetViewAccessibility().SetIsSelected(false);
  }

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

  ~OmniboxSuggestionRowButton() override = default;

  // Suggestion row buttons are allowed to collapse to the size of their icons
  // and insets only. Whether they are allocated their preferred size, which
  // also includes the label, is controlled by OmniboxSuggestionButtonRowLayout.
  gfx::Size GetMinimumSize() const override {
    gfx::Size size = image_container_view()->GetPreferredSize({});
    size.Enlarge(GetInsets().width(), GetInsets().height());
    return size;
  }

  void SetThemeState(OmniboxPartState theme_state) {
    if (theme_state_ == theme_state) {
      return;
    }
    theme_state_ = theme_state;
    OnThemeChanged();
  }

  OmniboxPopupSelection selection() const { return selection_; }

  void OnThemeChanged() override {
    MdTextButton::OnThemeChanged();
    // We can't use colors from NativeTheme as the omnibox theme might be
    // different (for example, if the NTP colors are customized).
    const auto* const color_provider = GetColorProvider();
    const bool selected = theme_state_ == OmniboxPartState::SELECTED;
    if (!image_.IsEmpty()) {
      SetImageModel(views::Button::STATE_NORMAL,
                    ui::ImageModel::FromImage(image_));
    } else {
      SetImageModel(views::Button::STATE_NORMAL,
                    ui::ImageModel::FromVectorIcon(
                        *icon_,
                        selected ? kColorOmniboxResultsButtonIconSelected
                                 : kColorOmniboxResultsButtonIcon,
                        GetLayoutConstant(LOCATION_BAR_ICON_SIZE)));
    }
    SetEnabledTextColors(color_provider->GetColor(
        selected ? kColorOmniboxResultsTextSelected : kColorOmniboxText));
    ConfigureInkDropForRefresh2023(
        this,
        /*hover_color_id=*/
        selected ? kColorOmniboxResultsButtonInkDropRowSelected
                 : kColorOmniboxResultsButtonInkDropRowHovered,
        /*ripple_color_id=*/
        selected ? kColorOmniboxResultsButtonInkDropSelectedRowSelected
                 : kColorOmniboxResultsButtonInkDropSelectedRowHovered);

    views::FocusRing::Get(this)->SchedulePaint();
  }

  void UpdateBackgroundColor() override {
    const auto* const color_provider = GetColorProvider();
    const SkColor stroke_color =
        color_provider->GetColor(kColorOmniboxResultsButtonBorder);
    const SkColor fill_color =
        color_provider->GetColor(GetOmniboxBackgroundColorId(theme_state_));
    SetBackground(CreateBackgroundFromPainter(
        views::Painter::CreateRoundRectWith1PxBorderPainter(
            fill_color, stroke_color, GetCornerRadii(), SkBlendMode::kSrcOver,
            /*antialias=*/true,
            /*should_border_scale=*/true)));
  }

  void SetIcon(const gfx::VectorIcon& icon) {
    if (icon_ != &icon) {
      icon_ = &icon;
      OnThemeChanged();
    }
  }

  void SetImage(const gfx::Image& image) {
    if (image_ != image) {
      image_ = image;
      OnThemeChanged();
    }
  }

 private:
  raw_ptr<const gfx::VectorIcon> icon_;
  gfx::Image image_;
  raw_ptr<OmniboxPopupViewViews> popup_view_;
  OmniboxPartState theme_state_ = OmniboxPartState::NORMAL;

  OmniboxPopupSelection selection_;
};

BEGIN_METADATA(OmniboxSuggestionRowButton)
END_METADATA

OmniboxSuggestionButtonRowView::OmniboxSuggestionButtonRowView(
    OmniboxPopupViewViews* popup_view,
    int model_index)
    : popup_view_(popup_view), model_index_(model_index) {
  SetLayoutManager(std::make_unique<OmniboxSuggestionButtonRowLayout>());
  BuildViews();
  SetPaintToLayer(ui::LAYER_NOT_DRAWN);
}

void OmniboxSuggestionButtonRowView::BuildViews() {
  // Clear and reset existing views. Reset all raw_ptr instances first to avoid
  // dangling.
  previous_active_button_ = nullptr;
  embeddings_chip_ = nullptr;
  keyword_button_ = nullptr;
  action_buttons_.clear();
  RemoveAllChildViews();

  // Skip remaining code that depends on `match()`.
  if (!HasMatch()) {
    return;
  }

  // For all of these buttons, the visibility is set from `UpdateFromModel()`.
  // The Keyword and Pedal buttons also get their text from there, since the
  // text depends on the actual match. That shouldn't produce a flicker, because
  // it's called directly from OmniboxResultView::SetMatch(). If this flickers,
  // then so does everything else in the result view.

  embeddings_chip_ = AddChildView(std::make_unique<OmniboxSuggestionRowChip>(
      l10n_util::GetStringUTF16(IDS_OMNIBOX_HISTORY_EMBEDDING_HINT),
      omnibox::kSparkIcon));

  {
    OmniboxPopupSelection selection(model_index_,
                                    OmniboxPopupSelection::KEYWORD_MODE);
    keyword_button_ = AddChildView(std::make_unique<OmniboxSuggestionRowButton>(
        base::BindRepeating(&OmniboxSuggestionButtonRowView::ButtonPressed,
                            base::Unretained(this), selection),
        CONTEXT_OMNIBOX_PRIMARY,
        vector_icons::kSearchChromeRefreshIcon, gfx::Image(), popup_view_,
        selection));
  }

  // Only create buttons for existent actions.
  for (size_t action_index = 0; action_index < match().actions.size();
       action_index++) {
    OmniboxPopupSelection selection(
        model_index_, OmniboxPopupSelection::FOCUSED_BUTTON_ACTION,
        action_index);
    auto* button = AddChildView(std::make_unique<OmniboxSuggestionRowButton>(
        base::BindRepeating(&OmniboxSuggestionButtonRowView::ButtonPressed,
                            base::Unretained(this), selection),
        match().IsToolbelt()
            ? CONTEXT_OMNIBOX_TOOLBELT_BUTTON
            : CONTEXT_OMNIBOX_PRIMARY,
        match().actions[action_index]->GetVectorIcon(),
        match().actions[action_index]->GetIconImage(), popup_view_, selection));
    action_buttons_.push_back(button);
  }
}

OmniboxSuggestionButtonRowView::~OmniboxSuggestionButtonRowView() = default;

void OmniboxSuggestionButtonRowView::Layout(PassKey) {
  LayoutSuperclass<View>(this);

  const auto bounds = GetLocalBounds();
  SkPath path;
  path.addRect(RectToSkRect(bounds), SkPathDirection::kCW, 0);
  SetClipPath(path);
}

void OmniboxSuggestionButtonRowView::UpdateFromModel() {
  if (!HasMatch()) {
    // Skip remaining code that depends on `match()`.
    return;
  }

  // Only build views if there was a structural change. Without this check,
  // performance could be impacted by frequent unnecessary rebuilds.
  // Note, the toolbelt is always rebuilt because its action count is mostly
  // constant but selection changes frequently invalidate button focus states.
  // TODO(crbug.com/429029560): try removing this optimization or making the
  // conditions smarter.
  if (action_buttons_.size() != match().actions.size() ||
      (match().IsToolbelt() &&
       omnibox_feature_configs::Toolbelt::Get().rebuild_button_row_views)) {
    BuildViews();
  }

  embeddings_chip_->SetVisible(match().type ==
                               AutocompleteMatchType::HISTORY_EMBEDDINGS);

  if (match().HasInstantKeyword(
          popup_view_->controller()->client()->GetTemplateURLService())) {
    keyword_button_->SetVisible(false);
  } else {
    SetPillButtonVisibility(keyword_button_,
                            OmniboxPopupSelection::KEYWORD_MODE);
    if (keyword_button_->GetVisible()) {
      std::u16string keyword;
      std::u16string keyword_placeholder;
      bool is_keyword_hint = false;
      match().GetKeywordUIState(
          popup_view_->controller()->client()->GetTemplateURLService(),
          popup_view_->controller()->client()->IsHistoryEmbeddingsEnabled(),
          &keyword, &keyword_placeholder, &is_keyword_hint);

      const auto names = SelectedKeywordView::GetKeywordLabelNames(
          keyword,
          popup_view_->controller()->client()->GetTemplateURLService());
      keyword_button_->SetText(names.full_name);
      keyword_button_->GetViewAccessibility().SetName(
          l10n_util::GetStringFUTF16(IDS_ACC_KEYWORD_MODE, names.short_name));
    }
  }

  for (const auto& action_button : action_buttons_) {
    SetPillButtonVisibility(action_button,
                            OmniboxPopupSelection::FOCUSED_BUTTON_ACTION);
    if (action_button->GetVisible()) {
      const OmniboxAction* action =
          match().actions[action_button->selection().action_index].get();
      const auto label_strings = action->GetLabelStrings();
      action_button->SetText(label_strings.hint);
      action_button->SetTooltipText(label_strings.suggestion_contents);
      action_button->GetViewAccessibility().SetName(
          label_strings.accessibility_hint);
      if (!action->GetIconImage().IsEmpty()) {
        action_button->SetImage(action->GetIconImage());
      } else {
        action_button->SetIcon(action->GetVectorIcon());
      }
    }
  }

  const bool is_any_child_visible =
      embeddings_chip_->GetVisible() || keyword_button_->GetVisible() ||
      std::ranges::any_of(action_buttons_, [](const auto& action_button) {
        return action_button->GetVisible();
      });
  SetVisible(is_any_child_visible);
}

void OmniboxSuggestionButtonRowView::SelectionStateChanged() {
  auto* const active_button = GetActiveButton();
  if (active_button == previous_active_button_) {
    return;
  }
  if (previous_active_button_) {
    views::FocusRing::Get(previous_active_button_)->SchedulePaint();
    previous_active_button_->GetViewAccessibility().SetIsSelected(false);
  }
  if (active_button) {
    views::FocusRing::Get(active_button)->SchedulePaint();
    active_button->GetViewAccessibility().SetIsSelected(true);
  }
  previous_active_button_ = active_button;
}

void OmniboxSuggestionButtonRowView::SetThemeState(
    OmniboxPartState theme_state) {
  if (embeddings_chip_) {
    embeddings_chip_->SetThemeState(theme_state);
  }
  if (keyword_button_) {
    keyword_button_->SetThemeState(theme_state);
  }
  for (const auto& action_button : action_buttons_) {
    action_button->SetThemeState(theme_state);
  }
}

views::Button* OmniboxSuggestionButtonRowView::GetActiveButton() const {
  if (!HasMatch()) {
    return nullptr;
  }

  std::vector<OmniboxSuggestionRowButton*> buttons{keyword_button_};
  buttons.insert(buttons.end(), action_buttons_.begin(), action_buttons_.end());

  // Find the button that matches model selection.
  auto selected_button =
      std::ranges::find(buttons, popup_view_->GetSelection(),
                        &OmniboxSuggestionRowButton::selection);
  return selected_button == buttons.end() ? nullptr : *selected_button;
}

bool OmniboxSuggestionButtonRowView::HasMatch() const {
  return popup_view_->controller()->autocomplete_controller()->result().size() >
         model_index_;
}

const AutocompleteMatch& OmniboxSuggestionButtonRowView::match() const {
  return popup_view_->controller()
      ->autocomplete_controller()
      ->result()
      .match_at(model_index_);
}

void OmniboxSuggestionButtonRowView::SetPillButtonVisibility(
    OmniboxSuggestionRowButton* button,
    OmniboxPopupSelection::LineState state) {
  button->SetVisible(popup_view_->model()->IsPopupControlPresentOnMatch(
      OmniboxPopupSelection(model_index_, state)));
}

void OmniboxSuggestionButtonRowView::ButtonPressed(
    const OmniboxPopupSelection selection,
    const ui::Event& event) {
  if (selection.state == OmniboxPopupSelection::KEYWORD_MODE) {
    // Note: Since keyword mode logic depends on state of the edit model, the
    // selection must first be set to prepare for keyword mode before accepting.
    popup_view_->model()->SetPopupSelection(selection);
    // Don't re-enter keyword mode if already in it. This occurs when the user
    // was in keyword mode and re-clicked the same or a different keyword chip.
    if (popup_view_->model()->is_keyword_hint()) {
      const auto entry_method =
          event.IsMouseEvent() ? metrics::OmniboxEventProto::CLICK_HINT_VIEW
                               : metrics::OmniboxEventProto::TAP_HINT_VIEW;
      popup_view_->model()->AcceptKeyword(entry_method);
    }
  } else {
    if (omnibox_feature_configs::Toolbelt::Get()
            .select_toolbelt_before_opening &&
        match().IsToolbelt()) {
      popup_view_->model()->SetPopupSelection(selection);
    }
    WindowOpenDisposition disposition =
        ui::DispositionFromEventFlags(event.flags());
    popup_view_->model()->OpenSelection(selection, event.time_stamp(),
                                        disposition,
                                        /*via_keyboard=*/event.IsKeyEvent());
  }
}

BEGIN_METADATA(OmniboxSuggestionButtonRowView)
END_METADATA