File: submenu_view.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; 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,806; 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 (736 lines) | stat: -rw-r--r-- 25,371 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
// 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 "ui/views/controls/menu/submenu_view.h"

#include <algorithm>
#include <numeric>
#include <set>
#include <tuple>
#include <utility>
#include <vector>

#include "base/compiler_specific.h"
#include "base/containers/contains.h"
#include "base/numerics/safe_conversions.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_host.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_scroll_view_container.h"
#include "ui/views/controls/menu/menu_separator.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"

namespace views {

namespace {

// Height of the drop indicator. This should be an even number.
constexpr int kDropIndicatorHeight = 2;

template <typename MIV, typename V>
std::vector<MIV*> GetMenuItemsFromChildren(const View::Views& children) {
  std::vector<MIV*> menu_items;
  std::ranges::transform(children, std::back_inserter(menu_items),
                         static_cast<MIV* (*)(V*)>(&AsViewClass<MenuItemView>));
  std::erase_if(menu_items, [](MIV* item) {
    return !item || IsViewClass<EmptyMenuMenuItem>(item);
  });
  return menu_items;
}

}  // namespace

SubmenuView::SubmenuView(MenuItemView* parent) : parent_menu_item_(parent) {
  CHECK(parent_menu_item_);
  // We'll delete ourselves, otherwise the ScrollView would delete us on close.
  set_owned_by_client(OwnedByClientPassKey());

  // Menus in Chrome are always traversed in a vertical direction.
  GetViewAccessibility().SetIsVertical(true);
  GetViewAccessibility().SetRole(ax::mojom::Role::kMenu);
}

SubmenuView::~SubmenuView() {
  // The menu may not have been closed yet (it will be hidden, but not
  // necessarily closed).
  Close();
}

std::vector<MenuItemView*> SubmenuView::GetMenuItems() {
  return GetMenuItemsFromChildren<MenuItemView, View>(children());
}

std::vector<const MenuItemView*> SubmenuView::GetMenuItems() const {
  return GetMenuItemsFromChildren<const MenuItemView, const View>(children());
}

MenuItemView* SubmenuView::GetMenuItemAt(size_t index) {
  const auto menu_items = GetMenuItems();
  CHECK_LT(index, menu_items.size());
  return menu_items[index];
}

int SubmenuView::GetPreferredItemHeight() const {
  EmptyMenuMenuItem menu_item(parent_menu_item_);
  menu_item.set_controller(parent_menu_item_->GetMenuController());
  return menu_item.GetPreferredSize({}).height();
}

PrefixSelector* SubmenuView::GetPrefixSelector() {
  return &prefix_selector_;
}

void SubmenuView::UpdateMenuPartSizes() {
  const MenuConfig& config = MenuConfig::instance();

  const auto get_metrics = [&] {
    return std::tie(icon_area_width_, label_start_, trailing_padding_);
  };
  const auto old_metrics = get_metrics();

  trailing_padding_ = config.item_horizontal_padding +
                      parent_menu_item_->GetItemHorizontalBorder();
  const auto& menu_items = GetMenuItems();
  if (config.reserve_dedicated_arrow_column &&
      std::ranges::any_of(menu_items, &MenuItemView::HasSubmenu)) {
    trailing_padding_ +=
        config.arrow_size +
        (base::Contains(menu_items, MenuItemView::Type::kActionableSubMenu,
                        &MenuItemView::GetType)
             ? config.actionable_submenu_arrow_to_edge_padding
             : config.arrow_to_edge_padding);
  }

  const auto is_check_or_radio = [](const auto* item) {
    const auto type = item->GetType();
    return type == MenuItemView::Type::kCheckbox ||
           type == MenuItemView::Type::kRadio;
  };
  icon_area_width_ = min_icon_height_ =
      (config.always_reserve_check_region ||
       std::ranges::any_of(menu_items, is_check_or_radio))
          ? kMenuCheckSize
          : 0;
  int max_icon_width = 0;
  if (!menu_items.empty()) {
    std::vector<int> widths(menu_items.size());
    std::ranges::transform(
        menu_items, widths.begin(), [&](const MenuItemView* item) {
          const auto icon_size = item->GetIconPreferredSize();
          if (icon_size.IsEmpty()) {
            return 0;
          }
          min_icon_height_ = std::max(min_icon_height_, kMenuCheckSize);
          // If this item has a radio or checkbox, an additional icon will not
          // affect horizontal alignment of other items.
          return (config.icons_in_label || !is_check_or_radio(item))
                     ? icon_size.width()
                     : 0;
        });
    max_icon_width = std::ranges::max(widths);
  }
  if (!config.icons_in_label) {
    icon_area_width_ = std::max(icon_area_width_, max_icon_width);
  }

  label_start_ = parent_menu_item_->GetContentStart() + icon_area_width_;
  if (icon_area_width_) {
    const auto* const controller = parent_menu_item_->GetMenuController();
    label_start_ += (controller && controller->use_ash_system_ui_layout())
                        ? config.touchable_item_horizontal_padding
                        : config.icon_label_spacing;
  }

  if (config.icons_in_label) {
    icon_area_width_ = max_icon_width;
  }

  if (get_metrics() != old_metrics) {
    InvalidateLayout();
  }
}

void SubmenuView::ChildPreferredSizeChanged(View* child) {
  if (!resize_open_menu_) {
    return;
  }

  MenuItemView* item = parent_menu_item_;
  MenuController* controller = item->GetMenuController();

  if (controller) {
    MenuController::MenuOpenDirection dir;
    ui::OwnedWindowAnchor anchor;
    gfx::Rect bounds = controller->CalculateMenuBounds(
        item, MenuController::MenuOpenDirection::kTrailing, &dir, &anchor);
    Reposition(bounds, anchor);
  }
}

void SubmenuView::Layout(PassKey) {
  // We're in a ScrollView, and need to set our width/height ourselves.
  if (!parent()) {
    return;
  }

  // Use our current y, unless it means part of the menu isn't visible anymore.
  const int pref_height = GetPreferredSize(SizeBounds(size())).height();
  SetBounds(x(),
            (pref_height > parent()->height())
                ? std::max(parent()->height() - pref_height, y())
                : 0,
            parent()->width(), pref_height);

  const gfx::Insets insets = GetInsets();
  const int x = insets.left();
  int y = insets.top();
  const int menu_item_width = width() - insets.width();
  const int between_item_vertical_padding =
      MenuConfig::instance().between_item_vertical_padding;
  bool previous_child_was_lower_separator = false;
  for (View* child : children()) {
    if (child->GetVisible()) {
      const auto* separator = AsViewClass<MenuSeparator>(child);
      if (y != insets.top() && !previous_child_was_lower_separator &&
          (!separator || separator->GetType() != ui::UPPER_SEPARATOR)) {
        y += between_item_vertical_padding;
      }
      child->SetBounds(x, y, menu_item_width,
                       child->GetHeightForWidth(menu_item_width));
      y = child->bounds().bottom();
      previous_child_was_lower_separator =
          separator && separator->GetType() == ui::LOWER_SEPARATOR;
    }
  }
}

gfx::Size SubmenuView::CalculatePreferredSize(
    const SizeBounds& /*available_size*/) const {
  if (children().empty()) {
    return gfx::Size();
  }

  max_minor_text_width_ = 0;
  // The maximum width of items which contain maybe a label and multiple views.
  int max_complex_width = 0;
  // The max. width of items which contain a label and maybe an accelerator.
  int max_simple_width = 0;
  // The minimum width of touchable items.
  int touchable_minimum_width = 0;

  // We perform the size calculation in two passes. In the first pass, we
  // calculate the width of the menu. In the second, we calculate the height
  // using that width. This allows views that have flexible widths to adjust
  // accordingly.
  for (const View* child : children()) {
    if (!child->GetVisible()) {
      continue;
    }
    if (const auto* const menu = AsViewClass<const MenuItemView>(child)) {
      const MenuItemView::MenuItemDimensions& dimensions =
          menu->GetDimensions();
      max_simple_width = std::max(max_simple_width, dimensions.standard_width);
      max_minor_text_width_ =
          std::max(max_minor_text_width_, dimensions.minor_text_width);
      max_complex_width =
          std::max(max_complex_width,
                   dimensions.standard_width + dimensions.children_width);
      touchable_minimum_width = dimensions.standard_width;
    } else {
      max_complex_width =
          std::max(max_complex_width, child->GetPreferredSize({}).width());
    }
  }
  const auto& config = MenuConfig::instance();
  if (max_minor_text_width_ > 0) {
    max_minor_text_width_ += config.item_horizontal_padding;
  }

  // Finish calculating our optimum width.
  const gfx::Insets insets = GetInsets();
  int width = std::max(
      max_complex_width,
      std::max(max_simple_width + max_minor_text_width_ + insets.width(),
               minimum_preferred_width_ - 2 * insets.width()));

  if (parent_menu_item_->GetMenuController() &&
      parent_menu_item_->GetMenuController()->use_ash_system_ui_layout()) {
    width = std::max(touchable_minimum_width, width);
  }

  // Then, the height for that width.
  const int menu_item_width = width - insets.width();
  bool previous_child_was_lower_separator = false;
  const auto get_height = [&](int height, const View* child) {
    if (!child->GetVisible()) {
      return height;
    }
    const auto* separator = AsViewClass<MenuSeparator>(child);
    if (height && !previous_child_was_lower_separator &&
        (!separator || separator->GetType() != ui::UPPER_SEPARATOR)) {
      height += config.between_item_vertical_padding;
    }
    previous_child_was_lower_separator =
        separator && separator->GetType() == ui::LOWER_SEPARATOR;
    return height + child->GetHeightForWidth(menu_item_width);
  };
  const int height =
      std::accumulate(children().cbegin(), children().cend(), 0, get_height);

  return gfx::Size(width, height + insets.height());
}

void SubmenuView::PaintChildren(const PaintInfo& paint_info) {
  View::PaintChildren(paint_info);

  bool paint_drop_indicator = false;
  if (drop_item_) {
    switch (drop_position_) {
      case MenuDelegate::DropPosition::kNone:
      case MenuDelegate::DropPosition::kOn:
        break;
      case MenuDelegate::DropPosition::kUnknow:
      case MenuDelegate::DropPosition::kBefore:
      case MenuDelegate::DropPosition::kAfter:
        paint_drop_indicator = true;
        break;
    }
  }

  if (paint_drop_indicator) {
    gfx::Rect bounds = CalculateDropIndicatorBounds(drop_item_, drop_position_);
    ui::PaintRecorder recorder(paint_info.context(), size());
    const SkColor drop_indicator_color =
        GetColorProvider()->GetColor(ui::kColorMenuDropmarker);
    recorder.canvas()->FillRect(bounds, drop_indicator_color);
  }
}

bool SubmenuView::GetDropFormats(
    int* formats,
    std::set<ui::ClipboardFormatType>* format_types) {
  DCHECK(parent_menu_item_->GetMenuController());
  return parent_menu_item_->GetMenuController()->GetDropFormats(this, formats,
                                                                format_types);
}

bool SubmenuView::AreDropTypesRequired() {
  DCHECK(parent_menu_item_->GetMenuController());
  return parent_menu_item_->GetMenuController()->AreDropTypesRequired(this);
}

bool SubmenuView::CanDrop(const OSExchangeData& data) {
  DCHECK(parent_menu_item_->GetMenuController());
  return parent_menu_item_->GetMenuController()->CanDrop(this, data);
}

void SubmenuView::OnDragEntered(const ui::DropTargetEvent& event) {
  DCHECK(parent_menu_item_->GetMenuController());
  parent_menu_item_->GetMenuController()->OnDragEntered(this, event);
}

int SubmenuView::OnDragUpdated(const ui::DropTargetEvent& event) {
  DCHECK(parent_menu_item_->GetMenuController());
  return parent_menu_item_->GetMenuController()->OnDragUpdated(this, event);
}

void SubmenuView::OnDragExited() {
  DCHECK(parent_menu_item_->GetMenuController());
  parent_menu_item_->GetMenuController()->OnDragExited(this);
}

views::View::DropCallback SubmenuView::GetDropCallback(
    const ui::DropTargetEvent& event) {
  DCHECK(parent_menu_item_->GetMenuController());
  drop_item_ = nullptr;
  return parent_menu_item_->GetMenuController()->GetDropCallback(this, event);
}

bool SubmenuView::OnMouseWheel(const ui::MouseWheelEvent& e) {
  gfx::Rect vis_bounds = GetVisibleBounds();
  const auto menu_items = GetMenuItems();
  if (vis_bounds.height() == height() || menu_items.empty()) {
    // All menu items are visible, nothing to scroll.
    return true;
  }

  auto i = std::ranges::lower_bound(menu_items, vis_bounds.y(), {},
                                    &MenuItemView::y);
  if (i == menu_items.cend()) {
    return true;
  }

  // If the first item isn't entirely visible, make it visible, otherwise make
  // the next/previous one entirely visible. If enough wasn't scrolled to show
  // any new rows, then just scroll the amount so that smooth scrolling using
  // the trackpad is possible.
  int delta = abs(e.y_offset() / ui::MouseWheelEvent::kWheelDelta);
  if (delta == 0) {
    return OnScroll(0, e.y_offset());
  }

  const auto scrolled_to_top = [&vis_bounds](const MenuItemView* item) {
    return item->y() == vis_bounds.y();
  };
  if (i != menu_items.cbegin() && !scrolled_to_top(*i)) {
    --i;
  }
  for (bool scroll_up = (e.y_offset() > 0); delta != 0; --delta) {
    int scroll_target;
    if (scroll_up) {
      if (scrolled_to_top(*i)) {
        if (i == menu_items.cbegin()) {
          break;
        }
        --i;
      }
      scroll_target = (*i)->y();
    } else {
      const auto next_iter = std::next(i);
      if (next_iter == menu_items.cend()) {
        break;
      }
      scroll_target = (*next_iter)->y();
      if (scrolled_to_top(*i)) {
        i = next_iter;
      }
    }
    ScrollRectToVisible(
        gfx::Rect(gfx::Point(0, scroll_target), vis_bounds.size()));
    vis_bounds = GetVisibleBounds();
  }

  return true;
}

void SubmenuView::OnGestureEvent(ui::GestureEvent* event) {
  bool handled = true;
  switch (event->type()) {
    case ui::EventType::kGestureScrollBegin:
      scroll_animator_->Stop();
      break;
    case ui::EventType::kGestureScrollUpdate:
      handled = OnScroll(0, event->details().scroll_y());
      break;
    case ui::EventType::kGestureScrollEnd:
      break;
    case ui::EventType::kScrollFlingStart:
      if (event->details().velocity_y() != 0.0f) {
        scroll_animator_->Start(0, event->details().velocity_y());
      }
      break;
    case ui::EventType::kGestureTapDown:
    case ui::EventType::kScrollFlingCancel:
      if (scroll_animator_->is_scrolling()) {
        scroll_animator_->Stop();
      } else {
        handled = false;
      }
      break;
    default:
      handled = false;
      break;
  }
  if (handled) {
    event->SetHandled();
  }
}

size_t SubmenuView::GetRowCount() {
  return GetMenuItems().size();
}

std::optional<size_t> SubmenuView::GetSelectedRow() {
  const auto menu_items = GetMenuItems();
  const auto i = std::ranges::find_if(menu_items, &MenuItemView::IsSelected);
  return (i == menu_items.cend()) ? std::nullopt
                                  : std::make_optional(static_cast<size_t>(
                                        std::distance(menu_items.cbegin(), i)));
}

void SubmenuView::SetSelectedRow(std::optional<size_t> row) {
  parent_menu_item_->GetMenuController()->SetSelection(
      GetMenuItemAt(row.value()), MenuController::SELECTION_DEFAULT);
}

std::u16string SubmenuView::GetTextForRow(size_t row) {
  return MenuItemView::GetAccessibleNameForMenuItem(
      GetMenuItemAt(row)->title(), std::u16string(),
      GetMenuItemAt(row)->ShouldShowNewBadge());
}

bool SubmenuView::IsShowing() const {
  return host_ && host_->IsMenuHostVisible();
}

void SubmenuView::ShowAt(const MenuHost::InitParams& init_params) {
  if (host_) {
    host_->SetMenuHostBounds(init_params.bounds);
    host_->ShowMenuHost(init_params.do_capture);
  } else {
    host_ = new MenuHost(this);
    // Force construction of the scroll view container.
    GetScrollViewContainer();
    // Force a layout since our preferred size may not have changed but our
    // content may have.
    InvalidateLayout();

    MenuHost::InitParams new_init_params = init_params;
    new_init_params.contents_view = scroll_view_container_.get();
    host_->InitMenuHost(new_init_params);
  }

  // Only fire kMenuStart when a top level menu is being shown to notify that
  // menu interaction is about to begin. Note that the ScrollViewContainer
  // is not exposed as a kMenu, but as a kMenuBar for most platforms and a
  // kNone on the Mac. See MenuScrollViewContainer::GetAccessibleNodeData.
  if (!GetMenuItem()->GetParentMenuItem()) {
    GetScrollViewContainer()->NotifyAccessibilityEventDeprecated(
        ax::mojom::Event::kMenuStart, true);
  }
  // Fire kMenuPopupStart for each menu/submenu that is shown.
  NotifyAccessibilityEventDeprecated(ax::mojom::Event::kMenuPopupStart, true);

  GetMenuItem()->UpdateAccessibleExpandedCollapsedState();

  // Announce if the menu/submenu is empty.
  if (GetRowCount() == 0) {
    GetViewAccessibility().AnnouncePolitely(
        l10n_util::GetStringUTF16(IDS_APP_MENU_AX_ANNOUNCE_EMPTY_SUBMENU));
  }
}

void SubmenuView::Reposition(const gfx::Rect& bounds,
                             const ui::OwnedWindowAnchor& anchor) {
  if (host_) {
    // Anchor must be updated first.
    host_->SetMenuHostOwnedWindowAnchor(anchor);
    host_->SetMenuHostBounds(bounds);
  }
}

void SubmenuView::Close() {
  if (host_) {
    host_->DestroyMenuHost();
    host_ = nullptr;
    GetMenuItem()->UpdateAccessibleExpandedCollapsedState();
  }
}

void SubmenuView::Hide() {
  if (host_) {
    /// -- Fire accessibility events ----
    // Both of these must be fired before HideMenuHost().
    // Only fire kMenuEnd when a top level menu closes, not for each submenu.
    // This is sent before kMenuPopupEnd to allow ViewAXPlatformNodeDelegate to
    // remove its focus override before AXPlatformNodeAuraLinux needs to access
    // the previously-focused node while handling kMenuPopupEnd.
    if (!GetMenuItem()->GetParentMenuItem()) {
      GetScrollViewContainer()->NotifyAccessibilityEventDeprecated(
          ax::mojom::Event::kMenuEnd, true);
      GetViewAccessibility().EndPopupFocusOverride();
    }
    // Fire these kMenuPopupEnd for each menu/submenu that closes/hides.
    if (host_->IsVisible()) {
      NotifyAccessibilityEventDeprecated(ax::mojom::Event::kMenuPopupEnd, true);
    }

    host_->HideMenuHost();
    GetMenuItem()->UpdateAccessibleExpandedCollapsedState();
  }

  if (scroll_animator_->is_scrolling()) {
    scroll_animator_->Stop();
  }
}

void SubmenuView::ReleaseCapture() {
  if (host_) {
    host_->ReleaseMenuHostCapture();
  }
}

bool SubmenuView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) {
  return views::FocusManager::IsTabTraversalKeyEvent(e);
}

const MenuItemView* SubmenuView::GetMenuItem() const {
  return parent_menu_item_;
}

void SubmenuView::SetDropMenuItem(MenuItemView* item,
                                  MenuDelegate::DropPosition position) {
  if (drop_item_ == item && drop_position_ == position) {
    return;
  }
  SchedulePaintForDropIndicator(drop_item_, drop_position_);
  MenuItemView* old_drop_item = std::exchange(drop_item_, item);
  drop_position_ = position;
  if (!old_drop_item || !item) {
    // Whether the selection is actually drawn
    // (`MenuItemView:last_paint_as_selected_`) depends upon whether there is a
    // drop item. Find the selected item and have it updates its paint as
    // selected state.
    for (View* child : children()) {
      if (auto* child_menu_item = AsViewClass<MenuItemView>(child);
          child_menu_item && child_menu_item->GetVisible() &&
          child_menu_item->IsSelected()) {
        child_menu_item->OnDropOrSelectionStatusMayHaveChanged();
        // Only one menu item is selected, so no need to continue iterating once
        // the selected item is found.
        break;
      }
    }
  } else {
    if (old_drop_item && old_drop_item != drop_item_) {
      old_drop_item->OnDropOrSelectionStatusMayHaveChanged();
    }
    if (drop_item_) {
      drop_item_->OnDropOrSelectionStatusMayHaveChanged();
    }
  }
  SchedulePaintForDropIndicator(drop_item_, drop_position_);
}

bool SubmenuView::GetShowSelection(const MenuItemView* item) const {
  return !drop_item_ || (drop_item_ == item &&
                         drop_position_ == MenuDelegate::DropPosition::kOn);
}

MenuScrollViewContainer* SubmenuView::GetScrollViewContainer() {
  // Perform null checks for scroll_view_container and MenuController since
  // MenuScrollViewContainer constructor is invoked later, which uses
  // menucontroller to determine the value of the use_ash_system_ui_layout_
  // variable.
  if (!scroll_view_container_ && !parent_menu_item_->GetMenuController()) {
    return nullptr;
  }

  if (!scroll_view_container_) {
    scroll_view_container_ = std::make_unique<MenuScrollViewContainer>(this);
    // Otherwise MenuHost would delete us.
    scroll_view_container_->set_owned_by_client(OwnedByClientPassKey());
    scroll_view_container_->SetBorderColorId(border_color_id_);
  }
  return scroll_view_container_.get();
}

MenuItemView* SubmenuView::GetLastItem() {
  const auto menu_items = GetMenuItems();
  return menu_items.empty() ? nullptr : menu_items.back();
}

void SubmenuView::MenuHostDestroyed() {
  host_ = nullptr;
  MenuController* controller = parent_menu_item_->GetMenuController();
  if (controller) {
    controller->Cancel(MenuController::ExitType::kDestroyed);
  }
}

void SubmenuView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
  SchedulePaint();
}

void SubmenuView::SchedulePaintForDropIndicator(
    MenuItemView* item,
    MenuDelegate::DropPosition position) {
  if (item == nullptr) {
    return;
  }

  if (position == MenuDelegate::DropPosition::kOn) {
    item->SchedulePaint();
  } else if (position != MenuDelegate::DropPosition::kNone) {
    SchedulePaintInRect(CalculateDropIndicatorBounds(item, position));
  }
}

gfx::Rect SubmenuView::CalculateDropIndicatorBounds(
    MenuItemView* item,
    MenuDelegate::DropPosition position) {
  DCHECK(position != MenuDelegate::DropPosition::kNone);
  gfx::Rect item_bounds = item->bounds();
  switch (position) {
    case MenuDelegate::DropPosition::kBefore:
      item_bounds.Offset(0, -kDropIndicatorHeight / 2);
      item_bounds.set_height(kDropIndicatorHeight);
      return item_bounds;

    case MenuDelegate::DropPosition::kAfter:
      item_bounds.Offset(0, item_bounds.height() - kDropIndicatorHeight / 2);
      item_bounds.set_height(kDropIndicatorHeight);
      return item_bounds;

    default:
      // Don't render anything for on.
      return gfx::Rect();
  }
}

bool SubmenuView::OnScroll(float dx, float dy) {
  const gfx::Rect& vis_bounds = GetVisibleBounds();
  const gfx::Rect& full_bounds = bounds();
  int x = vis_bounds.x();
  float y_f = vis_bounds.y() - dy - roundoff_error_;
  int y = base::ClampRound(y_f);
  roundoff_error_ = y - y_f;

  // Ensure that we never try to scroll outside the actual child view.
  // Note: the old code here was effectively:
  //   std::clamp(y, 0, full_bounds.height() - vis_bounds.height() - 1)
  // but the -1 there prevented fully scrolling to the bottom here. As a
  // worked example, suppose that:
  //   full_bounds = { x = 0, y = 0, w = 100, h = 1000 }
  //   vis_bounds = { x = 0, y = 450, w = 100, h = 500 }
  // and dy = 50. It should be the case that the new vis_bounds are:
  //   new_vis_bounds = { x = 0, y = 500, w = 100, h = 500 }
  // because full_bounds.height() - vis_bounds.height() == 500. Intuitively,
  // this makes sense - the bottom 500 pixels of this view, starting with y =
  // 500, are shown.
  //
  // With the clamp set to full_bounds.height() - vis_bounds.height() - 1,
  // this code path instead would produce:
  //   new_vis_bounds = { x = 0, y = 499, w = 100, h = 500 }
  // so pixels y=499 through y=998 of this view are drawn, and pixel y=999 is
  // hidden - oops.
  y = std::clamp(y, 0, full_bounds.height() - vis_bounds.height());

  gfx::Rect new_vis_bounds(x, y, vis_bounds.width(), vis_bounds.height());
  if (new_vis_bounds != vis_bounds) {
    ScrollRectToVisible(new_vis_bounds);
    return true;
  }
  return false;
}

void SubmenuView::SetBorderColorId(std::optional<ui::ColorId> color_id) {
  if (scroll_view_container_) {
    scroll_view_container_->SetBorderColorId(color_id);
  }

  border_color_id_ = color_id;
}

BEGIN_METADATA(SubmenuView)
END_METADATA

}  // namespace views