File: popup_cell_utils.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 (581 lines) | stat: -rw-r--r-- 24,249 bytes parent folder | download | duplicates (2)
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
// 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/autofill/popup/popup_cell_utils.h"

#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>

#include "base/check.h"
#include "base/check_op.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "build/branding_buildflags.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/ui/passwords/ui_utils.h"
#include "chrome/browser/ui/views/autofill/payments/payments_view_util.h"
#include "chrome/browser/ui/views/autofill/popup/popup_base_view.h"
#include "chrome/browser/ui/views/autofill/popup/popup_row_content_view.h"
#include "chrome/browser/ui/views/autofill/popup/popup_row_view.h"
#include "chrome/browser/ui/views/autofill/popup/popup_view_utils.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/webid/identity_ui_utils.h"
#include "components/autofill/core/browser/filling/filling_product.h"
#include "components/autofill/core/browser/suggestions/suggestion.h"
#include "components/autofill/core/browser/suggestions/suggestion_type.h"
#include "components/autofill/core/browser/ui/autofill_resource_utils.h"
#include "components/omnibox/browser/vector_icons.h"
#include "components/strings/grit/components_strings.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/image_model.h"
#include "ui/base/models/image_model_utils.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider_manager.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/border.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/throbber.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/layout/table_layout.h"
#include "ui/views/layout/table_layout_view.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"

#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
#include "components/plus_addresses/resources/vector_icons.h"
#endif

namespace autofill::popup_cell_utils {

namespace {

// The default icon size used in the suggestion drop down.
constexpr int kIconSize = 16;
constexpr int kChromeRefreshIconSize = 20;
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
constexpr int kGooglePayLogoWidth = 40;
// The icon size used in the suggestion dropdown for displaying the Google
// Wallet icon in the "Manage loyalty cards" entry and in all loyalty cards
// submenu entries.
constexpr int kGoogleWalletIconSize = 20;
#endif

// The additional height of the row in case it has two lines of text.
constexpr int kAutofillPopupAdditionalDoubleRowHeight = 16;

// The additional padding of the row in case it has three lines of text.
constexpr int kAutofillPopupAdditionalVerticalPadding = 16;

// Vertical spacing between labels in one row.
constexpr int kAdjacentLabelsVerticalSpacing = 2;

// The icon size used in the suggestion dropdown for displaying the Google
// Password Manager icon in the Manager Passwords entry.
constexpr int kGooglePasswordManagerIconSize = 20;

// Metric to measure the duration of getting the image for the Autofill pop-up.
constexpr char kHistogramGetImageViewByName[] =
    "Autofill.PopupGetImageViewTime";

// Returns the name of the network for payment method icons, empty string
// otherwise.
std::u16string GetIconAccessibleName(Suggestion::Icon icon) {
  // Networks for which icons are currently shown.
  switch (icon) {
    case Suggestion::Icon::kCardAmericanExpress:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX);
    case Suggestion::Icon::kCardDiners:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_DINERS);
    case Suggestion::Icon::kCardDiscover:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_DISCOVER);
    case Suggestion::Icon::kCardElo:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_ELO);
    case Suggestion::Icon::kCardJCB:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_JCB);
    case Suggestion::Icon::kCardMasterCard:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_MASTERCARD);
    case Suggestion::Icon::kCardMir:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_MIR);
    case Suggestion::Icon::kCardTroy:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_TROY);
    case Suggestion::Icon::kCardUnionPay:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_UNION_PAY);
    case Suggestion::Icon::kCardVerve:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_VERVE);
    case Suggestion::Icon::kCardVisa:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_VISA);
    // Other networks.
    case Suggestion::Icon::kCardGeneric:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_GENERIC);
    case Suggestion::Icon::kIban:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_IBAN_GENERIC);
    case Suggestion::Icon::kAccount:
    case Suggestion::Icon::kBnpl:
    case Suggestion::Icon::kClear:
    case Suggestion::Icon::kCode:
    case Suggestion::Icon::kCreate:
    case Suggestion::Icon::kDelete:
    case Suggestion::Icon::kDevice:
    case Suggestion::Icon::kVehicle:
    case Suggestion::Icon::kEdit:
    case Suggestion::Icon::kEmail:
    case Suggestion::Icon::kError:
    case Suggestion::Icon::kGlobe:
    case Suggestion::Icon::kGoogle:
    case Suggestion::Icon::kGoogleMonochrome:
    case Suggestion::Icon::kGooglePasswordManager:
    case Suggestion::Icon::kGooglePay:
    case Suggestion::Icon::kGoogleWallet:
    case Suggestion::Icon::kGoogleWalletMonochrome:
    case Suggestion::Icon::kHome:
    case Suggestion::Icon::kHttpsInvalid:
    case Suggestion::Icon::kHttpWarning:
    case Suggestion::Icon::kIdCard:
    case Suggestion::Icon::kKey:
    case Suggestion::Icon::kLocation:
    case Suggestion::Icon::kLoyalty:
    case Suggestion::Icon::kMagic:
    case Suggestion::Icon::kNoIcon:
    case Suggestion::Icon::kOfferTag:
    case Suggestion::Icon::kPenSpark:
    case Suggestion::Icon::kPlusAddress:
    case Suggestion::Icon::kSaveAndFill:
    case Suggestion::Icon::kScanCreditCard:
    case Suggestion::Icon::kSettings:
    case Suggestion::Icon::kSettingsAndroid:
    case Suggestion::Icon::kUndo:
    case Suggestion::Icon::kWork:
      return std::u16string();
  }
  NOTREACHED();
}

std::optional<ui::ImageModel> ImageModelFromImageSkia(
    const gfx::ImageSkia& image_skia) {
  if (image_skia.isNull()) {
    return std::nullopt;
  }
  auto image_model = ui::ImageModel::FromImageSkia(image_skia);
  return image_model;
}

// Converts the `image_model` to an `ImageView`. If `apply_deactivated_style` is
// true, the image will be converted to a disabled image.
std::unique_ptr<views::ImageView> ConvertModelToImageView(
    std::optional<ui::ImageModel> image_model,
    bool apply_deactivated_style) {
  if (!image_model) {
    return nullptr;
  }
  if (apply_deactivated_style) {
    image_model = ui::GetDefaultDisabledIconFromImageModel(
        image_model.value(),
        ui::ColorProviderManager::Get().GetColorProviderFor(
            ui::NativeTheme::GetInstanceForNativeUi()->GetColorProviderKey(
                nullptr)));
  }
  return std::make_unique<views::ImageView>(image_model.value());
}

// Creates the table in which all the Autofill suggestion content apart from
// leading and trailing icons is contained.
std::unique_ptr<views::TableLayoutView> CreateSuggestionContentTable(
    std::unique_ptr<views::Label> main_text_label,
    std::vector<std::unique_ptr<views::View>> minor_text_labels,
    std::unique_ptr<views::Label> description_label,
    std::vector<std::unique_ptr<views::View>> subtext_views) {
  const bool kHasTwoColumns = !!description_label;
  auto table =
      views::Builder<views::TableLayoutView>()
          .AddColumn(views::LayoutAlignment::kStart,
                     views::LayoutAlignment::kStretch,
                     views::TableLayout::kFixedSize,
                     views::TableLayout::ColumnSize::kUsePreferred, 0, 0)
          .Build();
  if (kHasTwoColumns) {
    const int kDividerSpacing = ChromeLayoutProvider::Get()->GetDistanceMetric(
        DISTANCE_RELATED_LABEL_HORIZONTAL_LIST);
    table->AddPaddingColumn(views::TableLayout::kFixedSize, kDividerSpacing);
    table->AddColumn(views::LayoutAlignment::kStart,
                     views::LayoutAlignment::kStretch,
                     views::TableLayout::kFixedSize,
                     views::TableLayout::ColumnSize::kUsePreferred, 0, 0);
  }

  // Major and minor text go into the first row, first column.
  table->AddRows(1, 0);
  if (!minor_text_labels.empty()) {
    auto first_line_container = std::make_unique<views::View>();
    first_line_container
        ->SetLayoutManager(std::make_unique<views::FlexLayout>())
        ->SetOrientation(views::LayoutOrientation::kHorizontal)
        .SetMainAxisAlignment(views::LayoutAlignment::kStart)
        .SetCrossAxisAlignment(views::LayoutAlignment::kCenter)
        .SetIgnoreDefaultMainAxisMargins(true)
        .SetCollapseMargins(true)
        .SetDefault(
            views::kMarginsKey,
            gfx::Insets::VH(0, ChromeLayoutProvider::Get()->GetDistanceMetric(
                                   DISTANCE_RELATED_LABEL_HORIZONTAL_LIST)));

    first_line_container->AddChildView(std::move(main_text_label));
    for (auto& minor_text : minor_text_labels) {
      first_line_container->AddChildView(std::move(minor_text));
    }
    table->AddChildView(std::move(first_line_container));
  } else {
    table->AddChildView(std::move(main_text_label));
  }

  // The description goes into the first row, second column.
  if (kHasTwoColumns) {
    table->AddChildView(description_label ? std::move(description_label)
                                          : std::make_unique<views::View>());
  }

  // Every subtext label goes into an additional row.
  for (std::unique_ptr<views::View>& subtext_view : subtext_views) {
    table->AddPaddingRow(0, kAdjacentLabelsVerticalSpacing).AddRows(1, 0);
    table->AddChildView(std::move(subtext_view));
    if (kHasTwoColumns) {
      table->AddChildView(std::make_unique<views::View>());
    }
  }
  return table;
}

}  // namespace

std::optional<ui::ImageModel> GetIconImageModelFromIcon(Suggestion::Icon icon) {
  switch (icon) {
    case Suggestion::Icon::kNoIcon:
      return std::nullopt;
    case Suggestion::Icon::kHome:
      return ImageModelFromVectorIcon(vector_icons::kHomeIcon, kIconSize);
    case Suggestion::Icon::kWork:
      return ImageModelFromVectorIcon(vector_icons::kWorkIcon, kIconSize);
    case Suggestion::Icon::kAccount:
      return ImageModelFromVectorIcon(kAccountCircleIcon, kIconSize);
    case Suggestion::Icon::kClear:
      return ImageModelFromVectorIcon(kBackspaceIcon, kIconSize);
    case Suggestion::Icon::kCode:
      return ImageModelFromVectorIcon(vector_icons::kCodeIcon, kIconSize);
    case Suggestion::Icon::kDelete:
      return ImageModelFromVectorIcon(kTrashCanRefreshIcon,
                                      kChromeRefreshIconSize);
    case Suggestion::Icon::kDevice:
      return ImageModelFromVectorIcon(kDevicesIcon, kIconSize);
    case Suggestion::Icon::kVehicle:
      return ImageModelFromVectorIcon(vector_icons::kDirectionsCarIcon,
                                      kChromeRefreshIconSize);
    case Suggestion::Icon::kEdit:
      return ImageModelFromVectorIcon(vector_icons::kEditChromeRefreshIcon,
                                      kChromeRefreshIconSize);
    case Suggestion::Icon::kEmail:
      return ImageModelFromVectorIcon(vector_icons::kEmailOutlineIcon,
                                      kIconSize);
    case Suggestion::Icon::kError:
      return ui::ImageModel::FromVectorIcon(vector_icons::kErrorIcon,
                                            ui::kColorSysError, kIconSize);
    case Suggestion::Icon::kGlobe:
      return ImageModelFromVectorIcon(kGlobeIcon, kIconSize);
    case Suggestion::Icon::kGoogle:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromImageSkia(gfx::CreateVectorIcon(
          vector_icons::kGoogleGLogoIcon, kIconSize, gfx::kPlaceholderColor));
#else
      return std::nullopt;
#endif
    case Suggestion::Icon::kGoogleMonochrome:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromVectorIcon(vector_icons::kGoogleGLogoMonochromeIcon,
                                      kIconSize);
#else
      return ImageModelFromVectorIcon(vector_icons::kEmailIcon, kIconSize);
#endif
    case Suggestion::Icon::kHttpWarning:
      // For the http warning message, get the icon images from VectorIcon,
      // which is the same as the security indicator icons in the location bar.
      return ImageModelFromVectorIcon(omnibox::kHttpIcon, kIconSize);
    case Suggestion::Icon::kHttpsInvalid:
      return ui::ImageModel::FromVectorIcon(vector_icons::kNotSecureWarningIcon,
                                            ui::kColorAlertHighSeverity,
                                            kIconSize);
    case Suggestion::Icon::kIdCard:
      return ImageModelFromVectorIcon(vector_icons::kIdCardIcon,
                                      kChromeRefreshIconSize);
    case Suggestion::Icon::kKey:
      return ImageModelFromVectorIcon(kKeyIcon, kIconSize);
    case Suggestion::Icon::kLocation:
      return ImageModelFromVectorIcon(
          vector_icons::kLocationOnChromeRefreshIcon, kChromeRefreshIconSize);
    case Suggestion::Icon::kLoyalty:
      return ImageModelFromVectorIcon(vector_icons::kLoyaltyIcon,
                                      kChromeRefreshIconSize);
    case Suggestion::Icon::kMagic:
      return ImageModelFromVectorIcon(vector_icons::kMagicButtonIcon,
                                      kIconSize);
    case Suggestion::Icon::kPenSpark:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromVectorIcon(vector_icons::kPenSparkIcon, kIconSize);
#else
      return ImageModelFromVectorIcon(vector_icons::kEditIcon, kIconSize);
#endif
    case Suggestion::Icon::kPlusAddress:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromVectorIcon(plus_addresses::kPlusAddressLogoSmallIcon,
                                      kIconSize);
#else
      return ImageModelFromVectorIcon(vector_icons::kEmailIcon, kIconSize);
#endif
    case Suggestion::Icon::kSaveAndFill:
      return ImageModelFromVectorIcon(kCreditCardIcon, kIconSize);
    case Suggestion::Icon::kSettings:
      return ImageModelFromVectorIcon(omnibox::kProductIcon, kIconSize);
    case Suggestion::Icon::kUndo:
      return ImageModelFromVectorIcon(vector_icons::kUndoIcon, kIconSize);
    case Suggestion::Icon::kGooglePasswordManager:
      return ImageModelFromVectorIcon(GooglePasswordManagerVectorIcon(),
                                      kGooglePasswordManagerIconSize);
    case Suggestion::Icon::kGooglePay:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ui::ImageModel::FromImageGenerator(
          base::BindRepeating(&CreateTiledGooglePayLogo, kGooglePayLogoWidth,
                              kIconSize),
          gfx::Size(kGooglePayLogoWidth, kIconSize));
#else
      return ImageModelFromVectorIcon(kCreditCardIcon, kIconSize);
#endif
    case Suggestion::Icon::kGoogleWallet:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromVectorIcon(vector_icons::kGoogleWalletIcon,
                                      kGoogleWalletIconSize);
#else
      return std::nullopt;
#endif
    case Suggestion::Icon::kGoogleWalletMonochrome:
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
      return ImageModelFromVectorIcon(vector_icons::kGoogleWalletMonochromeIcon,
                                      kGoogleWalletIconSize);
#else
      return std::nullopt;
#endif
    case Suggestion::Icon::kIban:
    case Suggestion::Icon::kCreate:
    case Suggestion::Icon::kOfferTag:
    case Suggestion::Icon::kScanCreditCard:
    case Suggestion::Icon::kSettingsAndroid:
    case Suggestion::Icon::kCardGeneric:
    case Suggestion::Icon::kCardAmericanExpress:
    case Suggestion::Icon::kCardDiners:
    case Suggestion::Icon::kCardDiscover:
    case Suggestion::Icon::kCardElo:
    case Suggestion::Icon::kCardJCB:
    case Suggestion::Icon::kCardMasterCard:
    case Suggestion::Icon::kCardMir:
    case Suggestion::Icon::kCardTroy:
    case Suggestion::Icon::kCardUnionPay:
    case Suggestion::Icon::kCardVerve:
    case Suggestion::Icon::kCardVisa:
    case Suggestion::Icon::kBnpl: {
      // For other suggestion entries, get the icon from PNG files.
      int icon_id = GetIconResourceID(icon);
      DCHECK_NE(icon_id, 0);
      return ImageModelFromImageSkia(
          *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(icon_id));
    }
  }
  NOTREACHED();
}

std::u16string GetVoiceOverStringFromSuggestion(const Suggestion& suggestion) {
  if (suggestion.voice_over) {
    return *suggestion.voice_over;
  }

  std::vector<std::u16string> text;
  auto add_if_not_empty = [&text](std::u16string value) {
    if (!value.empty()) {
      text.push_back(std::move(value));
    }
  };

  add_if_not_empty(GetIconAccessibleName(suggestion.icon));
  text.push_back(suggestion.main_text.value);
  if (!suggestion.minor_texts.empty()) {
    std::vector<std::u16string> text_values;
    for (const auto& minor_text : suggestion.minor_texts) {
      text_values.push_back(minor_text.value);
    }
    std::u16string sublabel = base::JoinString(text_values, u" ");
    add_if_not_empty(sublabel);
  }

  for (const std::vector<Suggestion::Text>& row : suggestion.labels) {
    for (const Suggestion::Text& label : row) {
      // `label_text` is not populated for footers or autocomplete entries.
      add_if_not_empty(label.value);
    }
  }

  // `additional_label` is only populated in a passwords context.
  add_if_not_empty(suggestion.additional_label);

  return base::JoinString(text, u" ");
}

std::unique_ptr<views::ImageView> GetIconImageView(
    const Suggestion& suggestion) {
  base::TimeTicks start_time = base::TimeTicks::Now();

  if (auto* icon = std::get_if<gfx::Image>(&suggestion.custom_icon);
      icon && !icon->IsEmpty()) {
    gfx::ImageSkia image = icon->AsImageSkia();
    if (std::holds_alternative<Suggestion::IdentityCredentialPayload>(
            suggestion.payload)) {
      image = webid::CreateCircleCroppedImage(
          image, webid::kDesiredAvatarSizeInAutofillDropdown);
    }
    return ConvertModelToImageView(ImageModelFromImageSkia(image),
                                   suggestion.HasDeactivatedStyle());
  }
  std::unique_ptr<views::ImageView> icon_image_view =
      ConvertModelToImageView(GetIconImageModelFromIcon(suggestion.icon),
                              suggestion.HasDeactivatedStyle());
  base::UmaHistogramTimes(kHistogramGetImageViewByName,
                          base::TimeTicks::Now() - start_time);

  if (icon_image_view) {
    // It is possible to have icons of different sizes (kChromeRefreshIconSize
    // and kIconSize) on the same popup. Setting the icon view width to
    // the largest value ensures that the icon occupies consistent horizontal
    // space and makes icons (and the text after them) aligned. It expands
    // the area of kIconSize icons only and doesn't change those that are bigger
    // by design (e.g. payment card icons) and have no alignment issues.
    gfx::Size size = icon_image_view->GetPreferredSize();
    size.set_width(std::max(kChromeRefreshIconSize, size.width()));
    icon_image_view->SetPreferredSize(size);
  }

  return icon_image_view;
}

std::unique_ptr<views::ImageView> GetTrailingIconImageView(
    const Suggestion& suggestion) {
  base::TimeTicks start_time = base::TimeTicks::Now();
  std::optional<ui::ImageModel> image_model =
      GetIconImageModelFromIcon(suggestion.trailing_icon);
  std::unique_ptr<views::ImageView> icon_image_view =
      ConvertModelToImageView(image_model, suggestion.HasDeactivatedStyle());
  base::UmaHistogramTimes(kHistogramGetImageViewByName,
                          base::TimeTicks::Now() - start_time);

  return icon_image_view;
}

void AddSpacerWithSize(views::BoxLayoutView& view,
                       int spacer_width,
                       bool resize) {
  auto spacer = views::Builder<views::View>()
                    .SetPreferredSize(gfx::Size(spacer_width, 1))
                    .Build();
  view.SetFlexForView(view.AddChildView(std::move(spacer)),
                      /*flex=*/resize ? 1 : 0,
                      /*use_min_size=*/true);
}

void AddSuggestionContentToView(
    const Suggestion& suggestion,
    std::unique_ptr<views::Label> main_text_label,
    std::vector<std::unique_ptr<views::View>> minor_text_labels,
    std::unique_ptr<views::Label> description_label,
    std::vector<std::unique_ptr<views::View>> subtext_views,
    std::unique_ptr<views::View> icon,
    PopupRowContentView& content_view) {
  // Adjust the row height based on the number of subtexts (lines of text).
  int row_height = views::MenuConfig::instance().touchable_menu_height;
  if (!subtext_views.empty()) {
    row_height += kAutofillPopupAdditionalDoubleRowHeight;
  }
  content_view.SetMinimumCrossAxisSize(row_height);

  // If there are three rows in total, add extra padding to avoid cramming.
  DCHECK_LE(subtext_views.size(), 2u);
  if (subtext_views.size() == 2u) {
    content_view.SetInsideBorderInsets(
        gfx::Insets(content_view.GetInsideBorderInsets())
            .set_top_bottom(kAutofillPopupAdditionalVerticalPadding,
                            kAutofillPopupAdditionalVerticalPadding));
  }

  // The leading icon.
  if (suggestion.is_loading) {
    views::Throbber* throbber =
        content_view.AddChildView(std::make_unique<views::Throbber>());
    if (icon) {
      // Prevent that the layout is shifted when transitioning from throbber to
      // icon and vice versa when there is a width difference.
      const int size_delta =
          icon->GetMinimumSize().width() - throbber->GetMinimumSize().width();
      throbber->SetProperty(views::kMarginsKey,
                            gfx::Insets::VH(0, std::max(size_delta, 0) / 2));
    }
    throbber->Start();
    AddSpacerWithSize(content_view, PopupBaseView::ArrowHorizontalMargin(),
                      /*resize=*/false);
    content_view.SetEnabled(false);
  } else if (icon) {
    content_view.AddChildView(std::move(icon));
    AddSpacerWithSize(content_view, PopupBaseView::ArrowHorizontalMargin(),
                      /*resize=*/false);
  }

  // The actual content table.
  content_view.SetFlexForView(
      content_view.AddChildView(CreateSuggestionContentTable(
          std::move(main_text_label), std::move(minor_text_labels),
          std::move(description_label), std::move(subtext_views))),
      1);

  // The trailing icon.
  if (std::unique_ptr<views::ImageView> trailing_icon =
          GetTrailingIconImageView(suggestion)) {
    AddSpacerWithSize(content_view, PopupBaseView::ArrowHorizontalMargin(),
                      /*resize=*/true);
    content_view.AddChildView(std::move(trailing_icon));
  }

  // Force a refresh to ensure all the labels'styles are correct.
  content_view.UpdateStyle(/*selected=*/false);
}

ui::ImageModel ImageModelFromVectorIcon(const gfx::VectorIcon& vector_icon,
                                        int icon_size = kIconSize) {
  return ui::ImageModel::FromVectorIcon(vector_icon, ui::kColorIcon, icon_size);
}

const gfx::VectorIcon& GetExpandableMenuIcon(SuggestionType type) {
  CHECK(IsExpandableSuggestionType(type));
  // Only compose suggestions have a different expandable icon.
  return GetFillingProductFromSuggestionType(type) == FillingProduct::kCompose
             ? kBrowserToolsChromeRefreshIcon
             : vector_icons::kSubmenuArrowChromeRefreshIcon;
}

}  // namespace autofill::popup_cell_utils