code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// 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/button/radio_button.h"
#include "base/auto_reset.h"
#include "base/check.h"
#include "base/ranges/algorithm.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/resources/grit/views_resources.h"
#include "ui/views/vector_icons.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
constexpr int kFocusRingRadius = 16;
} // namespace
RadioButton::RadioButton(const std::u16string& label, int group_id)
: Checkbox(label) {
SetGroup(group_id);
views::FocusRing::Get(this)->SetOutsetFocusRingDisabled(true);
}
RadioButton::~RadioButton() = default;
void RadioButton::GetAccessibleNodeData(ui::AXNodeData* node_data) {
Checkbox::GetAccessibleNodeData(node_data);
node_data->role = ax::mojom::Role::kRadioButton;
}
View* RadioButton::GetSelectedViewForGroup(int group) {
Views views;
GetViewsInGroupFromParent(group, &views);
const auto i = base::ranges::find_if(views, [](const auto* view) {
// Why don't we check the runtime type like is done in SetChecked()?
return static_cast<const RadioButton*>(view)->GetChecked();
});
return (i == views.cend()) ? nullptr : *i;
}
bool RadioButton::HandleAccessibleAction(const ui::AXActionData& action_data) {
if (action_data.action == ax::mojom::Action::kFocus) {
if (IsAccessibilityFocusable()) {
base::AutoReset<bool> reset(&select_on_focus_, false);
RequestFocus();
return true;
}
}
return Checkbox::HandleAccessibleAction(action_data);
}
bool RadioButton::IsGroupFocusTraversable() const {
// When focusing a radio button with tab/shift+tab, only the selected button
// from the group should be focused.
return false;
}
void RadioButton::OnFocus() {
Checkbox::OnFocus();
if (select_on_focus_)
SetChecked(true);
}
void RadioButton::OnThemeChanged() {
Checkbox::OnThemeChanged();
SchedulePaint();
}
void RadioButton::RequestFocusFromEvent() {
Checkbox::RequestFocusFromEvent();
// Take focus only if another radio button in the group has focus.
Views views;
GetViewsInGroupFromParent(GetGroup(), &views);
if (base::ranges::any_of(views, [](View* v) { return v->HasFocus(); }))
RequestFocus();
}
void RadioButton::NotifyClick(const ui::Event& event) {
// Set the checked state to true only if we are unchecked, since we can't
// be toggled on and off like a checkbox.
if (!GetChecked())
SetChecked(true);
LabelButton::NotifyClick(event);
}
ui::NativeTheme::Part RadioButton::GetThemePart() const {
return ui::NativeTheme::kRadio;
}
void RadioButton::SetChecked(bool checked) {
if (checked == RadioButton::GetChecked())
return;
if (checked) {
// We can't start from the root view because other parts of the UI might use
// radio buttons with the same group. This can happen when re-using the same
// component or even if views want to use the group for a different purpose.
Views other;
GetViewsInGroupFromParent(GetGroup(), &other);
for (auto* peer : other) {
if (peer != this) {
DCHECK(!strcmp(peer->GetClassName(), kViewClassName))
<< "radio-button-nt has same group as non radio-button-nt views.";
static_cast<RadioButton*>(peer)->SetChecked(false);
}
}
}
Checkbox::SetChecked(checked);
}
const gfx::VectorIcon& RadioButton::GetVectorIcon() const {
return GetChecked() ? kRadioButtonActiveIcon : kRadioButtonNormalIcon;
}
SkPath RadioButton::GetFocusRingPath() const {
SkPath path;
const gfx::Point center = image()->GetMirroredBounds().CenterPoint();
path.addCircle(center.x(), center.y(), kFocusRingRadius);
return path;
}
void RadioButton::GetViewsInGroupFromParent(int group, Views* views) {
if (parent())
parent()->GetViewsInGroup(group, views);
}
BEGIN_METADATA(RadioButton, Checkbox)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/radio_button.cc | C++ | unknown | 4,409 |
// 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.
#ifndef UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_
#define UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_
#include <string>
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/metadata/view_factory.h"
namespace views {
// A native themed class representing a radio button. This class does not use
// platform specific objects to replicate the native platforms looks and feel.
class VIEWS_EXPORT RadioButton : public Checkbox {
public:
METADATA_HEADER(RadioButton);
explicit RadioButton(const std::u16string& label = std::u16string(),
int group_id = 0);
RadioButton(const RadioButton&) = delete;
RadioButton& operator=(const RadioButton&) = delete;
~RadioButton() override;
// Overridden from View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
View* GetSelectedViewForGroup(int group) override;
bool HandleAccessibleAction(const ui::AXActionData& action_data) override;
bool IsGroupFocusTraversable() const override;
void OnFocus() override;
void OnThemeChanged() override;
// Overridden from Button:
void RequestFocusFromEvent() override;
void NotifyClick(const ui::Event& event) override;
// Overridden from LabelButton:
ui::NativeTheme::Part GetThemePart() const override;
// Overridden from Checkbox:
void SetChecked(bool checked) override;
const gfx::VectorIcon& GetVectorIcon() const override;
SkPath GetFocusRingPath() const override;
private:
void GetViewsInGroupFromParent(int group, Views* views);
bool select_on_focus_ = true;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, RadioButton, Checkbox)
VIEW_BUILDER_PROPERTY(bool, Checked)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, RadioButton)
#endif // UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/radio_button.h | C++ | unknown | 1,971 |
// Copyright 2017 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/button/radio_button.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/base_event_utils.h"
#include "ui/views/test/views_test_base.h"
namespace {
// Group ID of the test radio buttons.
constexpr int kGroup = 1;
} // namespace
namespace views {
class RadioButtonTest : public ViewsTestBase {
public:
RadioButtonTest() = default;
RadioButtonTest(const RadioButtonTest&) = delete;
RadioButtonTest& operator=(const RadioButtonTest&) = delete;
void SetUp() override {
ViewsTestBase::SetUp();
// Create a Widget so the radio buttons can find their group siblings.
widget_ = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_->Init(std::move(params));
widget_->Show();
button_container_ = widget_->SetContentsView(std::make_unique<View>());
}
void TearDown() override {
button_container_ = nullptr;
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
View& button_container() { return *button_container_; }
private:
raw_ptr<View> button_container_ = nullptr;
std::unique_ptr<Widget> widget_;
};
TEST_F(RadioButtonTest, Basics) {
RadioButton* button1 = new RadioButton(u"Blah", kGroup);
button_container().AddChildView(button1);
RadioButton* button2 = new RadioButton(u"Blah", kGroup);
button_container().AddChildView(button2);
button1->SetChecked(true);
EXPECT_TRUE(button1->GetChecked());
EXPECT_FALSE(button2->GetChecked());
button2->SetChecked(true);
EXPECT_FALSE(button1->GetChecked());
EXPECT_TRUE(button2->GetChecked());
}
TEST_F(RadioButtonTest, Focus) {
RadioButton* button1 = new RadioButton(u"Blah", kGroup);
button_container().AddChildView(button1);
RadioButton* button2 = new RadioButton(u"Blah", kGroup);
button_container().AddChildView(button2);
// Tabbing through only focuses the checked button.
button1->SetChecked(true);
auto* focus_manager = button_container().GetFocusManager();
ui::KeyEvent pressed_tab(ui::ET_KEY_PRESSED, ui::VKEY_TAB, ui::EF_NONE);
focus_manager->OnKeyEvent(pressed_tab);
EXPECT_EQ(button1, focus_manager->GetFocusedView());
focus_manager->OnKeyEvent(pressed_tab);
EXPECT_EQ(button1, focus_manager->GetFocusedView());
// The checked button can be moved using arrow keys.
focus_manager->OnKeyEvent(
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE));
EXPECT_EQ(button2, focus_manager->GetFocusedView());
EXPECT_FALSE(button1->GetChecked());
EXPECT_TRUE(button2->GetChecked());
focus_manager->OnKeyEvent(
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE));
EXPECT_EQ(button1, focus_manager->GetFocusedView());
EXPECT_TRUE(button1->GetChecked());
EXPECT_FALSE(button2->GetChecked());
}
TEST_F(RadioButtonTest, FocusOnClick) {
RadioButton* button1 = new RadioButton(std::u16string(), kGroup);
button1->SetSize(gfx::Size(10, 10));
button_container().AddChildView(button1);
button1->SetChecked(true);
RadioButton* button2 = new RadioButton(std::u16string(), kGroup);
button2->SetSize(gfx::Size(10, 10));
button_container().AddChildView(button2);
const gfx::Point point(1, 1);
const ui::MouseEvent event(ui::ET_MOUSE_PRESSED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
button2->OnMousePressed(event);
button2->OnMouseReleased(event);
EXPECT_TRUE(button2->GetChecked());
auto* focus_manager = button_container().GetFocusManager();
// No focus on click.
EXPECT_EQ(nullptr, focus_manager->GetFocusedView());
ui::KeyEvent pressed_tab(ui::ET_KEY_PRESSED, ui::VKEY_TAB, ui::EF_NONE);
focus_manager->OnKeyEvent(pressed_tab);
EXPECT_EQ(button2, focus_manager->GetFocusedView());
button1->OnMousePressed(event);
button1->OnMouseReleased(event);
// Button 1 gets focus on click because button 2 already had it.
EXPECT_TRUE(button1->GetChecked());
EXPECT_EQ(button1, focus_manager->GetFocusedView());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/radio_button_unittest.cc | C++ | unknown | 4,437 |
// Copyright 2016 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/button/toggle_button.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/callback_list.h"
#include "base/functional/bind.h"
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkDrawLooper.h"
#include "third_party/skia/include/core/SkRect.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/shadow_value.h"
#include "ui/gfx/skia_paint_util.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/painter.h"
namespace views {
namespace {
// Constants are measured in dip.
constexpr gfx::Size kTrackSize = gfx::Size(28, 12);
// Margins from edge of track to edge of view.
constexpr int kTrackVerticalMargin = 5;
constexpr int kTrackHorizontalMargin = 6;
// Inset from the rounded edge of the thumb to the rounded edge of the track.
constexpr int kThumbInset = 2;
// ChromeRefresh2023 specific values.
constexpr gfx::Size kRefreshTrackSize = gfx::Size(26, 16);
constexpr int kRefreshThumbInset = -4;
constexpr int kRefreshThumbInsetSelected = -2;
constexpr int kRefreshThumbPressedOutset = 1;
constexpr int kRefreshHoverDiameter = 20;
const gfx::Size GetTrackSize() {
return features::IsChromeRefresh2023() ? kRefreshTrackSize : kTrackSize;
}
int GetThumbInset(bool is_on) {
if (features::IsChromeRefresh2023()) {
return is_on ? kRefreshThumbInsetSelected : kRefreshThumbInset;
}
return kThumbInset;
}
absl::optional<SkColor> GetSkColorFromVariant(
const absl::variant<ui::ColorId, SkColor>& color_variant) {
return absl::holds_alternative<SkColor>(color_variant)
? absl::make_optional(absl::get<SkColor>(color_variant))
: absl::nullopt;
}
SkColor ConvertVariantToSkColor(
const absl::variant<ui::ColorId, SkColor> color_variant,
const ui::ColorProvider* color_provider) {
return absl::holds_alternative<SkColor>(color_variant)
? absl::get<SkColor>(color_variant)
: color_provider->GetColor(absl::get<ui::ColorId>(color_variant));
}
} // namespace
class ToggleButton::FocusRingHighlightPathGenerator
: public views::HighlightPathGenerator {
public:
SkPath GetHighlightPath(const views::View* view) override {
return static_cast<const ToggleButton*>(view)->GetFocusRingPath();
}
};
// Class representing the thumb (the circle that slides horizontally).
class ToggleButton::ThumbView : public View {
public:
METADATA_HEADER(ThumbView);
explicit ThumbView(bool has_shadow) : has_shadow_(has_shadow) {
// Make the thumb behave as part of the parent for event handling.
SetCanProcessEventsWithinSubtree(false);
}
ThumbView(const ThumbView&) = delete;
ThumbView& operator=(const ThumbView&) = delete;
~ThumbView() override = default;
void Update(const gfx::Rect& bounds,
float color_ratio,
float hover_ratio,
bool is_on,
bool is_hovered) {
SetBoundsRect(bounds);
color_ratio_ = color_ratio;
hover_ratio_ = hover_ratio;
is_on_ = is_on;
is_hovered_ = is_hovered;
SchedulePaint();
}
// Returns the extra space needed to draw the shadows around the thumb. Since
// the extra space is around the thumb, the insets will be negative.
gfx::Insets GetShadowOutsets() {
return has_shadow_ ? gfx::Insets(-kShadowBlur) +
gfx::Vector2d(kShadowOffsetX, kShadowOffsetY)
: gfx::Insets();
}
void SetThumbColor(bool is_on, SkColor thumb_color) {
(is_on ? thumb_on_color_ : thumb_off_color_) = thumb_color;
}
absl::optional<SkColor> GetThumbColor(bool is_on) const {
return GetSkColorFromVariant(is_on ? thumb_on_color_ : thumb_off_color_);
}
private:
static constexpr int kShadowOffsetX = 0;
static constexpr int kShadowOffsetY = 1;
static constexpr int kShadowBlur = 2;
// views::View:
void OnPaint(gfx::Canvas* canvas) override {
const float dsf = canvas->UndoDeviceScaleFactor();
const ui::ColorProvider* color_provider = GetColorProvider();
cc::PaintFlags thumb_flags;
if (has_shadow_) {
std::vector<gfx::ShadowValue> shadows;
gfx::ShadowValue shadow(
gfx::Vector2d(kShadowOffsetX, kShadowOffsetY), 2 * kShadowBlur,
color_provider->GetColor(ui::kColorToggleButtonShadow));
shadows.push_back(shadow.Scale(dsf));
thumb_flags.setLooper(gfx::CreateShadowDrawLooper(shadows));
}
thumb_flags.setAntiAlias(true);
const SkColor thumb_on_color =
ConvertVariantToSkColor(thumb_on_color_, color_provider);
const SkColor thumb_off_color =
ConvertVariantToSkColor(thumb_off_color_, color_provider);
SkColor thumb_color =
color_utils::AlphaBlend(thumb_on_color, thumb_off_color, color_ratio_);
if (features::IsChromeRefresh2023() && is_hovered_ && is_on_) {
// For Chrome Refresh this will blend and additional color into the "on"
// state thumb color while the view is hovered. This will also take into
// account both the off->on color animating along with the hover
// animation. Those animations are running independently.
thumb_color = color_utils::AlphaBlend(
color_provider->GetColor(ui::kColorToggleButtonThumbOnHover),
thumb_color, hover_ratio_);
}
thumb_flags.setColor(thumb_color);
// We want the circle to have an integer pixel diameter and to be aligned
// with pixel boundaries, so we scale dip bounds to pixel bounds and round.
gfx::RectF thumb_bounds(GetLocalBounds());
thumb_bounds.Inset(-gfx::InsetsF(GetShadowOutsets()));
thumb_bounds.Inset(0.5f);
thumb_bounds.Scale(dsf);
thumb_bounds = gfx::RectF(gfx::ToEnclosingRect(thumb_bounds));
canvas->DrawCircle(thumb_bounds.CenterPoint(), thumb_bounds.height() / 2.f,
thumb_flags);
}
void OnEnabledStateChanged() {
// If using default color ID, update it according to the enabled state.
if (absl::holds_alternative<ui::ColorId>(thumb_on_color_)) {
thumb_on_color_ = GetEnabled() ? ui::kColorToggleButtonThumbOn
: ui::kColorToggleButtonThumbOnDisabled;
}
if (absl::holds_alternative<ui::ColorId>(thumb_off_color_)) {
thumb_off_color_ = GetEnabled() ? ui::kColorToggleButtonThumbOff
: ui::kColorToggleButtonThumbOffDisabled;
}
}
// Indicate if the thumb has shadow.
const bool has_shadow_;
// Colors used for the thumb.
absl::variant<ui::ColorId, SkColor> thumb_on_color_ =
ui::kColorToggleButtonThumbOn;
absl::variant<ui::ColorId, SkColor> thumb_off_color_ =
ui::kColorToggleButtonThumbOff;
// Thumb paints differently when on under ChromeRefresh2023.
bool is_on_ = false;
bool is_hovered_ = false;
// Color ratio between 0 and 1 that controls the thumb color.
float color_ratio_ = 0.0f;
// Color ratio between 0 and 1 that controls the thumb hover color.
float hover_ratio_ = 0.0f;
// Callback when the enabled state changes.
base::CallbackListSubscription enabled_state_changed_subscription_{
AddEnabledChangedCallback(
base::BindRepeating(&ThumbView::OnEnabledStateChanged,
base::Unretained(this)))};
};
ToggleButton::ToggleButton(PressedCallback callback)
: ToggleButton(callback,
/*has_thumb_shadow=*/!features::IsChromeRefresh2023()) {}
ToggleButton::ToggleButton(PressedCallback callback, bool has_thumb_shadow)
: Button(std::move(callback)) {
slide_animation_.SetSlideDuration(base::Milliseconds(80));
slide_animation_.SetTweenType(gfx::Tween::LINEAR);
hover_animation_.SetSlideDuration(base::Milliseconds(250));
hover_animation_.SetTweenType(gfx::Tween::LINEAR);
thumb_view_ = AddChildView(std::make_unique<ThumbView>(has_thumb_shadow));
InkDrop::Get(this)->SetMode(InkDropHost::InkDropMode::ON);
InkDrop::Get(this)->SetLayerRegion(LayerRegion::kAbove);
// Do not set a clip, allow the ink drop to burst out.
// TODO(pbos): Consider an explicit InkDrop API to not use a clip rect / mask.
views::InstallEmptyHighlightPathGenerator(this);
// InkDrop event triggering is handled in NotifyClick().
SetHasInkDropActionOnClick(false);
InkDrop::UseInkDropForSquareRipple(
InkDrop::Get(this),
/*highlight_on_hover=*/features::IsChromeRefresh2023(),
/*highlight_on_focus=*/false,
/*show_highlight_on_ripple=*/features::IsChromeRefresh2023());
InkDrop::Get(this)->SetCreateRippleCallback(base::BindRepeating(
[](ToggleButton* host,
gfx::Insets insets) -> std::unique_ptr<InkDropRipple> {
gfx::Rect rect = host->thumb_view_->GetLocalBounds();
rect.Inset(insets);
if (!features::IsChromeRefresh2023()) {
return InkDrop::Get(host)->CreateSquareRipple(rect.CenterPoint());
}
const SkColor pressed_color = host->GetPressedColor();
const float pressed_alpha = SkColorGetA(pressed_color);
std::unique_ptr<SquareInkDropRipple> ripple =
std::make_unique<SquareInkDropRipple>(
InkDrop::Get(host),
gfx::Size(kRefreshHoverDiameter, kRefreshHoverDiameter),
kRefreshHoverDiameter / 2, rect.size(), rect.height() / 2,
rect.CenterPoint(), SkColorSetA(pressed_color, SK_AlphaOPAQUE),
pressed_alpha / SK_AlphaOPAQUE);
ripple->set_activated_shape(
views::SquareInkDropRipple::ActivatedShape::kCircle);
return ripple;
},
this, -thumb_view_->GetShadowOutsets()));
InkDrop::Get(this)->SetBaseColorCallback(base::BindRepeating(
[](ToggleButton* host) {
return host->GetTrackColor(host->GetIsOn() || host->HasFocus());
},
this));
if (features::IsChromeRefresh2023()) {
InkDrop::Get(this)->SetCreateHighlightCallback(base::BindRepeating(
[](ToggleButton* host) {
const gfx::Rect thumb_bounds = host->thumb_view_->GetLocalBounds();
const gfx::Size thumb_size(kRefreshHoverDiameter,
kRefreshHoverDiameter);
const SkColor hover_color = host->GetHoverColor();
const float hover_alpha = SkColorGetA(hover_color);
auto ink_drop_highlight = std::make_unique<InkDropHighlight>(
thumb_size, thumb_size.height() / 2,
gfx::PointF(thumb_bounds.CenterPoint()),
SkColorSetA(hover_color, SK_AlphaOPAQUE));
ink_drop_highlight->set_visible_opacity(hover_alpha / SK_AlphaOPAQUE);
return ink_drop_highlight;
},
this));
}
// Even though ToggleButton doesn't paint anything, declare us as flipped in
// RTL mode so that FocusRing correctly flips as well.
SetFlipCanvasOnPaintForRTLUI(true);
SetInstallFocusRingOnFocus(true);
FocusRing::Get(this)->SetPathGenerator(
std::make_unique<FocusRingHighlightPathGenerator>());
}
ToggleButton::~ToggleButton() {
// TODO(pbos): Revisit explicit removal of InkDrop for classes that override
// Add/RemoveLayerFromRegions(). This is done so that the InkDrop doesn't
// access the non-override versions in ~View.
views::InkDrop::Remove(this);
}
void ToggleButton::AnimateIsOn(bool is_on) {
if (GetIsOn() == is_on) {
return;
}
if (is_on)
slide_animation_.Show();
else
slide_animation_.Hide();
OnPropertyChanged(&slide_animation_, kPropertyEffectsNone);
}
void ToggleButton::SetIsOn(bool is_on) {
if ((GetIsOn() == is_on) && !slide_animation_.is_animating()) {
return;
}
slide_animation_.Reset(is_on ? 1.0 : 0.0);
UpdateThumb();
OnPropertyChanged(&slide_animation_, kPropertyEffectsPaint);
}
bool ToggleButton::GetIsOn() const {
return slide_animation_.IsShowing();
}
void ToggleButton::SetThumbOnColor(SkColor thumb_on_color) {
thumb_view_->SetThumbColor(true /* is_on */, thumb_on_color);
}
absl::optional<SkColor> ToggleButton::GetThumbOnColor() const {
return thumb_view_->GetThumbColor(true);
}
void ToggleButton::SetThumbOffColor(SkColor thumb_off_color) {
thumb_view_->SetThumbColor(false /* is_on */, thumb_off_color);
}
absl::optional<SkColor> ToggleButton::GetThumbOffColor() const {
return thumb_view_->GetThumbColor(false);
}
void ToggleButton::SetTrackOnColor(SkColor track_on_color) {
track_on_color_ = track_on_color;
}
absl::optional<SkColor> ToggleButton::GetTrackOnColor() const {
return GetSkColorFromVariant(track_on_color_);
}
void ToggleButton::SetTrackOffColor(SkColor track_off_color) {
track_off_color_ = track_off_color;
}
absl::optional<SkColor> ToggleButton::GetTrackOffColor() const {
return GetSkColorFromVariant(track_off_color_);
}
void ToggleButton::SetAcceptsEvents(bool accepts_events) {
if (GetAcceptsEvents() == accepts_events) {
return;
}
accepts_events_ = accepts_events;
OnPropertyChanged(&accepts_events_, kPropertyEffectsNone);
}
bool ToggleButton::GetAcceptsEvents() const {
return accepts_events_;
}
void ToggleButton::AddLayerToRegion(ui::Layer* layer,
views::LayerRegion region) {
// Ink-drop layers should go above/below the ThumbView.
thumb_view_->AddLayerToRegion(layer, region);
}
void ToggleButton::RemoveLayerFromRegions(ui::Layer* layer) {
thumb_view_->RemoveLayerFromRegions(layer);
}
gfx::Size ToggleButton::CalculatePreferredSize() const {
gfx::Rect rect(GetTrackSize());
rect.Inset(gfx::Insets::VH(-kTrackVerticalMargin, -kTrackHorizontalMargin));
rect.Inset(-GetInsets());
return rect.size();
}
gfx::Rect ToggleButton::GetTrackBounds() const {
gfx::Rect track_bounds(GetContentsBounds());
track_bounds.ClampToCenteredSize(GetTrackSize());
return track_bounds;
}
gfx::Rect ToggleButton::GetThumbBounds() const {
gfx::Rect thumb_bounds(GetTrackBounds());
thumb_bounds.Inset(gfx::Insets(-GetThumbInset(GetIsOn())));
thumb_bounds.set_x(thumb_bounds.x() +
slide_animation_.GetCurrentValue() *
(thumb_bounds.width() - thumb_bounds.height()));
// The thumb is a circle, so the width should match the height.
thumb_bounds.set_width(thumb_bounds.height());
thumb_bounds.Inset(thumb_view_->GetShadowOutsets());
if (GetState() == STATE_PRESSED && features::IsChromeRefresh2023()) {
thumb_bounds.Outset(kRefreshThumbPressedOutset);
}
return thumb_bounds;
}
double ToggleButton::GetAnimationProgress() const {
return slide_animation_.GetCurrentValue();
}
void ToggleButton::UpdateThumb() {
thumb_view_->Update(GetThumbBounds(),
static_cast<float>(slide_animation_.GetCurrentValue()),
static_cast<float>(hover_animation_.GetCurrentValue()),
GetIsOn(), IsMouseHovered());
if (features::IsChromeRefresh2023() && IsMouseHovered()) {
InkDrop::Get(this)->GetInkDrop()->SetHovered(
!slide_animation_.is_animating());
}
if (FocusRing::Get(this)) {
// Updating the thumb changes the result of GetFocusRingPath(), make sure
// the focus ring gets updated to match this new state.
FocusRing::Get(this)->InvalidateLayout();
FocusRing::Get(this)->SchedulePaint();
}
}
SkColor ToggleButton::GetTrackColor(bool is_on) const {
return ConvertVariantToSkColor(is_on ? track_on_color_ : track_off_color_,
GetColorProvider());
}
SkColor ToggleButton::GetHoverColor() const {
return GetColorProvider()->GetColor(ui::kColorToggleButtonHover);
}
SkColor ToggleButton::GetPressedColor() const {
return GetColorProvider()->GetColor(ui::kColorToggleButtonPressed);
}
bool ToggleButton::CanAcceptEvent(const ui::Event& event) {
return GetAcceptsEvents() && Button::CanAcceptEvent(event);
}
void ToggleButton::OnBoundsChanged(const gfx::Rect& previous_bounds) {
UpdateThumb();
}
void ToggleButton::OnThemeChanged() {
Button::OnThemeChanged();
SchedulePaint();
}
void ToggleButton::NotifyClick(const ui::Event& event) {
AnimateIsOn(!GetIsOn());
// Only trigger the action when we don't have focus. This lets the InkDrop
// remain and match the focus ring.
// TODO(pbos): Investigate triggering the ripple but returning back to the
// focused state correctly. This is set up to highlight on focus, but the
// highlight does not come back after the ripple is triggered. Then remove
// this and add back SetHasInkDropActionOnClick(true) in the constructor.
if (!HasFocus() || features::IsChromeRefresh2023()) {
InkDrop::Get(this)->AnimateToState(InkDropState::ACTION_TRIGGERED,
ui::LocatedEvent::FromIfValid(&event));
}
Button::NotifyClick(event);
}
void ToggleButton::StateChanged(ButtonState old_state) {
Button::StateChanged(old_state);
// Update default track color ID and propagate the enabled state to the thumb.
const bool enabled = GetState() != ButtonState::STATE_DISABLED;
if (absl::holds_alternative<ui::ColorId>(track_on_color_)) {
track_on_color_ = enabled ? ui::kColorToggleButtonTrackOn
: ui::kColorToggleButtonTrackOnDisabled;
}
if (absl::holds_alternative<ui::ColorId>(track_off_color_)) {
track_off_color_ = enabled ? ui::kColorToggleButtonTrackOff
: ui::kColorToggleButtonTrackOffDisabled;
}
thumb_view_->SetEnabled(enabled);
// Update thumb bounds.
if (features::IsChromeRefresh2023()) {
if (GetState() == STATE_PRESSED || old_state == STATE_PRESSED) {
UpdateThumb();
} else if (GetState() == STATE_HOVERED || old_state == STATE_HOVERED) {
if (old_state == STATE_HOVERED) {
hover_animation_.Hide();
} else {
hover_animation_.Show();
}
UpdateThumb();
}
}
}
SkPath ToggleButton::GetFocusRingPath() const {
SkPath path;
if (features::IsChromeRefresh2023()) {
gfx::RectF bounds(GetLocalBounds());
constexpr float kFocusRingInset = 3.f;
bounds.Inset(kFocusRingInset);
const SkRect sk_rect = gfx::RectFToSkRect(bounds);
const float corner_radius = sk_rect.height() / 2;
path.addRoundRect(sk_rect, corner_radius, corner_radius);
} else {
const gfx::Point center = GetThumbBounds().CenterPoint();
constexpr int kFocusRingRadius = 16;
path.addCircle(center.x(), center.y(), kFocusRingRadius);
}
return path;
}
void ToggleButton::GetAccessibleNodeData(ui::AXNodeData* node_data) {
Button::GetAccessibleNodeData(node_data);
node_data->role = ax::mojom::Role::kSwitch;
node_data->SetCheckedState(GetIsOn() ? ax::mojom::CheckedState::kTrue
: ax::mojom::CheckedState::kFalse);
}
void ToggleButton::OnFocus() {
Button::OnFocus();
if (!features::IsChromeRefresh2023()) {
InkDrop::Get(this)->AnimateToState(views::InkDropState::ACTION_PENDING,
nullptr);
SchedulePaint();
}
}
void ToggleButton::OnBlur() {
Button::OnBlur();
if (!features::IsChromeRefresh2023()) {
// The ink drop may have already gone away if the user clicked after
// focusing.
if (InkDrop::Get(this)->GetInkDrop()->GetTargetInkDropState() ==
views::InkDropState::ACTION_PENDING) {
InkDrop::Get(this)->AnimateToState(views::InkDropState::ACTION_TRIGGERED,
nullptr);
}
SchedulePaint();
}
}
void ToggleButton::PaintButtonContents(gfx::Canvas* canvas) {
// Paint the toggle track. To look sharp even at fractional scale factors,
// round up to pixel boundaries.
canvas->Save();
float dsf = canvas->UndoDeviceScaleFactor();
gfx::RectF track_rect(GetTrackBounds());
track_rect.Scale(dsf);
track_rect = gfx::RectF(gfx::ToEnclosingRect(track_rect));
const SkScalar radius = track_rect.height() / 2;
cc::PaintFlags track_flags;
track_flags.setAntiAlias(true);
const float color_ratio =
static_cast<float>(slide_animation_.GetCurrentValue());
track_flags.setColor(color_utils::AlphaBlend(
GetTrackColor(true), GetTrackColor(false), color_ratio));
canvas->DrawRoundRect(track_rect, radius, track_flags);
if (!GetIsOn() && features::IsChromeRefresh2023()) {
track_flags.setColor(
GetColorProvider()->GetColor(ui::kColorToggleButtonShadow));
track_flags.setStrokeWidth(0.5f);
track_flags.setStyle(cc::PaintFlags::kStroke_Style);
canvas->DrawRoundRect(track_rect, radius, track_flags);
}
canvas->Restore();
}
void ToggleButton::AnimationEnded(const gfx::Animation* animation) {
if (features::IsChromeRefresh2023() && animation == &slide_animation_ &&
IsMouseHovered()) {
InkDrop::Get(this)->GetInkDrop()->SetHovered(true);
}
}
void ToggleButton::AnimationProgressed(const gfx::Animation* animation) {
if (animation == &slide_animation_ || animation == &hover_animation_) {
// TODO(varkha, estade): The thumb is using its own view. Investigate if
// repainting in every animation step to update colors could be avoided.
UpdateThumb();
SchedulePaint();
return;
}
Button::AnimationProgressed(animation);
}
BEGIN_METADATA(ToggleButton, ThumbView, View)
END_METADATA
BEGIN_METADATA(ToggleButton, Button)
ADD_PROPERTY_METADATA(bool, IsOn)
ADD_PROPERTY_METADATA(bool, AcceptsEvents)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/toggle_button.cc | C++ | unknown | 22,196 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_BUTTON_TOGGLE_BUTTON_H_
#define UI_VIEWS_CONTROLS_BUTTON_TOGGLE_BUTTON_H_
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/color/color_id.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/views/controls/button/button.h"
namespace ui {
class Event;
} // namespace ui
namespace views {
// This view presents a button that has two states: on and off. This is similar
// to a checkbox but has no text and looks more like a two-state horizontal
// slider.
class VIEWS_EXPORT ToggleButton : public Button {
public:
METADATA_HEADER(ToggleButton);
explicit ToggleButton(PressedCallback callback = PressedCallback());
ToggleButton(PressedCallback callback, bool has_thumb_shadow);
ToggleButton(const ToggleButton&) = delete;
ToggleButton& operator=(const ToggleButton&) = delete;
~ToggleButton() override;
// AnimateIsOn() animates the state change to |is_on|; SetIsOn() doesn't.
void AnimateIsOn(bool is_on);
void SetIsOn(bool is_on);
bool GetIsOn() const;
// Sets and gets custom thumb and track colors.
void SetThumbOnColor(SkColor thumb_on_color);
absl::optional<SkColor> GetThumbOnColor() const;
void SetThumbOffColor(SkColor thumb_off_color);
absl::optional<SkColor> GetThumbOffColor() const;
void SetTrackOnColor(SkColor track_on_color);
absl::optional<SkColor> GetTrackOnColor() const;
void SetTrackOffColor(SkColor track_off_color);
absl::optional<SkColor> GetTrackOffColor() const;
void SetAcceptsEvents(bool accepts_events);
bool GetAcceptsEvents() const;
// views::View:
void AddLayerToRegion(ui::Layer* layer, LayerRegion region) override;
void RemoveLayerFromRegions(ui::Layer* layer) override;
gfx::Size CalculatePreferredSize() const override;
protected:
// views::View:
void OnThemeChanged() override;
// views::Button:
void NotifyClick(const ui::Event& event) override;
void StateChanged(ButtonState old_state) override;
// Returns the path to draw the focus ring around for this ToggleButton.
virtual SkPath GetFocusRingPath() const;
// Calculates and returns the bounding box for the track.
virtual gfx::Rect GetTrackBounds() const;
// Calculates and returns the bounding box for the thumb (the circle).
virtual gfx::Rect GetThumbBounds() const;
// Gets current slide animation progress.
double GetAnimationProgress() const;
private:
friend class TestToggleButton;
class FocusRingHighlightPathGenerator;
class ThumbView;
// Updates position of the thumb.
void UpdateThumb();
SkColor GetTrackColor(bool is_on) const;
SkColor GetHoverColor() const;
SkColor GetPressedColor() const;
// views::View:
bool CanAcceptEvent(const ui::Event& event) override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnFocus() override;
void OnBlur() override;
// Button:
void PaintButtonContents(gfx::Canvas* canvas) override;
// gfx::AnimationDelegate:
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationProgressed(const gfx::Animation* animation) override;
gfx::SlideAnimation slide_animation_{this};
gfx::SlideAnimation hover_animation_{this};
raw_ptr<ThumbView> thumb_view_;
absl::variant<ui::ColorId, SkColor> track_on_color_ =
ui::kColorToggleButtonTrackOn;
absl::variant<ui::ColorId, SkColor> track_off_color_ =
ui::kColorToggleButtonTrackOff;
// When false, this button won't accept input. Different from View::SetEnabled
// in that the view retains focus when this is false but not when disabled.
bool accepts_events_ = true;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ToggleButton, Button)
VIEW_BUILDER_PROPERTY(bool, IsOn)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ToggleButton)
#endif // UI_VIEWS_CONTROLS_BUTTON_TOGGLE_BUTTON_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/toggle_button.h | C++ | unknown | 4,191 |
// Copyright 2016 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/button/toggle_button.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget_utils.h"
namespace views {
class TestToggleButton : public ToggleButton {
public:
explicit TestToggleButton(int* counter) : counter_(counter) {}
TestToggleButton(const TestToggleButton&) = delete;
TestToggleButton& operator=(const TestToggleButton&) = delete;
~TestToggleButton() override {
// TODO(pbos): Revisit explicit removal of InkDrop for classes that override
// Add/RemoveLayerFromRegions(). This is done so that the InkDrop doesn't
// access the non-override versions in ~View.
views::InkDrop::Remove(this);
}
void AddLayerToRegion(ui::Layer* layer, views::LayerRegion region) override {
++(*counter_);
ToggleButton::AddLayerToRegion(layer, region);
}
void RemoveLayerFromRegions(ui::Layer* layer) override {
--(*counter_);
ToggleButton::RemoveLayerFromRegions(layer);
}
using View::Focus;
private:
const raw_ptr<int> counter_;
};
class ToggleButtonTest : public ViewsTestBase {
public:
ToggleButtonTest() = default;
ToggleButtonTest(const ToggleButtonTest&) = delete;
ToggleButtonTest& operator=(const ToggleButtonTest&) = delete;
~ToggleButtonTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
// Create a widget so that the ToggleButton can query the hover state
// correctly.
widget_ = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 650, 650);
widget_->Init(std::move(params));
widget_->Show();
button_ =
widget_->SetContentsView(std::make_unique<TestToggleButton>(&counter_));
}
void TearDown() override {
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
int counter() const { return counter_; }
Widget* widget() { return widget_.get(); }
TestToggleButton* button() { return button_; }
private:
std::unique_ptr<Widget> widget_;
raw_ptr<TestToggleButton> button_ = nullptr;
int counter_ = 0;
};
// Starts ink drop animation on a ToggleButton and destroys the button.
// The test verifies that the ink drop layer is removed properly when the
// ToggleButton gets destroyed.
TEST_F(ToggleButtonTest, ToggleButtonDestroyed) {
EXPECT_EQ(0, counter());
gfx::Point center(10, 10);
button()->OnMousePressed(ui::MouseEvent(
ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON));
EXPECT_EQ(1, counter());
delete button();
EXPECT_EQ(0, counter());
}
// Make sure nothing bad happens when the widget is destroyed while the
// ToggleButton has focus (and is showing a ripple).
TEST_F(ToggleButtonTest, ShutdownWithFocus) {
button()->RequestFocus();
EXPECT_EQ(1, counter());
}
// Verify that ToggleButton::accepts_events_ works as expected.
TEST_F(ToggleButtonTest, AcceptEvents) {
EXPECT_FALSE(button()->GetIsOn());
ui::test::EventGenerator generator(GetRootWindow(widget()));
generator.MoveMouseTo(widget()->GetClientAreaBoundsInScreen().CenterPoint());
// Clicking toggles.
generator.ClickLeftButton();
EXPECT_TRUE(button()->GetIsOn());
generator.ClickLeftButton();
EXPECT_FALSE(button()->GetIsOn());
// Spacebar toggles.
button()->RequestFocus();
generator.PressKey(ui::VKEY_SPACE, ui::EF_NONE);
generator.ReleaseKey(ui::VKEY_SPACE, ui::EF_NONE);
EXPECT_TRUE(button()->GetIsOn());
generator.PressKey(ui::VKEY_SPACE, ui::EF_NONE);
generator.ReleaseKey(ui::VKEY_SPACE, ui::EF_NONE);
EXPECT_FALSE(button()->GetIsOn());
// Spacebar and clicking do nothing when not accepting events, but focus is
// not affected.
button()->SetAcceptsEvents(false);
EXPECT_TRUE(button()->HasFocus());
generator.PressKey(ui::VKEY_SPACE, ui::EF_NONE);
generator.ReleaseKey(ui::VKEY_SPACE, ui::EF_NONE);
EXPECT_FALSE(button()->GetIsOn());
generator.ClickLeftButton();
EXPECT_FALSE(button()->GetIsOn());
// Re-enable events and clicking and spacebar resume working.
button()->SetAcceptsEvents(true);
generator.PressKey(ui::VKEY_SPACE, ui::EF_NONE);
generator.ReleaseKey(ui::VKEY_SPACE, ui::EF_NONE);
EXPECT_TRUE(button()->GetIsOn());
generator.ClickLeftButton();
EXPECT_FALSE(button()->GetIsOn());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/button/toggle_button_unittest.cc | C++ | unknown | 4,909 |
// 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/combobox/combobox.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.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/menu_source_utils.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_types.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/gfx/text_utils.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/button_controller.h"
#include "ui/views/controls/combobox/combobox_menu_model.h"
#include "ui/views/controls/combobox/combobox_util.h"
#include "ui/views/controls/combobox/empty_combobox_model.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/focusable_border.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/prefix_selector.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/mouse_constants.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/style/typography.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
constexpr int kBorderThickness = 1;
float GetCornerRadius() {
return LayoutProvider::Get()->GetCornerRadiusMetric(
ShapeContextTokens::kComboboxRadius);
}
SkColor GetTextColorForEnableState(const Combobox& combobox, bool enabled) {
const int style = enabled ? style::STYLE_PRIMARY : style::STYLE_DISABLED;
return combobox.GetColorProvider()->GetColor(
style::GetColorId(style::CONTEXT_TEXTFIELD, style));
}
// The transparent button which holds a button state but is not rendered.
class TransparentButton : public Button {
public:
explicit TransparentButton(PressedCallback callback)
: Button(std::move(callback)) {
SetFocusBehavior(FocusBehavior::NEVER);
button_controller()->set_notify_action(
ButtonController::NotifyAction::kOnPress);
if (features::IsChromeRefresh2023()) {
views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(),
GetCornerRadius());
}
ConfigureComboboxButtonInkDrop(this);
}
TransparentButton(const TransparentButton&) = delete;
TransparentButton& operator&=(const TransparentButton&) = delete;
~TransparentButton() override = default;
bool OnMousePressed(const ui::MouseEvent& mouse_event) override {
#if !BUILDFLAG(IS_MAC)
// On Mac, comboboxes do not take focus on mouse click, but on other
// platforms they do.
parent()->RequestFocus();
#endif
return Button::OnMousePressed(mouse_event);
}
double GetAnimationValue() const {
return hover_animation().GetCurrentValue();
}
void UpdateInkDrop(bool show_on_press_and_hover) {
if (show_on_press_and_hover) {
// We must use UseInkDropForFloodFillRipple here because
// UseInkDropForSquareRipple hides the InkDrop when the ripple effect is
// active instead of layering underneath it causing flashing.
InkDrop::UseInkDropForFloodFillRipple(InkDrop::Get(this),
/*highlight_on_hover=*/true);
} else {
InkDrop::UseInkDropForSquareRipple(InkDrop::Get(this),
/*highlight_on_hover=*/false);
}
}
};
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Combobox, public:
Combobox::Combobox(int text_context, int text_style)
: Combobox(std::make_unique<internal::EmptyComboboxModel>()) {}
Combobox::Combobox(std::unique_ptr<ui::ComboboxModel> model,
int text_context,
int text_style)
: Combobox(model.get(), text_context, text_style) {
owned_model_ = std::move(model);
}
Combobox::Combobox(ui::ComboboxModel* model, int text_context, int text_style)
: text_context_(text_context), text_style_(text_style) {
SetModel(model);
#if BUILDFLAG(IS_MAC)
SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY);
#else
SetFocusBehavior(FocusBehavior::ALWAYS);
#endif
SetBackgroundColorId(features::IsChromeRefresh2023()
? ui::kColorComboboxBackground
: ui::kColorTextfieldBackground);
UpdateBorder();
FocusRing::Install(this);
views::FocusRing::Get(this)->SetOutsetFocusRingDisabled(true);
arrow_button_ =
AddChildView(std::make_unique<TransparentButton>(base::BindRepeating(
&Combobox::ArrowButtonPressed, base::Unretained(this))));
UpdateFont();
if (features::IsChromeRefresh2023()) {
// TODO(crbug.com/1400024): This setter should be removed and the behavior
// made default when ChromeRefresh2023 is finalized.
SetEventHighlighting(true);
enabled_changed_subscription_ =
AddEnabledChangedCallback(base::BindRepeating(
[](Combobox* combobox) {
combobox->SetBackgroundColorId(
combobox->GetEnabled()
? ui::kColorComboboxBackground
: ui::kColorComboboxBackgroundDisabled);
combobox->UpdateBorder();
},
base::Unretained(this)));
}
// A layer is applied to make sure that canvas bounds are snapped to pixel
// boundaries (for the sake of drawing the arrow).
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
if (features::IsChromeRefresh2023()) {
views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(),
GetCornerRadius());
}
// `ax::mojom::Role::kComboBox` is for UI elements with a dropdown and
// an editable text field, which `views::Combobox` does not have. Use
// `ax::mojom::Role::kPopUpButton` to match an HTML <select> element.
SetAccessibilityProperties(ax::mojom::Role::kPopUpButton);
}
Combobox::~Combobox() {
if (GetInputMethod() && selector_.get()) {
// Combobox should have been blurred before destroy.
DCHECK(selector_.get() != GetInputMethod()->GetTextInputClient());
}
}
const gfx::FontList& Combobox::GetFontList() const {
return font_list_;
}
void Combobox::SetSelectedIndex(absl::optional<size_t> index) {
if (selected_index_ == index)
return;
// TODO(pbos): Add (D)CHECKs to validate the selected index.
selected_index_ = index;
if (size_to_largest_label_) {
OnPropertyChanged(&selected_index_, kPropertyEffectsPaint);
} else {
content_size_ = GetContentSize();
OnPropertyChanged(&selected_index_, kPropertyEffectsPreferredSizeChanged);
}
}
void Combobox::UpdateFont() {
// If the model uses a custom font, set the font to be the same as the font
// at the selected index.
if (GetModel() != nullptr && selected_index_.has_value()) {
std::vector<std::string> font_list =
GetModel()->GetLabelFontNameAt(selected_index_.value());
absl::optional<int> font_size = GetModel()->GetLabelFontSize();
font_list_ =
!font_list.empty() && font_size.has_value()
? gfx::FontList(font_list, gfx::Font::FontStyle::NORMAL,
font_size.value(), gfx::Font::Weight::NORMAL)
: style::GetFont(text_context_, text_style_);
}
}
base::CallbackListSubscription Combobox::AddSelectedIndexChangedCallback(
views::PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&selected_index_, std::move(callback));
}
bool Combobox::SelectValue(const std::u16string& value) {
for (size_t i = 0; i < GetModel()->GetItemCount(); ++i) {
if (value == GetModel()->GetItemAt(i)) {
SetSelectedIndex(i);
return true;
}
}
return false;
}
void Combobox::SetOwnedModel(std::unique_ptr<ui::ComboboxModel> model) {
// The swap keeps the outgoing model alive for SetModel().
owned_model_.swap(model);
SetModel(owned_model_.get());
}
void Combobox::SetModel(ui::ComboboxModel* model) {
if (!model) {
SetOwnedModel(std::make_unique<internal::EmptyComboboxModel>());
return;
}
if (model_) {
DCHECK(observation_.IsObservingSource(model_.get()));
observation_.Reset();
}
model_ = model;
if (model_) {
model_ = model;
menu_model_ = std::make_unique<ComboboxMenuModel>(this, model_);
observation_.Observe(model_.get());
SetSelectedIndex(model_->GetDefaultIndex());
OnComboboxModelChanged(model_);
}
}
std::u16string Combobox::GetTooltipTextAndAccessibleName() const {
return arrow_button_->GetTooltipText();
}
void Combobox::SetTooltipTextAndAccessibleName(
const std::u16string& tooltip_text) {
arrow_button_->SetTooltipText(tooltip_text);
if (GetAccessibleName().empty()) {
SetAccessibleName(tooltip_text);
}
}
void Combobox::SetInvalid(bool invalid) {
if (invalid == invalid_)
return;
invalid_ = invalid;
if (views::FocusRing::Get(this))
views::FocusRing::Get(this)->SetInvalid(invalid);
UpdateBorder();
OnPropertyChanged(&selected_index_, kPropertyEffectsPaint);
}
void Combobox::SetBorderColorId(ui::ColorId color_id) {
border_color_id_ = color_id;
UpdateBorder();
}
void Combobox::SetBackgroundColorId(ui::ColorId color_id) {
SetBackground(CreateThemedRoundedRectBackground(color_id, GetCornerRadius()));
}
void Combobox::SetForegroundColorId(ui::ColorId color_id) {
foreground_color_id_ = color_id;
SchedulePaint();
}
void Combobox::SetEventHighlighting(bool should_highlight) {
should_highlight_ = should_highlight;
AsViewClass<TransparentButton>(arrow_button_)
->UpdateInkDrop(should_highlight);
}
void Combobox::SetSizeToLargestLabel(bool size_to_largest_label) {
if (size_to_largest_label_ == size_to_largest_label)
return;
size_to_largest_label_ = size_to_largest_label;
content_size_ = GetContentSize();
OnPropertyChanged(&selected_index_, kPropertyEffectsPreferredSizeChanged);
}
bool Combobox::IsMenuRunning() const {
return menu_runner_ && menu_runner_->IsRunning();
}
void Combobox::OnThemeChanged() {
View::OnThemeChanged();
OnContentSizeMaybeChanged();
}
size_t Combobox::GetRowCount() {
return GetModel()->GetItemCount();
}
absl::optional<size_t> Combobox::GetSelectedRow() {
return selected_index_;
}
void Combobox::SetSelectedRow(absl::optional<size_t> row) {
absl::optional<size_t> prev_index = selected_index_;
SetSelectedIndex(row);
if (selected_index_ != prev_index)
OnPerformAction();
}
std::u16string Combobox::GetTextForRow(size_t row) {
return GetModel()->IsItemSeparatorAt(row) ? std::u16string()
: GetModel()->GetItemAt(row);
}
////////////////////////////////////////////////////////////////////////////////
// Combobox, View overrides:
gfx::Size Combobox::CalculatePreferredSize() const {
// Limit how small a combobox can be.
constexpr int kMinComboboxWidth = 25;
// The preferred size will drive the local bounds which in turn is used to set
// the minimum width for the dropdown list.
int width = std::max(kMinComboboxWidth, content_size_.width()) +
LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING) *
2 +
GetInsets().width();
// If an arrow is being shown, add extra width to include that arrow.
if (should_show_arrow_) {
width += GetComboboxArrowContainerWidthAndMargins();
}
const int height = LayoutProvider::GetControlHeightForFont(
text_context_, text_style_, GetFontList());
return gfx::Size(width, height);
}
void Combobox::OnBoundsChanged(const gfx::Rect& previous_bounds) {
arrow_button_->SetBounds(0, 0, width(), height());
}
bool Combobox::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) {
// Escape should close the drop down list when it is active, not host UI.
if (e.key_code() != ui::VKEY_ESCAPE || e.IsShiftDown() || e.IsControlDown() ||
e.IsAltDown() || e.IsAltGrDown()) {
return false;
}
return !!menu_runner_;
}
bool Combobox::OnKeyPressed(const ui::KeyEvent& e) {
// TODO(oshima): handle IME.
DCHECK_EQ(e.type(), ui::ET_KEY_PRESSED);
DCHECK(selected_index_.has_value());
DCHECK_LT(selected_index_.value(), GetModel()->GetItemCount());
#if BUILDFLAG(IS_MAC)
if (e.key_code() != ui::VKEY_DOWN && e.key_code() != ui::VKEY_UP &&
e.key_code() != ui::VKEY_SPACE && e.key_code() != ui::VKEY_HOME &&
e.key_code() != ui::VKEY_END) {
return false;
}
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
#else
const auto index_at_or_after = [](ui::ComboboxModel* model,
size_t index) -> absl::optional<size_t> {
for (; index < model->GetItemCount(); ++index) {
if (!model->IsItemSeparatorAt(index) && model->IsItemEnabledAt(index))
return index;
}
return absl::nullopt;
};
const auto index_before = [](ui::ComboboxModel* model,
size_t index) -> absl::optional<size_t> {
for (; index > 0; --index) {
const auto prev = index - 1;
if (!model->IsItemSeparatorAt(prev) && model->IsItemEnabledAt(prev))
return prev;
}
return absl::nullopt;
};
absl::optional<size_t> new_index;
switch (e.key_code()) {
// Show the menu on F4 without modifiers.
case ui::VKEY_F4:
if (e.IsAltDown() || e.IsAltGrDown() || e.IsControlDown())
return false;
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
// Move to the next item if any, or show the menu on Alt+Down like Windows.
case ui::VKEY_DOWN:
if (e.IsAltDown()) {
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
}
new_index = index_at_or_after(GetModel(), selected_index_.value() + 1);
break;
// Move to the end of the list.
case ui::VKEY_END:
case ui::VKEY_NEXT: // Page down.
new_index = index_before(GetModel(), GetModel()->GetItemCount());
break;
// Move to the beginning of the list.
case ui::VKEY_HOME:
case ui::VKEY_PRIOR: // Page up.
new_index = index_at_or_after(GetModel(), 0);
break;
// Move to the previous item if any.
case ui::VKEY_UP:
new_index = index_before(GetModel(), selected_index_.value());
break;
case ui::VKEY_RETURN:
case ui::VKEY_SPACE:
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
default:
return false;
}
if (new_index.has_value()) {
SetSelectedIndex(new_index);
OnPerformAction();
}
return true;
#endif // BUILDFLAG(IS_MAC)
}
void Combobox::OnPaint(gfx::Canvas* canvas) {
OnPaintBackground(canvas);
PaintIconAndText(canvas);
OnPaintBorder(canvas);
}
void Combobox::OnFocus() {
if (GetInputMethod())
GetInputMethod()->SetFocusedTextInputClient(GetPrefixSelector());
View::OnFocus();
// Border renders differently when focused.
SchedulePaint();
}
void Combobox::OnBlur() {
if (GetInputMethod())
GetInputMethod()->DetachTextInputClient(GetPrefixSelector());
if (selector_)
selector_->OnViewBlur();
// Border renders differently when focused.
SchedulePaint();
}
void Combobox::GetAccessibleNodeData(ui::AXNodeData* node_data) {
View::GetAccessibleNodeData(node_data);
if (menu_runner_) {
node_data->AddState(ax::mojom::State::kExpanded);
} else {
node_data->AddState(ax::mojom::State::kCollapsed);
}
node_data->SetValue(model_->GetItemAt(selected_index_.value()));
if (GetEnabled()) {
node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kOpen);
}
node_data->AddIntAttribute(ax::mojom::IntAttribute::kPosInSet,
base::checked_cast<int>(selected_index_.value()));
node_data->AddIntAttribute(ax::mojom::IntAttribute::kSetSize,
base::checked_cast<int>(model_->GetItemCount()));
}
bool Combobox::HandleAccessibleAction(const ui::AXActionData& action_data) {
// The action handling in View would generate a mouse event and send it to
// |this|. However, mouse events for Combobox are handled by |arrow_button_|,
// which is hidden from the a11y tree (so can't expose actions). Rather than
// forwarding ax::mojom::Action::kDoDefault to View and then forwarding the
// mouse event it generates to |arrow_button_| to have it forward back to the
// callback on |this|, just handle the action explicitly here and bypass View.
if (GetEnabled() && action_data.action == ax::mojom::Action::kDoDefault) {
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
}
return View::HandleAccessibleAction(action_data);
}
void Combobox::OnComboboxModelChanged(ui::ComboboxModel* model) {
DCHECK_EQ(model_, model);
// If the selection is no longer valid (or the model is empty), restore the
// default index.
if (selected_index_ >= model_->GetItemCount() ||
model_->GetItemCount() == 0 ||
model_->IsItemSeparatorAt(selected_index_.value())) {
SetSelectedIndex(model_->GetDefaultIndex());
}
OnContentSizeMaybeChanged();
}
void Combobox::OnComboboxModelDestroying(ui::ComboboxModel* model) {
SetModel(nullptr);
}
const base::RepeatingClosure& Combobox::GetCallback() const {
return callback_;
}
const std::unique_ptr<ui::ComboboxModel>& Combobox::GetOwnedModel() const {
return owned_model_;
}
void Combobox::UpdateBorder() {
if (features::IsChromeRefresh2023()) {
if (!GetEnabled()) {
SetBorder(nullptr);
return;
}
SetBorder(CreateThemedRoundedRectBorder(
kBorderThickness, GetCornerRadius(),
invalid_
? ui::kColorAlertHighSeverity
: border_color_id_.value_or(ui::kColorComboboxContainerOutline)));
} else {
auto border = std::make_unique<FocusableBorder>();
border->SetColorId(invalid_ ? ui::kColorAlertHighSeverity
: border_color_id_.value_or(
ui::kColorFocusableBorderUnfocused));
SetBorder(std::move(border));
}
}
void Combobox::AdjustBoundsForRTLUI(gfx::Rect* rect) const {
rect->set_x(GetMirroredXForRect(*rect));
}
void Combobox::PaintIconAndText(gfx::Canvas* canvas) {
gfx::Insets insets = GetInsets();
insets += gfx::Insets::VH(0, LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING));
gfx::ScopedCanvas scoped_canvas(canvas);
canvas->ClipRect(GetContentsBounds());
int x = insets.left();
int y = insets.top();
int contents_height = height() - insets.height();
DCHECK(selected_index_.has_value());
DCHECK_LT(selected_index_.value(), GetModel()->GetItemCount());
// Draw the icon.
ui::ImageModel icon = GetModel()->GetIconAt(selected_index_.value());
if (!icon.IsEmpty()) {
gfx::ImageSkia icon_skia = icon.Rasterize(GetColorProvider());
int icon_y = y + (contents_height - icon_skia.height()) / 2;
gfx::Rect icon_bounds(x, icon_y, icon_skia.width(), icon_skia.height());
AdjustBoundsForRTLUI(&icon_bounds);
canvas->DrawImageInt(icon_skia, icon_bounds.x(), icon_bounds.y());
x += icon_skia.width();
}
// Draw the text.
SkColor text_color = foreground_color_id_
? GetColorProvider()->GetColor(*foreground_color_id_)
: GetTextColorForEnableState(*this, GetEnabled());
std::u16string text = GetModel()->GetItemAt(*selected_index_);
const gfx::FontList& font_list = GetFontList();
// If the text is not empty, add padding between it and the icon. If there
// was an empty icon, this padding is not necessary.
if (!text.empty() && !icon.IsEmpty()) {
x += LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_RELATED_LABEL_HORIZONTAL);
}
// The total width of the text is the minimum of either the string width,
// or the available space, accounting for optional arrow.
int text_width = gfx::GetStringWidth(text, font_list);
int available_width = width() - x - insets.right();
if (should_show_arrow_) {
available_width -= GetComboboxArrowContainerWidthAndMargins();
}
text_width = std::min(text_width, available_width);
gfx::Rect text_bounds(x, y, text_width, contents_height);
AdjustBoundsForRTLUI(&text_bounds);
canvas->DrawStringRect(text, font_list, text_color, text_bounds);
// Draw the arrow.
// TODO(crbug.com/1392549): Replace placeholder spacing and color values for
// ChromeRefresh2023.
if (should_show_arrow_) {
gfx::Rect arrow_bounds(width() - GetComboboxArrowContainerWidthAndMargins(),
0, GetComboboxArrowContainerWidth(), height());
arrow_bounds.ClampToCenteredSize(ComboboxArrowSize());
AdjustBoundsForRTLUI(&arrow_bounds);
PaintComboboxArrow(text_color, arrow_bounds, canvas);
}
}
void Combobox::ArrowButtonPressed(const ui::Event& event) {
if (!GetEnabled())
return;
// TODO(hajimehoshi): Fix the problem that the arrow button blinks when
// cliking this while the dropdown menu is opened.
if ((base::TimeTicks::Now() - closed_time_) > kMinimumTimeBetweenButtonClicks)
ShowDropDownMenu(ui::GetMenuSourceTypeForEvent(event));
}
void Combobox::ShowDropDownMenu(ui::MenuSourceType source_type) {
constexpr int kMenuBorderWidthTop = 1;
// Menu's requested position's width should be the same as local bounds so the
// border of the menu lines up with the border of the combobox. The y
// coordinate however should be shifted to the bottom with the border with not
// to overlap with the combobox border.
gfx::Rect lb = GetLocalBounds();
gfx::Point menu_position(lb.origin());
menu_position.set_y(menu_position.y() + kMenuBorderWidthTop);
View::ConvertPointToScreen(this, &menu_position);
gfx::Rect bounds(menu_position, lb.size());
// If check marks exist in the combobox, adjust with bounds width to account
// for them.
if (!size_to_largest_label_)
bounds.set_width(MaybeAdjustWidthForCheckmarks(bounds.width()));
Button::ButtonState original_state = arrow_button_->GetState();
arrow_button_->SetState(Button::STATE_PRESSED);
// Allow |menu_runner_| to be set by the testing API, but if this method is
// ever invoked recursively, ensure the old menu is closed.
if (!menu_runner_ || IsMenuRunning()) {
menu_runner_ = std::make_unique<MenuRunner>(
menu_model_.get(), MenuRunner::COMBOBOX,
base::BindRepeating(&Combobox::OnMenuClosed, base::Unretained(this),
original_state));
}
if (should_highlight_) {
InkDrop::Get(arrow_button_)
->AnimateToState(InkDropState::ACTIVATED, nullptr);
}
menu_runner_->RunMenuAt(GetWidget(), nullptr, bounds,
MenuAnchorPosition::kTopLeft, source_type);
NotifyAccessibilityEvent(ax::mojom::Event::kExpandedChanged, true);
}
void Combobox::OnMenuClosed(Button::ButtonState original_button_state) {
if (should_highlight_) {
InkDrop::Get(arrow_button_)
->AnimateToState(InkDropState::DEACTIVATED, nullptr);
InkDrop::Get(arrow_button_)->GetInkDrop()->SetHovered(IsMouseHovered());
}
menu_runner_.reset();
arrow_button_->SetState(original_button_state);
closed_time_ = base::TimeTicks::Now();
NotifyAccessibilityEvent(ax::mojom::Event::kExpandedChanged, true);
}
void Combobox::MenuSelectionAt(size_t index) {
if (!menu_selection_at_callback_ || !menu_selection_at_callback_.Run(index)) {
SetSelectedIndex(index);
OnPerformAction();
}
}
void Combobox::OnPerformAction() {
NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true);
SchedulePaint();
if (callback_)
callback_.Run();
// Note |this| may be deleted by |callback_|.
}
gfx::Size Combobox::GetContentSize() const {
const gfx::FontList& font_list = GetFontList();
int height = font_list.GetHeight();
int width = 0;
for (size_t i = 0; i < GetModel()->GetItemCount(); ++i) {
if (model_->IsItemSeparatorAt(i))
continue;
if (size_to_largest_label_ || i == selected_index_) {
int item_width = 0;
ui::ImageModel icon = GetModel()->GetIconAt(i);
std::u16string text = GetModel()->GetItemAt(i);
if (!icon.IsEmpty()) {
gfx::ImageSkia icon_skia;
if (GetWidget())
icon_skia = icon.Rasterize(GetColorProvider());
item_width += icon_skia.width();
height = std::max(height, icon_skia.height());
// If both the text and icon are not empty, include padding between.
// We do not include this padding if there is no icon present.
if (!text.empty()) {
item_width += LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_RELATED_LABEL_HORIZONTAL);
}
}
// If text is not empty, the content size needs to include the text width
if (!text.empty()) {
item_width += gfx::GetStringWidth(GetModel()->GetItemAt(i), font_list);
}
if (size_to_largest_label_)
item_width = MaybeAdjustWidthForCheckmarks(item_width);
width = std::max(width, item_width);
}
}
return gfx::Size(width, height);
}
int Combobox::MaybeAdjustWidthForCheckmarks(int original_width) const {
return MenuConfig::instance().check_selected_combobox_item
? original_width + kMenuCheckSize +
LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_RELATED_BUTTON_HORIZONTAL)
: original_width;
}
void Combobox::OnContentSizeMaybeChanged() {
content_size_ = GetContentSize();
PreferredSizeChanged();
}
PrefixSelector* Combobox::GetPrefixSelector() {
if (!selector_)
selector_ = std::make_unique<PrefixSelector>(this, this);
return selector_.get();
}
BEGIN_METADATA(Combobox, View)
ADD_PROPERTY_METADATA(base::RepeatingClosure, Callback)
ADD_PROPERTY_METADATA(std::unique_ptr<ui::ComboboxModel>, OwnedModel)
ADD_PROPERTY_METADATA(ui::ComboboxModel*, Model)
ADD_PROPERTY_METADATA(absl::optional<size_t>, SelectedIndex)
ADD_PROPERTY_METADATA(bool, Invalid)
ADD_PROPERTY_METADATA(bool, SizeToLargestLabel)
ADD_PROPERTY_METADATA(std::u16string, TooltipTextAndAccessibleName)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox.cc | C++ | unknown | 26,898 |
// 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.
#ifndef UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
#include <memory>
#include <string>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/time/time.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/combobox_model_observer.h"
#include "ui/base/models/menu_model.h"
#include "ui/color/color_id.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/prefix_delegate.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/style/typography.h"
namespace gfx {
class FontList;
}
namespace ui {
class MenuModel;
}
namespace views {
namespace test {
class ComboboxTestApi;
class InteractionTestUtilSimulatorViews;
}
class MenuRunner;
class PrefixSelector;
// A non-editable combobox (aka a drop-down list or selector).
// Combobox has two distinct parts, the drop down arrow and the text.
class VIEWS_EXPORT Combobox : public View,
public PrefixDelegate,
public ui::ComboboxModelObserver {
public:
METADATA_HEADER(Combobox);
using MenuSelectionAtCallback = base::RepeatingCallback<bool(size_t index)>;
static constexpr int kDefaultComboboxTextContext = style::CONTEXT_BUTTON;
static constexpr int kDefaultComboboxTextStyle = style::STYLE_PRIMARY;
// A combobox with an empty model.
explicit Combobox(int text_context = kDefaultComboboxTextContext,
int text_style = kDefaultComboboxTextStyle);
// |model| is owned by the combobox when using this constructor.
explicit Combobox(std::unique_ptr<ui::ComboboxModel> model,
int text_context = kDefaultComboboxTextContext,
int text_style = kDefaultComboboxTextStyle);
// |model| is not owned by the combobox when using this constructor.
explicit Combobox(ui::ComboboxModel* model,
int text_context = kDefaultComboboxTextContext,
int text_style = kDefaultComboboxTextStyle);
Combobox(const Combobox&) = delete;
Combobox& operator=(const Combobox&) = delete;
~Combobox() override;
const gfx::FontList& GetFontList() const;
// Sets the callback which will be called when a selection has been made.
void SetCallback(base::RepeatingClosure callback) {
callback_ = std::move(callback);
}
// Set menu model.
void SetMenuModel(std::unique_ptr<ui::MenuModel> menu_model) {
menu_model_ = std::move(menu_model);
}
// Gets/Sets the selected index.
absl::optional<size_t> GetSelectedIndex() const { return selected_index_; }
void SetSelectedIndex(absl::optional<size_t> index);
[[nodiscard]] base::CallbackListSubscription AddSelectedIndexChangedCallback(
views::PropertyChangedCallback callback);
// Called when there has been a selection from the menu.
void MenuSelectionAt(size_t index);
// Looks for the first occurrence of |value| in |model()|. If found, selects
// the found index and returns true. Otherwise simply noops and returns false.
bool SelectValue(const std::u16string& value);
void SetOwnedModel(std::unique_ptr<ui::ComboboxModel> model);
void SetModel(ui::ComboboxModel* model);
ui::ComboboxModel* GetModel() const { return model_; }
// Gets/Sets the tooltip text, and the accessible name if it is currently
// empty.
std::u16string GetTooltipTextAndAccessibleName() const;
void SetTooltipTextAndAccessibleName(const std::u16string& tooltip_text);
// Visually marks the combobox as having an invalid value selected.
// When invalid, it paints with white text on a red background.
// Callers are responsible for restoring validity with selection changes.
void SetInvalid(bool invalid);
bool GetInvalid() const { return invalid_; }
void SetBorderColorId(ui::ColorId color_id);
void SetBackgroundColorId(ui::ColorId color_id);
void SetForegroundColorId(ui::ColorId color_id);
// Sets whether there should be ink drop highlighting on hover/press.
void SetEventHighlighting(bool should_highlight);
// Whether the combobox should use the largest label as the content size.
void SetSizeToLargestLabel(bool size_to_largest_label);
bool GetSizeToLargestLabel() const { return size_to_largest_label_; }
void SetMenuSelectionAtCallback(MenuSelectionAtCallback callback) {
menu_selection_at_callback_ = std::move(callback);
}
// Set whether the arrow should be shown to the user.
void SetShouldShowArrow(bool should_show_arrow) {
should_show_arrow_ = should_show_arrow;
}
// Use the time when combobox was closed in order for parent view to not
// treat a user event already treated by the combobox.
base::TimeTicks GetClosedTime() { return closed_time_; }
// Returns whether or not the menu is currently running.
bool IsMenuRunning() const;
// Overridden from View:
gfx::Size CalculatePreferredSize() const override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) override;
bool OnKeyPressed(const ui::KeyEvent& e) override;
void OnPaint(gfx::Canvas* canvas) override;
void OnFocus() override;
void OnBlur() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
bool HandleAccessibleAction(const ui::AXActionData& action_data) override;
void OnThemeChanged() override;
// Overridden from PrefixDelegate:
size_t GetRowCount() override;
absl::optional<size_t> GetSelectedRow() override;
void SetSelectedRow(absl::optional<size_t> row) override;
std::u16string GetTextForRow(size_t row) override;
void UpdateFont();
protected:
// Overridden from ComboboxModelObserver:
void OnComboboxModelChanged(ui::ComboboxModel* model) override;
void OnComboboxModelDestroying(ui::ComboboxModel* model) override;
// Getters to be used by metadata.
const base::RepeatingClosure& GetCallback() const;
const std::unique_ptr<ui::ComboboxModel>& GetOwnedModel() const;
private:
friend class test::ComboboxTestApi;
friend class test::InteractionTestUtilSimulatorViews;
// Updates the border according to the current node_data.
void UpdateBorder();
// Given bounds within our View, this helper mirrors the bounds if necessary.
void AdjustBoundsForRTLUI(gfx::Rect* rect) const;
// Draws the selected value of the drop down list
void PaintIconAndText(gfx::Canvas* canvas);
// Opens the dropdown menu in response to |event|.
void ArrowButtonPressed(const ui::Event& event);
// Show the drop down list
void ShowDropDownMenu(ui::MenuSourceType source_type);
// Cleans up after the menu as closed
void OnMenuClosed(Button::ButtonState original_button_state);
// Called when the selection is changed by the user.
void OnPerformAction();
// Finds the size of the largest menu label.
gfx::Size GetContentSize() const;
// Returns the width needed to accommodate the provided width and checkmarks
// and padding if checkmarks should be shown.
int MaybeAdjustWidthForCheckmarks(int original_width) const;
void OnContentSizeMaybeChanged();
PrefixSelector* GetPrefixSelector();
// Optionally used to tie the lifetime of the model to this combobox. See
// constructor.
std::unique_ptr<ui::ComboboxModel> owned_model_;
// Reference to our model, which may be owned or not.
raw_ptr<ui::ComboboxModel> model_ = nullptr;
// Typography context for the text written in the combobox and the options
// shown in the drop-down menu.
const int text_context_;
// Typography style for the text written in the combobox and the options shown
// in the drop-down menu.
const int text_style_;
// Callback notified when the selected index changes.
base::RepeatingClosure callback_;
// Callback notified when the selected index is triggered to change. If set,
// when a selection is made in the combobox this callback is called. If it
// returns true no other action is taken, if it returns false then the model
// will updated based on the selection.
MenuSelectionAtCallback menu_selection_at_callback_;
// The current selected index; nullopt means no selection.
absl::optional<size_t> selected_index_ = absl::nullopt;
// True when the selection is visually denoted as invalid.
bool invalid_ = false;
// True when there should be ink drop highlighting on hover and press.
bool should_highlight_ = false;
// True when the combobox should display the arrow during paint.
bool should_show_arrow_ = true;
// Overriding ColorId for the combobox border.
absl::optional<ui::ColorId> border_color_id_;
// Overriding ColorId for the combobox foreground (text and caret icon).
absl::optional<ui::ColorId> foreground_color_id_;
// A helper used to select entries by keyboard input.
std::unique_ptr<PrefixSelector> selector_;
// The ComboboxModel for use by |menu_runner_|.
std::unique_ptr<ui::MenuModel> menu_model_;
// Like MenuButton, we use a time object in order to keep track of when the
// combobox was closed. The time is used for simulating menu behavior; that
// is, if the menu is shown and the button is pressed, we need to close the
// menu. There is no clean way to get the second click event because the
// menu is displayed using a modal loop and, unlike regular menus in Windows,
// the button is not part of the displayed menu.
base::TimeTicks closed_time_;
// The maximum dimensions of the content in the dropdown.
gfx::Size content_size_;
// A transparent button that handles events and holds button state. Placed on
// top of the combobox as a child view. Doesn't paint itself, but serves as a
// host for inkdrops.
raw_ptr<Button> arrow_button_;
// Set while the dropdown is showing. Ensures the menu is closed if |this| is
// destroyed.
std::unique_ptr<MenuRunner> menu_runner_;
// Called to update background color and border when the combobox is
// enabled/disabled.
base::CallbackListSubscription enabled_changed_subscription_;
// When true, the size of contents is defined by the widest label in the menu.
// If this is set to true, the parent view must relayout in
// ChildPreferredSizeChanged(). When false, the size of contents is defined by
// the selected label
bool size_to_largest_label_ = true;
// The font list to be used for the main dropdown of the combobox. Individual
// menu items on the dropdown may be defined separately by
// ComboboxMenuModel::GetLabelFontListAt.
gfx::FontList font_list_;
base::ScopedObservation<ui::ComboboxModel, ui::ComboboxModelObserver>
observation_{this};
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Combobox, View)
VIEW_BUILDER_PROPERTY(base::RepeatingClosure, Callback)
VIEW_BUILDER_PROPERTY(std::unique_ptr<ui::ComboboxModel>, OwnedModel)
VIEW_BUILDER_PROPERTY(ui::ComboboxModel*, Model)
VIEW_BUILDER_PROPERTY(absl::optional<size_t>, SelectedIndex)
VIEW_BUILDER_PROPERTY(bool, Invalid)
VIEW_BUILDER_PROPERTY(bool, SizeToLargestLabel)
VIEW_BUILDER_PROPERTY(std::u16string, TooltipTextAndAccessibleName)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Combobox)
#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox.h | C++ | unknown | 11,347 |
// Copyright 2022 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/combobox/combobox_menu_model.h"
ComboboxMenuModel::ComboboxMenuModel(views::Combobox* owner,
ui::ComboboxModel* model)
: owner_(owner), model_(model) {}
ComboboxMenuModel::~ComboboxMenuModel() = default;
bool ComboboxMenuModel::UseCheckmarks() const {
return views::MenuConfig::instance().check_selected_combobox_item;
}
// Overridden from MenuModel:
bool ComboboxMenuModel::HasIcons() const {
for (size_t i = 0; i < GetItemCount(); ++i) {
if (!GetIconAt(i).IsEmpty())
return true;
}
return false;
}
size_t ComboboxMenuModel::GetItemCount() const {
return model_->GetItemCount();
}
ui::MenuModel::ItemType ComboboxMenuModel::GetTypeAt(size_t index) const {
if (model_->IsItemSeparatorAt(index))
return TYPE_SEPARATOR;
return UseCheckmarks() ? TYPE_CHECK : TYPE_COMMAND;
}
ui::MenuSeparatorType ComboboxMenuModel::GetSeparatorTypeAt(
size_t index) const {
return ui::NORMAL_SEPARATOR;
}
int ComboboxMenuModel::GetCommandIdAt(size_t index) const {
// Define the id of the first item in the menu (since it needs to be > 0)
constexpr int kFirstMenuItemId = 1000;
return static_cast<int>(index) + kFirstMenuItemId;
}
std::u16string ComboboxMenuModel::GetLabelAt(size_t index) const {
// Inserting the Unicode formatting characters if necessary so that the
// text is displayed correctly in right-to-left UIs.
std::u16string text = model_->GetDropDownTextAt(index);
base::i18n::AdjustStringForLocaleDirection(&text);
return text;
}
std::u16string ComboboxMenuModel::GetSecondaryLabelAt(size_t index) const {
std::u16string text = model_->GetDropDownSecondaryTextAt(index);
base::i18n::AdjustStringForLocaleDirection(&text);
return text;
}
bool ComboboxMenuModel::IsItemDynamicAt(size_t index) const {
return true;
}
const gfx::FontList* ComboboxMenuModel::GetLabelFontListAt(size_t index) const {
return &owner_->GetFontList();
}
bool ComboboxMenuModel::GetAcceleratorAt(size_t index,
ui::Accelerator* accelerator) const {
return false;
}
bool ComboboxMenuModel::IsItemCheckedAt(size_t index) const {
return UseCheckmarks() && index == owner_->GetSelectedIndex();
}
int ComboboxMenuModel::GetGroupIdAt(size_t index) const {
return -1;
}
ui::ImageModel ComboboxMenuModel::GetIconAt(size_t index) const {
return model_->GetDropDownIconAt(index);
}
ui::ButtonMenuItemModel* ComboboxMenuModel::GetButtonMenuItemAt(
size_t index) const {
return nullptr;
}
bool ComboboxMenuModel::IsEnabledAt(size_t index) const {
return model_->IsItemEnabledAt(index);
}
void ComboboxMenuModel::ActivatedAt(size_t index) {
owner_->MenuSelectionAt(index);
}
void ComboboxMenuModel::ActivatedAt(size_t index, int event_flags) {
ActivatedAt(index);
}
ui::MenuModel* ComboboxMenuModel::GetSubmenuModelAt(size_t index) const {
return nullptr;
}
absl::optional<ui::ColorId> ComboboxMenuModel::GetForegroundColorId(
size_t index) {
return model_->GetDropdownForegroundColorIdAt(index);
}
absl::optional<ui::ColorId> ComboboxMenuModel::GetSubmenuBackgroundColorId(
size_t index) {
return model_->GetDropdownBackgroundColorIdAt(index);
}
absl::optional<ui::ColorId> ComboboxMenuModel::GetSelectedBackgroundColorId(
size_t index) {
return model_->GetDropdownSelectedBackgroundColorIdAt(index);
}
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox_menu_model.cc | C++ | unknown | 3,537 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_MENU_MODEL_H_
#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_MENU_MODEL_H_
#include "base/i18n/rtl.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/image_model.h"
#include "ui/base/models/menu_model.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/menu/menu_config.h"
// Adapts a ui::ComboboxModel to a ui::MenuModel.
class VIEWS_EXPORT ComboboxMenuModel : public ui::MenuModel {
public:
ComboboxMenuModel(views::Combobox* owner, ui::ComboboxModel* model);
ComboboxMenuModel(const ComboboxMenuModel&) = delete;
ComboboxMenuModel& operator&(const ComboboxMenuModel&) = delete;
~ComboboxMenuModel() override;
absl::optional<ui::ColorId> GetForegroundColorId(size_t index) override;
absl::optional<ui::ColorId> GetSubmenuBackgroundColorId(
size_t index) override;
absl::optional<ui::ColorId> GetSelectedBackgroundColorId(
size_t index) override;
void SetForegroundColorId(absl::optional<ui::ColorId> foreground_color) {
foreground_color_id_ = foreground_color;
}
void SetSubmenuBackgroundColorId(
absl::optional<ui::ColorId> background_color) {
submenu_background_color_id_ = background_color;
}
void SetSelectedBackgroundColorId(
absl::optional<ui::ColorId> selected_color) {
selected_background_color_id_ = selected_color;
}
protected:
ui::ComboboxModel* GetModel() const { return model_; }
const gfx::FontList* GetLabelFontListAt(size_t index) const override;
private:
bool UseCheckmarks() const;
// Overridden from MenuModel:
bool HasIcons() const override;
size_t GetItemCount() const override;
ui::MenuModel::ItemType GetTypeAt(size_t index) const override;
ui::MenuSeparatorType GetSeparatorTypeAt(size_t index) const override;
int GetCommandIdAt(size_t index) const override;
std::u16string GetLabelAt(size_t index) const override;
std::u16string GetSecondaryLabelAt(size_t index) const override;
bool IsItemDynamicAt(size_t index) const override;
bool GetAcceleratorAt(size_t index,
ui::Accelerator* accelerator) const override;
bool IsItemCheckedAt(size_t index) const override;
int GetGroupIdAt(size_t index) const override;
ui::ImageModel GetIconAt(size_t index) const override;
ui::ButtonMenuItemModel* GetButtonMenuItemAt(size_t index) const override;
bool IsEnabledAt(size_t index) const override;
void ActivatedAt(size_t index) override;
void ActivatedAt(size_t index, int event_flags) override;
ui::MenuModel* GetSubmenuModelAt(size_t index) const override;
absl::optional<ui::ColorId> foreground_color_id_;
absl::optional<ui::ColorId> submenu_background_color_id_;
absl::optional<ui::ColorId> selected_background_color_id_;
raw_ptr<views::Combobox> owner_; // Weak. Owns this.
raw_ptr<ui::ComboboxModel> model_; // Weak.
};
#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_MENU_MODEL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox_menu_model.h | C++ | unknown | 3,095 |
// Copyright 2013 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/combobox/combobox.h"
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.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/ime/text_input_client.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/combobox_model_observer.h"
#include "ui/base/models/menu_model.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/text_utils.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/test/combobox_test_api.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_utils.h"
using base::ASCIIToUTF16;
namespace views {
using test::ComboboxTestApi;
namespace {
using TestCombobox = Combobox;
// A concrete class is needed to test the combobox.
class TestComboboxModel : public ui::ComboboxModel {
public:
TestComboboxModel() = default;
TestComboboxModel(const TestComboboxModel&) = delete;
TestComboboxModel& operator=(const TestComboboxModel&) = delete;
~TestComboboxModel() override = default;
static constexpr size_t kItemCount = 10;
// ui::ComboboxModel:
size_t GetItemCount() const override { return item_count_; }
std::u16string GetItemAt(size_t index) const override {
DCHECK(!IsItemSeparatorAt(index));
return ASCIIToUTF16(index % 2 == 0 ? "PEANUT BUTTER" : "JELLY");
}
bool IsItemSeparatorAt(size_t index) const override {
return separators_.find(index) != separators_.end();
}
absl::optional<size_t> GetDefaultIndex() const override {
// Return the first index that is not a separator.
for (size_t index = 0; index < kItemCount; ++index) {
if (separators_.find(index) == separators_.end())
return index;
}
NOTREACHED_NORETURN();
}
void SetSeparators(const std::set<size_t>& separators) {
separators_ = separators;
OnModelChanged();
}
void set_item_count(size_t item_count) {
item_count_ = item_count;
OnModelChanged();
}
private:
void OnModelChanged() {
for (auto& observer : observers())
observer.OnComboboxModelChanged(this);
}
std::set<size_t> separators_;
size_t item_count_ = kItemCount;
};
// A combobox model which refers to a vector.
class VectorComboboxModel : public ui::ComboboxModel {
public:
explicit VectorComboboxModel(std::vector<std::string>* values)
: values_(values) {}
VectorComboboxModel(const VectorComboboxModel&) = delete;
VectorComboboxModel& operator=(const VectorComboboxModel&) = delete;
~VectorComboboxModel() override = default;
void set_default_index(size_t default_index) {
default_index_ = default_index;
}
// ui::ComboboxModel:
size_t GetItemCount() const override { return values_->size(); }
std::u16string GetItemAt(size_t index) const override {
return ASCIIToUTF16((*values_)[index]);
}
bool IsItemSeparatorAt(size_t index) const override { return false; }
absl::optional<size_t> GetDefaultIndex() const override {
return default_index_;
}
void ValuesChanged() {
for (auto& observer : observers())
observer.OnComboboxModelChanged(this);
}
private:
size_t default_index_ = 0;
const raw_ptr<std::vector<std::string>> values_;
};
// A combobox model which uses a custom font.
class CustomFontComboboxModel : public ui::ComboboxModel {
public:
CustomFontComboboxModel() = default;
CustomFontComboboxModel(const CustomFontComboboxModel&) = delete;
CustomFontComboboxModel& operator=(const CustomFontComboboxModel&) = delete;
~CustomFontComboboxModel() override = default;
// ui::ComboboxModel:
size_t GetItemCount() const override { return 2; }
std::u16string GetItemAt(size_t index) const override {
return ASCIIToUTF16(index % 2 == 0 ? "EVEN" : "ODD");
}
std::vector<std::string> GetLabelFontNameAt(size_t index) override {
return {font_, "Arial"};
}
absl::optional<int> GetLabelFontSize() override { return 25; }
void SetFontString(std::string font) { font_ = font; }
std::string font_ = "Arial";
};
class EvilListener {
public:
EvilListener() {
combobox_->SetCallback(base::BindRepeating(&EvilListener::OnPerformAction,
base::Unretained(this)));
}
EvilListener(const EvilListener&) = delete;
EvilListener& operator=(const EvilListener&) = delete;
~EvilListener() = default;
TestCombobox* combobox() { return combobox_.get(); }
private:
void OnPerformAction() { combobox_.reset(); }
TestComboboxModel model_;
std::unique_ptr<TestCombobox> combobox_ =
std::make_unique<TestCombobox>(&model_);
};
class TestComboboxListener {
public:
explicit TestComboboxListener(Combobox* combobox) : combobox_(combobox) {}
TestComboboxListener(const TestComboboxListener&) = delete;
TestComboboxListener& operator=(const TestComboboxListener&) = delete;
~TestComboboxListener() = default;
void OnPerformAction() {
perform_action_index_ = combobox_->GetSelectedIndex();
actions_performed_++;
}
absl::optional<size_t> perform_action_index() const {
return perform_action_index_;
}
bool on_perform_action_called() const { return actions_performed_ > 0; }
int actions_performed() const { return actions_performed_; }
private:
raw_ptr<Combobox> combobox_;
absl::optional<size_t> perform_action_index_ = absl::nullopt;
int actions_performed_ = 0;
};
} // namespace
class ComboboxTest : public ViewsTestBase {
public:
ComboboxTest() = default;
ComboboxTest(const ComboboxTest&) = delete;
ComboboxTest& operator=(const ComboboxTest&) = delete;
void TearDown() override {
widget_.reset();
ViewsTestBase::TearDown();
}
void InitCombobox(const std::set<size_t>* separators) {
model_ = std::make_unique<TestComboboxModel>();
if (separators)
model_->SetSeparators(*separators);
ASSERT_FALSE(combobox_);
auto combobox = std::make_unique<TestCombobox>(model_.get());
test_api_ = std::make_unique<ComboboxTestApi>(combobox.get());
test_api_->InstallTestMenuRunner(&menu_show_count_);
combobox->SetID(1);
widget_ = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(200, 200, 200, 200);
widget_->Init(std::move(params));
View* container = widget_->SetContentsView(std::make_unique<View>());
combobox_ = container->AddChildView(std::move(combobox));
widget_->Show();
combobox_->RequestFocus();
combobox_->SizeToPreferredSize();
event_generator_ = std::make_unique<ui::test::EventGenerator>(
GetRootWindow(widget_.get()));
event_generator_->set_target(ui::test::EventGenerator::Target::WINDOW);
}
protected:
void PressKey(ui::KeyboardCode key_code, ui::EventFlags flags = ui::EF_NONE) {
event_generator_->PressKey(key_code, flags);
}
void ReleaseKey(ui::KeyboardCode key_code,
ui::EventFlags flags = ui::EF_NONE) {
event_generator_->ReleaseKey(key_code, flags);
}
View* GetFocusedView() {
return widget_->GetFocusManager()->GetFocusedView();
}
void PerformMousePress(const gfx::Point& point) {
ui::MouseEvent pressed_event = ui::MouseEvent(
ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
widget_->OnMouseEvent(&pressed_event);
}
void PerformMouseRelease(const gfx::Point& point) {
ui::MouseEvent released_event = ui::MouseEvent(
ui::ET_MOUSE_RELEASED, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
widget_->OnMouseEvent(&released_event);
}
void PerformClick(const gfx::Point& point) {
PerformMousePress(point);
PerformMouseRelease(point);
}
// We need widget to populate wrapper class.
UniqueWidgetPtr widget_;
// |combobox_| will be allocated InitCombobox() and then owned by |widget_|.
raw_ptr<TestCombobox> combobox_ = nullptr;
std::unique_ptr<ComboboxTestApi> test_api_;
// Combobox does not take ownership of the model, hence it needs to be scoped.
std::unique_ptr<TestComboboxModel> model_;
// The current menu show count.
int menu_show_count_ = 0;
std::unique_ptr<ui::test::EventGenerator> event_generator_;
};
#if BUILDFLAG(IS_MAC)
// Tests whether the various Mac specific keyboard shortcuts invoke the dropdown
// menu or not.
TEST_F(ComboboxTest, KeyTestMac) {
InitCombobox(nullptr);
PressKey(ui::VKEY_END);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(1, menu_show_count_);
PressKey(ui::VKEY_HOME);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(2, menu_show_count_);
PressKey(ui::VKEY_UP, ui::EF_COMMAND_DOWN);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(3, menu_show_count_);
PressKey(ui::VKEY_DOWN, ui::EF_COMMAND_DOWN);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(4, menu_show_count_);
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(5, menu_show_count_);
PressKey(ui::VKEY_RIGHT);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(5, menu_show_count_);
PressKey(ui::VKEY_LEFT);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(5, menu_show_count_);
PressKey(ui::VKEY_UP);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(6, menu_show_count_);
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(6, menu_show_count_);
PressKey(ui::VKEY_NEXT);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_EQ(6, menu_show_count_);
}
#endif
// Iterate through all the metadata and test each property.
TEST_F(ComboboxTest, MetadataTest) {
InitCombobox(nullptr);
test::TestViewMetadata(combobox_);
}
// Check that if a combobox is disabled before it has a native wrapper, then the
// native wrapper inherits the disabled state when it gets created.
TEST_F(ComboboxTest, DisabilityTest) {
model_ = std::make_unique<TestComboboxModel>();
ASSERT_FALSE(combobox_);
auto combobox = std::make_unique<TestCombobox>(model_.get());
combobox->SetEnabled(false);
widget_ = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(100, 100, 100, 100);
widget_->Init(std::move(params));
View* container = widget_->SetContentsView(std::make_unique<View>());
combobox_ = container->AddChildView(std::move(combobox));
EXPECT_FALSE(combobox_->GetEnabled());
}
// Ensure the border on the combobox is set correctly when Enabled state
// changes.
TEST_F(ComboboxTest, DisabledBorderTest) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kChromeRefresh2023);
InitCombobox(nullptr);
ASSERT_TRUE(combobox_->GetEnabled());
ASSERT_NE(combobox_->GetBorder(), nullptr);
combobox_->SetEnabled(false);
ASSERT_FALSE(combobox_->GetEnabled());
ASSERT_EQ(combobox_->GetBorder(), nullptr);
combobox_->SetEnabled(true);
ASSERT_TRUE(combobox_->GetEnabled());
ASSERT_NE(combobox_->GetBorder(), nullptr);
}
// On Mac, key events can't change the currently selected index directly for a
// combobox.
#if !BUILDFLAG(IS_MAC)
// Tests the behavior of various keyboard shortcuts on the currently selected
// index.
TEST_F(ComboboxTest, KeyTest) {
InitCombobox(nullptr);
PressKey(ui::VKEY_END);
EXPECT_EQ(model_->GetItemCount() - 1, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_HOME);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(2u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_RIGHT);
EXPECT_EQ(2u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_LEFT);
EXPECT_EQ(2u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_NEXT);
EXPECT_EQ(model_->GetItemCount() - 1, combobox_->GetSelectedIndex());
}
// Verifies that we don't select a separator line in combobox when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipSeparatorSimple) {
std::set<size_t> separators;
separators.insert(2);
InitCombobox(&separators);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_HOME);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_END);
EXPECT_EQ(9u, combobox_->GetSelectedIndex());
}
// Verifies that we never select the separator that is in the beginning of the
// combobox list when navigating through keyboard.
TEST_F(ComboboxTest, SkipSeparatorBeginning) {
std::set<size_t> separators;
separators.insert(0);
InitCombobox(&separators);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(2u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(2u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_HOME);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_END);
EXPECT_EQ(9u, combobox_->GetSelectedIndex());
}
// Verifies that we never select the separator that is in the end of the
// combobox list when navigating through keyboard.
TEST_F(ComboboxTest, SkipSeparatorEnd) {
std::set<size_t> separators;
separators.insert(TestComboboxModel::kItemCount - 1);
InitCombobox(&separators);
combobox_->SetSelectedIndex(8);
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(8u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(7u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_END);
EXPECT_EQ(8u, combobox_->GetSelectedIndex());
}
// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the beginning of the combobox list when
// navigating through keyboard.
TEST_F(ComboboxTest, SkipMultipleSeparatorsAtBeginning) {
std::set<size_t> separators;
separators.insert(0);
separators.insert(1);
separators.insert(2);
InitCombobox(&separators);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(4u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_NEXT);
EXPECT_EQ(9u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_HOME);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_END);
EXPECT_EQ(9u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
}
// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the middle of the combobox list when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipMultipleAdjacentSeparatorsAtMiddle) {
std::set<size_t> separators;
separators.insert(4);
separators.insert(5);
separators.insert(6);
InitCombobox(&separators);
combobox_->SetSelectedIndex(3);
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(7u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(3u, combobox_->GetSelectedIndex());
}
// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the end of the combobox list when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipMultipleSeparatorsAtEnd) {
std::set<size_t> separators;
separators.insert(7);
separators.insert(8);
separators.insert(9);
InitCombobox(&separators);
combobox_->SetSelectedIndex(6);
PressKey(ui::VKEY_DOWN);
EXPECT_EQ(6u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_UP);
EXPECT_EQ(5u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_HOME);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_NEXT);
EXPECT_EQ(6u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_PRIOR);
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
PressKey(ui::VKEY_END);
EXPECT_EQ(6u, combobox_->GetSelectedIndex());
}
#endif // !BUILDFLAG(IS_MAC)
TEST_F(ComboboxTest, GetTextForRowTest) {
std::set<size_t> separators;
separators.insert(0);
separators.insert(1);
separators.insert(9);
InitCombobox(&separators);
for (size_t i = 0; i < combobox_->GetRowCount(); ++i) {
if (separators.count(i) != 0) {
EXPECT_TRUE(combobox_->GetTextForRow(i).empty()) << i;
} else {
EXPECT_EQ(ASCIIToUTF16(i % 2 == 0 ? "PEANUT BUTTER" : "JELLY"),
combobox_->GetTextForRow(i))
<< i;
}
}
}
// Verifies selecting the first matching value (and returning whether found).
TEST_F(ComboboxTest, SelectValue) {
InitCombobox(nullptr);
ASSERT_EQ(model_->GetDefaultIndex(), combobox_->GetSelectedIndex());
EXPECT_TRUE(combobox_->SelectValue(u"PEANUT BUTTER"));
EXPECT_EQ(0u, combobox_->GetSelectedIndex());
EXPECT_TRUE(combobox_->SelectValue(u"JELLY"));
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
EXPECT_FALSE(combobox_->SelectValue(u"BANANAS"));
EXPECT_EQ(1u, combobox_->GetSelectedIndex());
}
TEST_F(ComboboxTest, ListenerHandlesDelete) {
auto evil_listener = std::make_unique<EvilListener>();
ASSERT_TRUE(evil_listener->combobox());
ASSERT_NO_FATAL_FAILURE(
ComboboxTestApi(evil_listener->combobox()).PerformActionAt(2));
EXPECT_FALSE(evil_listener->combobox());
}
TEST_F(ComboboxTest, Click) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
views::test::RunScheduledLayout(combobox_);
// Click the left side. The menu is shown.
EXPECT_EQ(0, menu_show_count_);
PerformClick(
gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2));
EXPECT_FALSE(listener.on_perform_action_called());
EXPECT_EQ(1, menu_show_count_);
}
TEST_F(ComboboxTest, ClickButDisabled) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
views::test::RunScheduledLayout(combobox_);
combobox_->SetEnabled(false);
// Click the left side, but nothing happens since the combobox is disabled.
PerformClick(
gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2));
EXPECT_FALSE(listener.on_perform_action_called());
EXPECT_EQ(0, menu_show_count_);
}
TEST_F(ComboboxTest, NotifyOnClickWithReturnKey) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
// The click event is ignored. Instead the menu is shown.
PressKey(ui::VKEY_RETURN);
EXPECT_EQ(PlatformStyle::kReturnClicksFocusedControl ? 1 : 0,
menu_show_count_);
EXPECT_FALSE(listener.on_perform_action_called());
}
TEST_F(ComboboxTest, NotifyOnClickWithSpaceKey) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
// The click event is ignored. Instead the menu is shwon.
PressKey(ui::VKEY_SPACE);
EXPECT_EQ(1, menu_show_count_);
EXPECT_FALSE(listener.on_perform_action_called());
ReleaseKey(ui::VKEY_SPACE);
EXPECT_EQ(1, menu_show_count_);
EXPECT_FALSE(listener.on_perform_action_called());
}
// Test that accessibility action events show the combobox dropdown.
TEST_F(ComboboxTest, ShowViaAccessibleAction) {
InitCombobox(nullptr);
ui::AXActionData data;
data.action = ax::mojom::Action::kDoDefault;
EXPECT_EQ(0, menu_show_count_);
combobox_->HandleAccessibleAction(data);
EXPECT_EQ(1, menu_show_count_);
// ax::mojom::Action::kShowContextMenu is specifically for a context menu
// (e.g. right- click). Combobox should ignore it.
data.action = ax::mojom::Action::kShowContextMenu;
combobox_->HandleAccessibleAction(data);
EXPECT_EQ(1, menu_show_count_); // No change.
data.action = ax::mojom::Action::kBlur;
combobox_->HandleAccessibleAction(data);
EXPECT_EQ(1, menu_show_count_); // No change.
combobox_->SetEnabled(false);
combobox_->HandleAccessibleAction(data);
EXPECT_EQ(1, menu_show_count_); // No change.
data.action = ax::mojom::Action::kShowContextMenu;
combobox_->HandleAccessibleAction(data);
EXPECT_EQ(1, menu_show_count_); // No change.
}
TEST_F(ComboboxTest, NotifyOnClickWithMouse) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
views::test::RunScheduledLayout(combobox_);
// Click the right side (arrow button). The menu is shown.
const gfx::Point right_point(combobox_->x() + combobox_->width() - 1,
combobox_->y() + combobox_->height() / 2);
EXPECT_EQ(0, menu_show_count_);
// Menu is shown on mouse down.
PerformMousePress(right_point);
EXPECT_EQ(1, menu_show_count_);
PerformMouseRelease(right_point);
EXPECT_EQ(1, menu_show_count_);
// Click the left side (text button). The click event is notified.
const gfx::Point left_point(
gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2));
PerformMousePress(left_point);
PerformMouseRelease(left_point);
// Both the text and the arrow may toggle the menu.
EXPECT_EQ(2, menu_show_count_);
EXPECT_FALSE(listener.perform_action_index().has_value());
}
TEST_F(ComboboxTest, ConsumingPressKeyEvents) {
InitCombobox(nullptr);
EXPECT_TRUE(combobox_->OnKeyPressed(
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE)));
EXPECT_EQ(1, menu_show_count_);
ui::KeyEvent return_press(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE);
if (PlatformStyle::kReturnClicksFocusedControl) {
EXPECT_TRUE(combobox_->OnKeyPressed(return_press));
EXPECT_EQ(2, menu_show_count_);
} else {
EXPECT_FALSE(combobox_->OnKeyPressed(return_press));
EXPECT_EQ(1, menu_show_count_);
}
}
// Test that ensures that the combobox is resized correctly when selecting
// between indices of different label lengths.
TEST_F(ComboboxTest, ContentSizeUpdateOnSetSelectedIndex) {
const gfx::FontList& font_list =
style::GetFont(Combobox::kDefaultComboboxTextContext,
Combobox::kDefaultComboboxTextStyle);
InitCombobox(nullptr);
combobox_->SetSizeToLargestLabel(false);
test_api_->PerformActionAt(1);
EXPECT_EQ(gfx::GetStringWidth(model_->GetItemAt(1), font_list),
test_api_->content_size().width());
combobox_->SetSelectedIndex(1);
EXPECT_EQ(gfx::GetStringWidth(model_->GetItemAt(1), font_list),
test_api_->content_size().width());
// Avoid selected_index_ == index optimization and start with index 1 selected
// to test resizing from a an index with a shorter label to an index with a
// longer label.
combobox_->SetSelectedIndex(0);
combobox_->SetSelectedIndex(1);
test_api_->PerformActionAt(0);
EXPECT_EQ(gfx::GetStringWidth(model_->GetItemAt(0), font_list),
test_api_->content_size().width());
combobox_->SetSelectedIndex(0);
EXPECT_EQ(gfx::GetStringWidth(model_->GetItemAt(0), font_list),
test_api_->content_size().width());
}
TEST_F(ComboboxTest, ContentWidth) {
std::vector<std::string> values;
VectorComboboxModel model(&values);
TestCombobox combobox(&model);
ComboboxTestApi test_api(&combobox);
std::string long_item = "this is the long item";
std::string short_item = "s";
values.resize(1);
values[0] = long_item;
model.ValuesChanged();
const int long_item_width = test_api.content_size().width();
values[0] = short_item;
model.ValuesChanged();
const int short_item_width = test_api.content_size().width();
values.resize(2);
values[0] = short_item;
values[1] = long_item;
model.ValuesChanged();
// The width will fit with the longest item.
EXPECT_EQ(long_item_width, test_api.content_size().width());
EXPECT_LT(short_item_width, test_api.content_size().width());
}
// Test that model updates preserve the selected index, so long as it is in
// range.
TEST_F(ComboboxTest, ModelChanged) {
InitCombobox(nullptr);
EXPECT_EQ(0u, combobox_->GetSelectedRow());
EXPECT_EQ(10u, combobox_->GetRowCount());
combobox_->SetSelectedIndex(4);
EXPECT_EQ(4u, combobox_->GetSelectedRow());
model_->set_item_count(5);
EXPECT_EQ(5u, combobox_->GetRowCount());
EXPECT_EQ(4u, combobox_->GetSelectedRow()); // Unchanged.
model_->set_item_count(4);
EXPECT_EQ(4u, combobox_->GetRowCount());
EXPECT_EQ(0u, combobox_->GetSelectedRow()); // Resets.
// Restore a non-zero selection.
combobox_->SetSelectedIndex(2);
EXPECT_EQ(2u, combobox_->GetSelectedRow());
// Make the selected index a separator.
std::set<size_t> separators;
separators.insert(2);
model_->SetSeparators(separators);
EXPECT_EQ(4u, combobox_->GetRowCount());
EXPECT_EQ(0u, combobox_->GetSelectedRow()); // Resets.
// Restore a non-zero selection.
combobox_->SetSelectedIndex(1);
EXPECT_EQ(1u, combobox_->GetSelectedRow());
// Test an empty model.
model_->set_item_count(0);
EXPECT_EQ(0u, combobox_->GetRowCount());
EXPECT_EQ(0u, combobox_->GetSelectedRow()); // Resets.
}
TEST_F(ComboboxTest, TypingPrefixNotifiesListener) {
InitCombobox(nullptr);
TestComboboxListener listener(combobox_);
combobox_->SetCallback(base::BindRepeating(
&TestComboboxListener::OnPerformAction, base::Unretained(&listener)));
ui::TextInputClient* input_client =
widget_->GetInputMethod()->GetTextInputClient();
// Type the first character of the second menu item ("JELLY").
ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_J, ui::DomCode::US_J, 0,
ui::DomKey::FromCharacter('J'), ui::EventTimeForNow());
input_client->InsertChar(key_event);
EXPECT_EQ(1, listener.actions_performed());
EXPECT_EQ(1u, listener.perform_action_index());
// Type the second character of "JELLY", item shouldn't change and
// OnPerformAction() shouldn't be re-called.
key_event =
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_E, ui::DomCode::US_E, 0,
ui::DomKey::FromCharacter('E'), ui::EventTimeForNow());
input_client->InsertChar(key_event);
EXPECT_EQ(1, listener.actions_performed());
EXPECT_EQ(1u, listener.perform_action_index());
// Clears the typed text.
combobox_->OnBlur();
combobox_->RequestFocus();
// Type the first character of "PEANUT BUTTER", which should change the
// selected index and perform an action.
key_event =
ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_E, ui::DomCode::US_P, 0,
ui::DomKey::FromCharacter('P'), ui::EventTimeForNow());
input_client->InsertChar(key_event);
EXPECT_EQ(2, listener.actions_performed());
EXPECT_EQ(2u, listener.perform_action_index());
}
// Test properties on the Combobox menu model.
TEST_F(ComboboxTest, MenuModel) {
const int kSeparatorIndex = 3;
std::set<size_t> separators;
separators.insert(kSeparatorIndex);
InitCombobox(&separators);
ui::MenuModel* menu_model = test_api_->menu_model();
EXPECT_EQ(TestComboboxModel::kItemCount, menu_model->GetItemCount());
EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR,
menu_model->GetTypeAt(kSeparatorIndex));
#if BUILDFLAG(IS_MAC)
// Comboboxes on Mac should have checkmarks, with the selected item checked,
EXPECT_EQ(ui::MenuModel::TYPE_CHECK, menu_model->GetTypeAt(0));
EXPECT_EQ(ui::MenuModel::TYPE_CHECK, menu_model->GetTypeAt(1));
EXPECT_TRUE(menu_model->IsItemCheckedAt(0));
EXPECT_FALSE(menu_model->IsItemCheckedAt(1));
combobox_->SetSelectedIndex(1);
EXPECT_FALSE(menu_model->IsItemCheckedAt(0));
EXPECT_TRUE(menu_model->IsItemCheckedAt(1));
#else
EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(0));
EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(1));
#endif
EXPECT_EQ(u"PEANUT BUTTER", menu_model->GetLabelAt(0));
EXPECT_EQ(u"JELLY", menu_model->GetLabelAt(1));
EXPECT_TRUE(menu_model->IsVisibleAt(0));
}
// Verifies SetTooltipTextAndAccessibleName will call NotifyAccessibilityEvent.
TEST_F(ComboboxTest, SetTooltipTextNotifiesAccessibilityEvent) {
InitCombobox(nullptr);
std::u16string test_tooltip_text = u"Test Tooltip Text";
test::AXEventCounter counter(AXEventManager::Get());
EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged));
// `SetTooltipTextAndAccessibleName` does two things:
// 1. sets the tooltip text on the arrow button. `Button::SetTooltipText`
// fires a text-changed event.
// 2. if the accessible name is empty, calls `View::SetAccessibleName`
// on the combobox. `SetAccessibleName` fires a text-changed event.
combobox_->SetTooltipTextAndAccessibleName(test_tooltip_text);
EXPECT_EQ(test_tooltip_text, combobox_->GetTooltipTextAndAccessibleName());
EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged,
ax::mojom::Role::kButton));
EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged,
ax::mojom::Role::kPopUpButton));
EXPECT_EQ(test_tooltip_text, combobox_->GetAccessibleName());
ui::AXNodeData data;
combobox_->GetAccessibleNodeData(&data);
const std::string& name =
data.GetStringAttribute(ax::mojom::StringAttribute::kName);
EXPECT_EQ(test_tooltip_text, ASCIIToUTF16(name));
}
// Regression test for crbug.com/1264288.
// Should fail in ASan build before the fix.
TEST_F(ComboboxTest, NoCrashWhenComboboxOutlivesModel) {
auto model = std::make_unique<TestComboboxModel>();
auto combobox = std::make_unique<TestCombobox>(model.get());
model.reset();
combobox.reset();
}
namespace {
using ComboboxDefaultTest = ViewsTestBase;
class ConfigurableComboboxModel final : public ui::ComboboxModel {
public:
explicit ConfigurableComboboxModel(bool* destroyed = nullptr)
: destroyed_(destroyed) {
if (destroyed_)
*destroyed_ = false;
}
ConfigurableComboboxModel(ConfigurableComboboxModel&) = delete;
ConfigurableComboboxModel& operator=(const ConfigurableComboboxModel&) =
delete;
~ConfigurableComboboxModel() override {
if (destroyed_)
*destroyed_ = true;
}
// ui::ComboboxModel:
size_t GetItemCount() const override { return item_count_; }
std::u16string GetItemAt(size_t index) const override {
DCHECK_LT(index, item_count_);
return base::NumberToString16(index);
}
absl::optional<size_t> GetDefaultIndex() const override {
return default_index_;
}
void SetItemCount(size_t item_count) { item_count_ = item_count; }
void SetDefaultIndex(size_t default_index) { default_index_ = default_index; }
private:
const raw_ptr<bool> destroyed_;
size_t item_count_ = 0;
absl::optional<size_t> default_index_;
};
} // namespace
TEST_F(ComboboxDefaultTest, Default) {
auto combobox = std::make_unique<Combobox>();
EXPECT_EQ(0u, combobox->GetRowCount());
EXPECT_FALSE(combobox->GetSelectedRow().has_value());
}
TEST_F(ComboboxDefaultTest, SetModel) {
bool destroyed = false;
std::unique_ptr<ConfigurableComboboxModel> model =
std::make_unique<ConfigurableComboboxModel>(&destroyed);
model->SetItemCount(42);
model->SetDefaultIndex(27);
{
auto combobox = std::make_unique<Combobox>();
combobox->SetModel(model.get());
EXPECT_EQ(42u, combobox->GetRowCount());
EXPECT_EQ(27u, combobox->GetSelectedRow());
}
EXPECT_FALSE(destroyed);
}
TEST_F(ComboboxDefaultTest, SetOwnedModel) {
bool destroyed = false;
std::unique_ptr<ConfigurableComboboxModel> model =
std::make_unique<ConfigurableComboboxModel>(&destroyed);
model->SetItemCount(42);
model->SetDefaultIndex(27);
{
auto combobox = std::make_unique<Combobox>();
combobox->SetOwnedModel(std::move(model));
EXPECT_EQ(42u, combobox->GetRowCount());
EXPECT_EQ(27u, combobox->GetSelectedRow());
}
EXPECT_TRUE(destroyed);
}
TEST_F(ComboboxDefaultTest, SetModelOverwriteOwned) {
bool destroyed = false;
std::unique_ptr<ConfigurableComboboxModel> model =
std::make_unique<ConfigurableComboboxModel>(&destroyed);
auto combobox = std::make_unique<Combobox>();
combobox->SetModel(model.get());
ASSERT_FALSE(destroyed);
combobox->SetOwnedModel(std::make_unique<ConfigurableComboboxModel>());
EXPECT_FALSE(destroyed);
}
TEST_F(ComboboxDefaultTest, SetOwnedModelOverwriteOwned) {
bool destroyed_first = false;
bool destroyed_second = false;
{
auto combobox = std::make_unique<Combobox>();
combobox->SetOwnedModel(
std::make_unique<ConfigurableComboboxModel>(&destroyed_first));
ASSERT_FALSE(destroyed_first);
combobox->SetOwnedModel(
std::make_unique<ConfigurableComboboxModel>(&destroyed_second));
EXPECT_TRUE(destroyed_first);
ASSERT_FALSE(destroyed_second);
}
EXPECT_TRUE(destroyed_second);
}
TEST_F(ComboboxDefaultTest, DefaultFontUsedBeforeUpdateFont) {
auto combobox = std::make_unique<Combobox>();
ASSERT_TRUE(combobox->GetModel()->GetLabelFontNameAt(0).empty());
const gfx::FontList font_list1 = combobox->GetFontList();
combobox->UpdateFont();
const gfx::FontList font_list2 = combobox->GetFontList();
// Test that the default font used is the same after UpdateFont is explicitly
// called.
EXPECT_EQ(font_list1.GetPrimaryFont().GetFontName(),
font_list2.GetPrimaryFont().GetFontName());
}
TEST_F(ComboboxDefaultTest, UpdateFontUsesCustomFont) {
CustomFontComboboxModel model;
Combobox combobox(&model);
ASSERT_FALSE(combobox.GetModel()->GetLabelFontNameAt(0).empty());
ASSERT_FALSE(combobox.GetModel()->GetLabelFontNameAt(1).empty());
// Default font from the model is used.
combobox.UpdateFont();
// Instead of asserting that "Arial" == the primary font, assert that a font
// created with the "Arial" font string == the primary font. This is because
// some platforms, such as fuchsia, don't support all fonts.
EXPECT_EQ(gfx::Font("Arial", 15).GetFontName(),
combobox.GetFontList().GetPrimaryFont().GetFontName());
// Update Font isn't called so the combobox font isn't updated.
model.SetFontString("Comic Sans");
EXPECT_NE("Comic Sans",
combobox.GetFontList().GetPrimaryFont().GetFontName());
model.SetFontString("Times New Roman");
combobox.UpdateFont();
// Wrap Times New Roman in a gfx::Font in case it is not supported on a
// platform (i.e. fuchsia).
EXPECT_EQ(gfx::Font("Times New Roman", 15).GetFontName(),
combobox.GetFontList().GetPrimaryFont().GetFontName());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox_unittest.cc | C++ | unknown | 36,050 |
// Copyright 2019 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/combobox/combobox_util.h"
#include <memory>
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/typography.h"
namespace views {
const int kComboboxArrowPaddingWidth = 8;
const int kComboboxArrowPaddingWidthChromeRefresh2023 = 4;
int GetComboboxArrowContainerWidthAndMargins() {
// For ChromeRefresh2023, add extra margins between combobox arrow container
// and edge of the combobox.
return features::IsChromeRefresh2023()
? GetComboboxArrowContainerWidth() +
LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING)
: GetComboboxArrowContainerWidth();
}
int GetComboboxArrowContainerWidth() {
int padding = features::IsChromeRefresh2023()
? kComboboxArrowPaddingWidthChromeRefresh2023 * 2
: kComboboxArrowPaddingWidth * 2;
return ComboboxArrowSize().width() + padding;
}
void PaintComboboxArrow(SkColor color,
const gfx::Rect& bounds,
gfx::Canvas* canvas) {
// Since this is a core piece of UI and vector icons don't handle fractional
// scale factors particularly well, manually draw an arrow and make sure it
// looks good at all scale factors.
float dsf = canvas->UndoDeviceScaleFactor();
SkScalar x = std::ceil(bounds.x() * dsf);
SkScalar y = std::ceil(bounds.y() * dsf);
SkScalar height = std::floor(bounds.height() * dsf);
SkPath path;
// This epsilon makes sure that all the aliasing pixels are slightly more
// than half full. Otherwise, rounding issues cause some to be considered
// slightly less than half full and come out a little lighter.
constexpr SkScalar kEpsilon = 0.0001f;
path.moveTo(x - kEpsilon, y);
path.rLineTo(/*dx=*/height, /*dy=*/height);
path.rLineTo(/*dx=*/2 * kEpsilon, /*dy=*/0);
path.rLineTo(/*dx=*/height, /*dy=*/-height);
path.close();
cc::PaintFlags flags;
flags.setColor(color);
flags.setAntiAlias(true);
canvas->DrawPath(path, flags);
}
void ConfigureComboboxButtonInkDrop(Button* host_view) {
InkDrop::Get(host_view)->SetMode(views::InkDropHost::InkDropMode::ON);
host_view->SetHasInkDropActionOnClick(true);
if (features::IsChromeRefresh2023()) {
// We must use UseInkDropForFloodFillRipple here because
// UseInkDropForSquareRipple hides the InkDrop when the ripple effect is
// active instead of layering underneath it causing flashing.
InkDrop::UseInkDropForFloodFillRipple(InkDrop::Get(host_view),
/*highlight_on_hover=*/true);
// Chrome Refresh colors already have opacity applied for hover and pressed
// states. Set the highlight opacity to 1 so the two values don't compound.
InkDrop::Get(host_view)->SetHighlightOpacity(1);
} else {
InkDrop::UseInkDropForSquareRipple(InkDrop::Get(host_view),
/*highlight_on_hover=*/false);
}
views::InkDrop::Get(host_view)->SetBaseColorCallback(base::BindRepeating(
[](Button* host) {
return color_utils::DeriveDefaultIconColor(
host->GetColorProvider()->GetColor(
features::IsChromeRefresh2023()
? ui::kColorComboboxInkDropHovered
: views::style::GetColorId(views::style::CONTEXT_BUTTON,
views::style::STYLE_PRIMARY)));
},
host_view));
// Chrome Refresh colors already have opacity applied for ripple state. Set
// the ripple opacity to 1 so the two values don't compound.
InkDrop::Get(host_view)->SetCreateRippleCallback(base::BindRepeating(
[](Button* host) -> std::unique_ptr<views::InkDropRipple> {
return std::make_unique<views::FloodFillInkDropRipple>(
InkDrop::Get(host), host->size(),
InkDrop::Get(host)->GetInkDropCenterBasedOnLastEvent(),
host->GetColorProvider()->GetColor(
features::IsChromeRefresh2023()
? ui::kColorComboboxInkDropRipple
: style::GetColorId(style::CONTEXT_TEXTFIELD,
style::STYLE_PRIMARY)),
features::IsChromeRefresh2023()
? 1
: InkDrop::Get(host)->GetVisibleOpacity());
},
host_view));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox_util.cc | C++ | unknown | 5,014 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_UTIL_H_
#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_UTIL_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/size.h"
// Constants and functions common to combobox-like controls so we can reuse code
// and keep the same visual style.
namespace gfx {
class Canvas;
class Rect;
} // namespace gfx
namespace views {
class Button;
// Constants for the size of the combobox arrow.
constexpr gfx::Size ComboboxArrowSize() {
return gfx::Size(/*width=*/8, /*height=*/4);
}
extern const int kComboboxArrowPaddingWidth;
extern const int kComboboxArrowPaddingWidthChromeRefresh2023;
int GetComboboxArrowContainerWidthAndMargins();
int GetComboboxArrowContainerWidth();
// Paints the arrow for a combobox.
void PaintComboboxArrow(SkColor color,
const gfx::Rect& bounds,
gfx::Canvas* canvas);
void ConfigureComboboxButtonInkDrop(Button* host_view);
} // namespace views
#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/combobox_util.h | C++ | unknown | 1,190 |
// 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 "ui/views/controls/combobox/empty_combobox_model.h"
#include <string>
#include "base/notreached.h"
namespace views::internal {
EmptyComboboxModel::EmptyComboboxModel() = default;
EmptyComboboxModel::~EmptyComboboxModel() = default;
size_t EmptyComboboxModel::GetItemCount() const {
return 0;
}
std::u16string EmptyComboboxModel::GetItemAt(size_t index) const {
NOTREACHED_NORETURN();
}
absl::optional<size_t> EmptyComboboxModel::GetDefaultIndex() const {
return absl::nullopt;
}
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/empty_combobox_model.cc | C++ | unknown | 678 |
// 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.
#ifndef UI_VIEWS_CONTROLS_COMBOBOX_EMPTY_COMBOBOX_MODEL_H_
#define UI_VIEWS_CONTROLS_COMBOBOX_EMPTY_COMBOBOX_MODEL_H_
#include "ui/base/models/combobox_model.h"
namespace views::internal {
// An empty model for a combo box.
class EmptyComboboxModel final : public ui::ComboboxModel {
public:
EmptyComboboxModel();
EmptyComboboxModel(EmptyComboboxModel&) = delete;
EmptyComboboxModel& operator=(const EmptyComboboxModel&) = delete;
~EmptyComboboxModel() override;
// ui::ComboboxModel:
size_t GetItemCount() const override;
std::u16string GetItemAt(size_t index) const override;
absl::optional<size_t> GetDefaultIndex() const override;
};
} // namespace views::internal
#endif // UI_VIEWS_CONTROLS_COMBOBOX_EMPTY_COMBOBOX_MODEL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/combobox/empty_combobox_model.h | C++ | unknown | 899 |
// Copyright 2021 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/dot_indicator.h"
#include <algorithm>
#include <utility>
#include "base/memory/ptr_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/views/cascading_property.h"
namespace views {
DotIndicator::~DotIndicator() = default;
// static
DotIndicator* DotIndicator::Install(View* parent) {
auto dot = base::WrapUnique<DotIndicator>(new DotIndicator());
dot->SetPaintToLayer();
dot->layer()->SetFillsBoundsOpaquely(false);
dot->SetVisible(false);
return parent->AddChildView(std::move(dot));
}
void DotIndicator::SetColor(SkColor dot_color, SkColor border_color) {
dot_color_ = dot_color;
border_color_ = border_color;
SchedulePaint();
}
void DotIndicator::Show() {
SetVisible(true);
}
void DotIndicator::Hide() {
SetVisible(false);
}
DotIndicator::DotIndicator() {
// Don't allow the view to process events.
SetCanProcessEventsWithinSubtree(false);
}
void DotIndicator::OnPaint(gfx::Canvas* canvas) {
canvas->SaveLayerAlpha(SK_AlphaOPAQUE);
DCHECK_EQ(width(), height());
float radius = width() / 2.0f;
const float scale = canvas->UndoDeviceScaleFactor();
const int kStrokeWidthPx = 1;
gfx::PointF center = gfx::RectF(GetLocalBounds()).CenterPoint();
center.Scale(scale);
// Fill the center.
cc::PaintFlags flags;
flags.setColor(dot_color_.value_or(GetCascadingAccentColor(this)));
flags.setAntiAlias(true);
canvas->DrawCircle(center, scale * radius - kStrokeWidthPx, flags);
// Draw the border.
flags.setColor(border_color_.value_or(GetCascadingBackgroundColor(this)));
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(kStrokeWidthPx * scale);
canvas->DrawCircle(center, scale * radius - kStrokeWidthPx / 2.0f, flags);
}
void DotIndicator::OnThemeChanged() {
View::OnThemeChanged();
SchedulePaint();
}
BEGIN_METADATA(DotIndicator, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/dot_indicator.cc | C++ | unknown | 2,234 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_DOT_INDICATOR_H_
#define UI_VIEWS_CONTROLS_DOT_INDICATOR_H_
#include "ui/gfx/color_palette.h"
#include "ui/views/view.h"
namespace views {
// Dot indicator that can be added to a view, usually used as a status
// indicator.
class VIEWS_EXPORT DotIndicator : public View {
public:
METADATA_HEADER(DotIndicator);
DotIndicator(DotIndicator&) = delete;
DotIndicator& operator=(const DotIndicator&) = delete;
~DotIndicator() override;
// Create a DotIndicator and adds it to |parent|. The returned dot indicator
// is owned by the |parent|.
static DotIndicator* Install(View* parent);
void SetColor(SkColor dot_color, SkColor border_color);
void Show();
void Hide();
private:
DotIndicator();
// View:
void OnPaint(gfx::Canvas* canvas) override;
void OnThemeChanged() override;
absl::optional<SkColor> dot_color_;
absl::optional<SkColor> border_color_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_DOT_INDICATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/dot_indicator.h | C++ | unknown | 1,133 |
// Copyright 2019 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/editable_combobox/editable_combobox.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/menu_source_utils.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/combobox_model_observer.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_types.h"
#include "ui/color/color_provider.h"
#include "ui/events/event.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/range/range.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/button_controller.h"
#include "ui/views/controls/combobox/combobox_util.h"
#include "ui/views/controls/combobox/empty_combobox_model.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/style/typography.h"
#include "ui/views/vector_icons.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
int kEditableComboboxButtonSize = 24;
int kEditableComboboxControlsContainerInsets = 6;
class Arrow : public Button {
public:
METADATA_HEADER(Arrow);
explicit Arrow(PressedCallback callback) : Button(std::move(callback)) {
if (features::IsChromeRefresh2023()) {
SetPreferredSize(
gfx::Size(kEditableComboboxButtonSize, kEditableComboboxButtonSize));
} else {
SetPreferredSize(gfx::Size(GetComboboxArrowContainerWidthAndMargins(),
ComboboxArrowSize().height()));
SetFocusBehavior(FocusBehavior::NEVER);
}
button_controller()->set_notify_action(
ButtonController::NotifyAction::kOnPress);
ConfigureComboboxButtonInkDrop(this);
SetAccessibilityProperties(ax::mojom::Role::kButton);
}
Arrow(const Arrow&) = delete;
Arrow& operator=(const Arrow&) = delete;
~Arrow() override = default;
double GetAnimationValue() const {
return hover_animation().GetCurrentValue();
}
private:
void PaintButtonContents(gfx::Canvas* canvas) override {
gfx::ScopedCanvas scoped_canvas(canvas);
canvas->ClipRect(GetContentsBounds());
gfx::Rect arrow_bounds = GetLocalBounds();
arrow_bounds.ClampToCenteredSize(ComboboxArrowSize());
// Make sure the arrow use the same color as the text in the combobox.
PaintComboboxArrow(
GetColorProvider()->GetColor(style::GetColorId(
style::CONTEXT_TEXTFIELD,
GetEnabled() ? style::STYLE_PRIMARY : style::STYLE_DISABLED)),
arrow_bounds, canvas);
}
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
Button::GetAccessibleNodeData(node_data);
node_data->SetHasPopup(ax::mojom::HasPopup::kMenu);
if (GetEnabled()) {
node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kOpen);
}
}
};
BEGIN_METADATA(Arrow, Button)
END_METADATA
} // namespace
std::u16string EditableCombobox::MenuDecorationStrategy::DecorateItemText(
std::u16string text) const {
return text;
}
// Adapts a ui::ComboboxModel to a ui::MenuModel to be used by EditableCombobox.
// Also provides a filtering capability.
class EditableCombobox::EditableComboboxMenuModel
: public ui::MenuModel,
public ui::ComboboxModelObserver {
public:
EditableComboboxMenuModel(EditableCombobox* owner,
std::unique_ptr<ui::ComboboxModel> combobox_model,
const bool filter_on_edit,
const bool show_on_empty)
: decoration_strategy_(std::make_unique<MenuDecorationStrategy>()),
owner_(owner),
combobox_model_(std::move(combobox_model)),
filter_on_edit_(filter_on_edit),
show_on_empty_(show_on_empty) {
UpdateItemsShown();
observation_.Observe(combobox_model_.get());
}
EditableComboboxMenuModel(const EditableComboboxMenuModel&) = delete;
EditableComboboxMenuModel& operator=(const EditableComboboxMenuModel&) =
delete;
~EditableComboboxMenuModel() override = default;
void UpdateItemsShown() {
if (!update_items_shown_enabled_) {
return;
}
items_shown_.clear();
if (show_on_empty_ || !owner_->GetText().empty()) {
for (size_t i = 0; i < combobox_model_->GetItemCount(); ++i) {
if (!filter_on_edit_ ||
base::StartsWith(combobox_model_->GetItemAt(i), owner_->GetText(),
base::CompareCase::INSENSITIVE_ASCII)) {
items_shown_.push_back({i, combobox_model_->IsItemEnabledAt(i)});
}
}
}
if (menu_model_delegate()) {
menu_model_delegate()->OnMenuStructureChanged();
}
}
void SetDecorationStrategy(
std::unique_ptr<EditableCombobox::MenuDecorationStrategy> strategy) {
DCHECK(strategy);
decoration_strategy_ = std::move(strategy);
UpdateItemsShown();
}
void DisableUpdateItemsShown() { update_items_shown_enabled_ = false; }
void EnableUpdateItemsShown() { update_items_shown_enabled_ = true; }
bool UseCheckmarks() const {
return MenuConfig::instance().check_selected_combobox_item;
}
std::u16string GetItemTextAt(size_t index) const {
return combobox_model_->GetItemAt(items_shown_[index].index);
}
const ui::ComboboxModel* GetComboboxModel() const {
return combobox_model_.get();
}
ui::ImageModel GetIconAt(size_t index) const override {
return combobox_model_->GetDropDownIconAt(items_shown_[index].index);
}
// ComboboxModelObserver:
void OnComboboxModelChanged(ui::ComboboxModel* model) override {
UpdateItemsShown();
}
void OnComboboxModelDestroying(ui::ComboboxModel* model) override {
observation_.Reset();
}
size_t GetItemCount() const override { return items_shown_.size(); }
// ui::MenuModel:
std::u16string GetLabelAt(size_t index) const override {
std::u16string text =
decoration_strategy_->DecorateItemText(GetItemTextAt(index));
base::i18n::AdjustStringForLocaleDirection(&text);
return text;
}
private:
struct ShownItem {
size_t index;
bool enabled;
};
bool HasIcons() const override {
for (size_t i = 0; i < GetItemCount(); ++i) {
if (!GetIconAt(i).IsEmpty()) {
return true;
}
}
return false;
}
ItemType GetTypeAt(size_t index) const override {
return UseCheckmarks() ? TYPE_CHECK : TYPE_COMMAND;
}
ui::MenuSeparatorType GetSeparatorTypeAt(size_t index) const override {
return ui::NORMAL_SEPARATOR;
}
int GetCommandIdAt(size_t index) const override {
constexpr int kFirstMenuItemId = 1000;
return static_cast<int>(index) + kFirstMenuItemId;
}
bool IsItemDynamicAt(size_t index) const override { return false; }
const gfx::FontList* GetLabelFontListAt(size_t index) const override {
return &owner_->GetFontList();
}
bool GetAcceleratorAt(size_t index,
ui::Accelerator* accelerator) const override {
return false;
}
bool IsItemCheckedAt(size_t index) const override {
return UseCheckmarks() &&
combobox_model_->GetItemAt(items_shown_[index].index) ==
owner_->GetText();
}
int GetGroupIdAt(size_t index) const override { return -1; }
ui::ButtonMenuItemModel* GetButtonMenuItemAt(size_t index) const override {
return nullptr;
}
bool IsEnabledAt(size_t index) const override {
return items_shown_[index].enabled;
}
void ActivatedAt(size_t index) override { owner_->OnItemSelected(index); }
MenuModel* GetSubmenuModelAt(size_t index) const override { return nullptr; }
// The strategy used to customize the display of the dropdown menu.
std::unique_ptr<MenuDecorationStrategy> decoration_strategy_;
raw_ptr<EditableCombobox> owner_; // Weak. Owns |this|.
std::unique_ptr<ui::ComboboxModel> combobox_model_;
// Whether to adapt the items shown to the textfield content.
const bool filter_on_edit_;
// Whether to show options when the textfield is empty.
const bool show_on_empty_;
// The indices of the items from |combobox_model_| that we are currently
// showing, and whether they are enabled.
std::vector<ShownItem> items_shown_;
// When false, UpdateItemsShown doesn't do anything.
bool update_items_shown_enabled_ = true;
base::ScopedObservation<ui::ComboboxModel, ui::ComboboxModelObserver>
observation_{this};
};
// This class adds itself as the pre-target handler for the RootView of the
// EditableCombobox. We use it to close the menu when press events happen in the
// RootView but not inside the EditableComboobox's textfield.
class EditableCombobox::EditableComboboxPreTargetHandler
: public ui::EventHandler {
public:
EditableComboboxPreTargetHandler(EditableCombobox* owner, View* root_view)
: owner_(owner), root_view_(root_view) {
root_view_->AddPreTargetHandler(this);
}
EditableComboboxPreTargetHandler(const EditableComboboxPreTargetHandler&) =
delete;
EditableComboboxPreTargetHandler& operator=(
const EditableComboboxPreTargetHandler&) = delete;
~EditableComboboxPreTargetHandler() override { StopObserving(); }
// ui::EventHandler overrides.
void OnMouseEvent(ui::MouseEvent* event) override {
if (event->type() == ui::ET_MOUSE_PRESSED &&
event->button_flags() == event->changed_button_flags()) {
HandlePressEvent(event->root_location());
}
}
void OnTouchEvent(ui::TouchEvent* event) override {
if (event->type() == ui::ET_TOUCH_PRESSED) {
HandlePressEvent(event->root_location());
}
}
private:
void HandlePressEvent(const gfx::Point& root_location) {
View* handler = root_view_->GetEventHandlerForPoint(root_location);
if (handler == owner_->textfield_ || handler == owner_->arrow_) {
return;
}
owner_->CloseMenu();
}
void StopObserving() {
if (!root_view_) {
return;
}
root_view_->RemovePreTargetHandler(this);
root_view_ = nullptr;
}
raw_ptr<EditableCombobox> owner_;
raw_ptr<View> root_view_;
};
EditableCombobox::EditableCombobox()
: EditableCombobox(std::make_unique<internal::EmptyComboboxModel>()) {}
EditableCombobox::EditableCombobox(
std::unique_ptr<ui::ComboboxModel> combobox_model,
const bool filter_on_edit,
const bool show_on_empty,
const int text_context,
const int text_style,
const bool display_arrow)
: textfield_(new Textfield()),
text_context_(text_context),
text_style_(text_style),
filter_on_edit_(filter_on_edit),
show_on_empty_(show_on_empty) {
SetModel(std::move(combobox_model));
observation_.Observe(textfield_.get());
textfield_->set_controller(this);
textfield_->SetFontList(GetFontList());
AddChildView(textfield_.get());
views::FocusRing::Get(textfield_)->SetOutsetFocusRingDisabled(true);
control_elements_container_ = AddChildView(std::make_unique<BoxLayoutView>());
if (features::IsChromeRefresh2023()) {
control_elements_container_->SetInsideBorderInsets(
gfx::Insets::TLBR(kEditableComboboxControlsContainerInsets, 0,
kEditableComboboxControlsContainerInsets,
kEditableComboboxControlsContainerInsets));
}
if (display_arrow) {
arrow_ = AddControlElement(std::make_unique<Arrow>(base::BindRepeating(
&EditableCombobox::ArrowButtonPressed, base::Unretained(this))));
}
SetLayoutManager(std::make_unique<FillLayout>());
SetAccessibilityProperties(ax::mojom::Role::kComboBoxGrouping);
}
EditableCombobox::~EditableCombobox() {
CloseMenu();
textfield_->set_controller(nullptr);
}
void EditableCombobox::SetModel(std::unique_ptr<ui::ComboboxModel> model) {
CloseMenu();
menu_model_ = std::make_unique<EditableComboboxMenuModel>(
this, std::move(model), filter_on_edit_, show_on_empty_);
}
const std::u16string& EditableCombobox::GetText() const {
return textfield_->GetText();
}
void EditableCombobox::SetText(const std::u16string& text) {
textfield_->SetText(text);
// SetText does not actually notify the TextfieldController, so we call the
// handling code directly.
HandleNewContent(text);
}
std::u16string EditableCombobox::GetPlaceholderText() const {
return textfield_->GetPlaceholderText();
}
void EditableCombobox::SetPlaceholderText(const std::u16string& text) {
textfield_->SetPlaceholderText(text);
}
const gfx::FontList& EditableCombobox::GetFontList() const {
return style::GetFont(text_context_, text_style_);
}
void EditableCombobox::SelectRange(const gfx::Range& range) {
textfield_->SetSelectedRange(range);
}
void EditableCombobox::OnAccessibleNameChanged(const std::u16string& new_name) {
textfield_->SetAccessibleName(new_name);
if (arrow_) {
arrow_->SetAccessibleName(new_name);
}
}
void EditableCombobox::SetMenuDecorationStrategy(
std::unique_ptr<MenuDecorationStrategy> strategy) {
DCHECK(menu_model_);
menu_model_->SetDecorationStrategy(std::move(strategy));
}
void EditableCombobox::UpdateMenu() {
menu_model_->UpdateItemsShown();
}
void EditableCombobox::Layout() {
View::Layout();
int preferred_width = control_elements_container_->GetPreferredSize().width();
control_elements_container_->SetBounds(width() - preferred_width, 0,
preferred_width, height());
}
void EditableCombobox::GetAccessibleNodeData(ui::AXNodeData* node_data) {
View::GetAccessibleNodeData(node_data);
node_data->SetValue(GetText());
}
void EditableCombobox::RequestFocus() {
textfield_->RequestFocus();
}
bool EditableCombobox::GetNeedsNotificationWhenVisibleBoundsChange() const {
return true;
}
void EditableCombobox::OnVisibleBoundsChanged() {
CloseMenu();
}
void EditableCombobox::ContentsChanged(Textfield* sender,
const std::u16string& new_contents) {
HandleNewContent(new_contents);
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
}
bool EditableCombobox::HandleKeyEvent(Textfield* sender,
const ui::KeyEvent& key_event) {
if (key_event.type() == ui::ET_KEY_PRESSED &&
(key_event.key_code() == ui::VKEY_UP ||
key_event.key_code() == ui::VKEY_DOWN)) {
ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD);
return true;
}
return false;
}
void EditableCombobox::OnViewBlurred(View* observed_view) {
CloseMenu();
}
void EditableCombobox::OnLayoutIsAnimatingChanged(
views::AnimatingLayoutManager* source,
bool is_animating) {
dropdown_blocked_for_animation_ = is_animating;
if (dropdown_blocked_for_animation_) {
CloseMenu();
}
}
bool EditableCombobox::ShouldApplyInkDropEffects() {
return features::IsChromeRefresh2023() && arrow_ && InkDrop::Get(arrow_) &&
GetWidget();
}
void EditableCombobox::CloseMenu() {
if (ShouldApplyInkDropEffects()) {
InkDrop::Get(arrow_)->AnimateToState(InkDropState::DEACTIVATED, nullptr);
InkDrop::Get(arrow_)->GetInkDrop()->SetHovered(arrow_->IsMouseHovered());
}
menu_runner_.reset();
pre_target_handler_.reset();
}
void EditableCombobox::OnItemSelected(size_t index) {
std::u16string selected_item_text = menu_model_->GetItemTextAt(index);
textfield_->SetText(selected_item_text);
// SetText does not actually notify the TextfieldController, so we call the
// handling code directly.
HandleNewContent(selected_item_text);
NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged,
/*send_native_event=*/true);
}
void EditableCombobox::HandleNewContent(const std::u16string& new_content) {
DCHECK(GetText() == new_content);
// We notify |callback_| before updating |menu_model_|'s items shown. This
// gives the user a chance to modify the ComboboxModel beforehand if they wish
// to do so.
// We disable UpdateItemsShown while we notify the listener in case it
// modifies the ComboboxModel, then calls OnComboboxModelChanged and thus
// UpdateItemsShown. That way UpdateItemsShown doesn't do its work twice.
if (!content_changed_callback_.is_null()) {
menu_model_->DisableUpdateItemsShown();
content_changed_callback_.Run();
menu_model_->EnableUpdateItemsShown();
}
UpdateMenu();
}
void EditableCombobox::ArrowButtonPressed(const ui::Event& event) {
textfield_->RequestFocus();
if (ShouldApplyInkDropEffects()) {
InkDrop::Get(arrow_)->AnimateToState(InkDropState::ACTIVATED, nullptr);
}
if (menu_runner_ && menu_runner_->IsRunning()) {
CloseMenu();
} else {
ShowDropDownMenu(ui::GetMenuSourceTypeForEvent(event));
}
}
void EditableCombobox::ShowDropDownMenu(ui::MenuSourceType source_type) {
constexpr int kMenuBorderWidthTop = 1;
if (dropdown_blocked_for_animation_) {
return;
}
if (!menu_model_->GetItemCount()) {
CloseMenu();
return;
}
if (menu_runner_ && menu_runner_->IsRunning()) {
return;
}
if (!GetWidget()) {
return;
}
// Since we don't capture the mouse, we want to see the events that happen in
// the EditableCombobox's RootView to get a chance to close the menu if they
// happen outside |textfield_|. Events that happen over the menu belong to
// another Widget and they don't go through this pre-target handler.
// Events that happen outside both the menu and the RootView cause
// OnViewBlurred to be called, which also closes the menu.
pre_target_handler_ = std::make_unique<EditableComboboxPreTargetHandler>(
this, GetWidget()->GetRootView());
gfx::Rect local_bounds = textfield_->GetLocalBounds();
// Menu's requested position's width should be the same as local bounds so the
// border of the menu lines up with the border of the combobox. The y
// coordinate however should be shifted to the bottom with the border width
// not to overlap with the combobox border.
gfx::Point menu_position(local_bounds.origin());
menu_position.set_y(menu_position.y() + kMenuBorderWidthTop);
View::ConvertPointToScreen(this, &menu_position);
gfx::Rect bounds(menu_position, local_bounds.size());
menu_runner_ = std::make_unique<MenuRunner>(
menu_model_.get(), MenuRunner::EDITABLE_COMBOBOX,
base::BindRepeating(&EditableCombobox::CloseMenu,
base::Unretained(this)));
menu_runner_->RunMenuAt(GetWidget(), nullptr, bounds,
MenuAnchorPosition::kTopLeft, source_type);
}
void EditableCombobox::UpdateTextfieldInsets() {
textfield_->SetExtraInsets(gfx::Insets::TLBR(
0, 0, 0,
std::max(control_elements_container_->GetPreferredSize().width() -
(features::IsChromeRefresh2023()
? kComboboxArrowPaddingWidthChromeRefresh2023
: kComboboxArrowPaddingWidth),
0)));
}
const ui::MenuModel* EditableCombobox::GetMenuModelForTesting() const {
return menu_model_.get();
}
std::u16string EditableCombobox::GetItemTextForTesting(size_t index) const {
return menu_model_->GetLabelAt(index);
}
const ui::ComboboxModel* EditableCombobox::GetComboboxModel() const {
DCHECK(menu_model_);
return menu_model_->GetComboboxModel();
}
BEGIN_METADATA(EditableCombobox, View)
ADD_PROPERTY_METADATA(std::u16string, Text)
ADD_PROPERTY_METADATA(std::u16string, PlaceholderText)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_combobox.cc | C++ | unknown | 20,816 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_COMBOBOX_H_
#define UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_COMBOBOX_H_
#include <memory>
#include <string>
#include <utility>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "build/build_config.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/layout/animating_layout_manager.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/style/typography.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/views_export.h"
namespace gfx {
class FontList;
class Range;
} // namespace gfx
namespace ui {
class ComboboxModel;
class Event;
class MenuModel;
} // namespace ui
namespace views {
class Button;
class EditableComboboxMenuModel;
class EditableComboboxPreTargetHandler;
class MenuRunner;
class Textfield;
namespace test {
class InteractionTestUtilSimulatorViews;
} // namespace test
// Textfield that also shows a drop-down list with suggestions.
class VIEWS_EXPORT EditableCombobox
: public View,
public TextfieldController,
public ViewObserver,
public views::AnimatingLayoutManager::Observer {
public:
METADATA_HEADER(EditableCombobox);
// A strategy that can be used to customize the display of the drop-down menu.
// It is only intended to be used by classes that extend `EditableCombobox`.
class MenuDecorationStrategy {
public:
virtual ~MenuDecorationStrategy() = default;
virtual std::u16string DecorateItemText(std::u16string text) const;
};
static constexpr int kDefaultTextContext = style::CONTEXT_BUTTON;
static constexpr int kDefaultTextStyle = style::STYLE_PRIMARY;
EditableCombobox();
// |combobox_model|: The ComboboxModel that gives us the items to show in the
// menu.
// |filter_on_edit|: Whether to only show the items that are case-insensitive
// completions of the current textfield content.
// |show_on_empty|: Whether to show the drop-down list when there is no
// textfield content.
// |text_context| and |text_style|: Together these indicate the font to use.
// |display_arrow|: Whether to display an arrow in the combobox to indicate
// that there is a drop-down list.
explicit EditableCombobox(std::unique_ptr<ui::ComboboxModel> combobox_model,
bool filter_on_edit = false,
bool show_on_empty = true,
int text_context = kDefaultTextContext,
int text_style = kDefaultTextStyle,
bool display_arrow = true);
EditableCombobox(const EditableCombobox&) = delete;
EditableCombobox& operator=(const EditableCombobox&) = delete;
~EditableCombobox() override;
void SetModel(std::unique_ptr<ui::ComboboxModel> model);
const std::u16string& GetText() const;
void SetText(const std::u16string& text);
std::u16string GetPlaceholderText() const;
void SetPlaceholderText(const std::u16string& text);
const gfx::FontList& GetFontList() const;
void SetCallback(base::RepeatingClosure callback) {
content_changed_callback_ = std::move(callback);
}
// Selects the specified logical text range for the textfield.
void SelectRange(const gfx::Range& range);
protected:
// Sets the menu decoration strategy. Setting it triggers an update to the
// menu.
void SetMenuDecorationStrategy(
std::unique_ptr<MenuDecorationStrategy> strategy);
// Forces an update of the drop-down menu.
void UpdateMenu();
// Adds `view` to the set of controls. The ordering is such that views are
// added to the front (i.e. to the left in LTR set-ups).
template <typename T>
T* AddControlElement(std::unique_ptr<T> view) {
T* raw_view =
control_elements_container_->AddChildViewAt(std::move(view), 0);
UpdateTextfieldInsets();
return raw_view;
}
Textfield& GetTextfield() { return *textfield_; }
Button* GetArrowButtonForTesting() { return arrow_; }
private:
friend class EditableComboboxTest;
friend class EditablePasswordComboboxTest;
friend class test::InteractionTestUtilSimulatorViews;
FRIEND_TEST_ALL_PREFIXES(EditableComboboxTest, AccessibleNameAndRole);
class EditableComboboxMenuModel;
class EditableComboboxPreTargetHandler;
void CloseMenu();
// Called when an item is selected from the menu.
void OnItemSelected(size_t index);
// Notifies listener of new content and updates the menu items to show.
void HandleNewContent(const std::u16string& new_content);
// Toggles the dropdown menu in response to |event|.
void ArrowButtonPressed(const ui::Event& event);
// Shows the drop-down menu.
void ShowDropDownMenu(ui::MenuSourceType source_type = ui::MENU_SOURCE_NONE);
// Recalculates the extra insets of the textfield based on the size of the
// controls container.
void UpdateTextfieldInsets();
// These are for unit tests to get data from private implementation classes.
const ui::MenuModel* GetMenuModelForTesting() const;
std::u16string GetItemTextForTesting(size_t index) const;
// Returns the underlying combobox model. Used only by
// `ui::test::InteractionTestUtil`.
const ui::ComboboxModel* GetComboboxModel() const;
// Overridden from View:
void Layout() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void RequestFocus() override;
bool GetNeedsNotificationWhenVisibleBoundsChange() const override;
void OnVisibleBoundsChanged() override;
void OnAccessibleNameChanged(const std::u16string& new_name) override;
// Overridden from TextfieldController:
void ContentsChanged(Textfield* sender,
const std::u16string& new_contents) override;
bool HandleKeyEvent(Textfield* sender,
const ui::KeyEvent& key_event) override;
// Overridden from ViewObserver:
void OnViewBlurred(View* observed_view) override;
// Overridden from views::AnimatingLayoutManager::Observer:
void OnLayoutIsAnimatingChanged(views::AnimatingLayoutManager* source,
bool is_animating) override;
bool ShouldApplyInkDropEffects();
raw_ptr<Textfield> textfield_;
raw_ptr<BoxLayoutView> control_elements_container_ = nullptr;
raw_ptr<Button> arrow_ = nullptr;
// The EditableComboboxMenuModel used by |menu_runner_|.
std::unique_ptr<EditableComboboxMenuModel> menu_model_;
// Pre-target handler that closes the menu when press events happen in the
// root view (outside of the open menu's boundaries) but not inside the
// textfield.
std::unique_ptr<EditableComboboxPreTargetHandler> pre_target_handler_;
// Typography context for the text written in the textfield and the options
// shown in the drop-down menu.
const int text_context_;
// Typography style for the text written in the textfield and the options
// shown in the drop-down menu.
const int text_style_;
// Whether to adapt the items shown to the textfield content.
const bool filter_on_edit_;
// Whether to show options when the textfield is empty.
const bool show_on_empty_;
// Set while the drop-down is showing.
std::unique_ptr<MenuRunner> menu_runner_;
base::RepeatingClosure content_changed_callback_;
bool dropdown_blocked_for_animation_ = false;
base::ScopedObservation<View, ViewObserver> observation_{this};
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_COMBOBOX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_combobox.h | C++ | unknown | 7,792 |
// Copyright 2019 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/editable_combobox/editable_combobox.h"
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/simple_combobox_model.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/controls/combobox/combobox_util.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/button_test_api.h"
#include "ui/views/test/menu_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_utils.h"
#if BUILDFLAG(IS_OZONE)
#include "ui/events/ozone/layout/keyboard_layout_engine_test_utils.h"
#endif
namespace views {
namespace {
using base::ASCIIToUTF16;
using views::test::WaitForMenuClosureAnimation;
// No-op test double of a ContextMenuController
class TestContextMenuController : public ContextMenuController {
public:
TestContextMenuController() = default;
TestContextMenuController(const TestContextMenuController&) = delete;
TestContextMenuController& operator=(const TestContextMenuController&) =
delete;
~TestContextMenuController() override = default;
// ContextMenuController:
void ShowContextMenuForViewImpl(View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) override {
opened_menu_ = true;
}
bool opened_menu() const { return opened_menu_; }
private:
bool opened_menu_ = false;
};
} // namespace
class EditableComboboxTest : public ViewsTestBase {
public:
EditableComboboxTest() { views::test::DisableMenuClosureAnimations(); }
EditableComboboxTest(const EditableComboboxTest&) = delete;
EditableComboboxTest& operator=(const EditableComboboxTest&) = delete;
void SetUp() override;
void TearDown() override;
// Initializes the combobox with the given number of items.
void InitEditableCombobox(int item_count = 8,
bool filter_on_edit = false,
bool show_on_empty = true);
// Initializes the combobox with the given items.
void InitEditableCombobox(const std::vector<std::u16string>& items,
bool filter_on_edit,
bool show_on_empty = true);
void InitEditableCombobox(
const std::vector<ui::SimpleComboboxModel::Item>& items,
bool filter_on_edit,
bool show_on_empty = true);
// Initializes the widget where the combobox and the dummy control live.
void InitWidget();
static size_t GetItemCount(const EditableCombobox* combobox);
protected:
enum class IconSource { kMenuModel, kComboboxModel };
size_t GetItemCount() const;
std::u16string GetItemAt(size_t index) const;
ui::ImageModel GetIconAt(size_t index, IconSource source) const;
void ClickArrow();
void ClickMenuItem(int index);
void ClickTextfield();
void FocusTextfield();
bool IsTextfieldFocused() const;
std::u16string GetSelectedText() const;
void SetContextMenuController(ContextMenuController* controller);
void DragMouseTo(const gfx::Point& location);
MenuRunner* GetMenuRunner();
bool IsMenuOpen();
void PerformMouseEvent(Widget* widget,
const gfx::Point& point,
ui::EventType type);
void PerformClick(Widget* widget, const gfx::Point& point);
void SendKeyEvent(ui::KeyboardCode key_code,
bool alt = false,
bool shift = false,
bool ctrl_cmd = false);
int change_count() const { return change_count_; }
void OnContentChanged() { ++change_count_; }
// The widget where the control will appear.
raw_ptr<Widget> widget_ = nullptr;
// |combobox_| and |dummy_focusable_view_| are allocated in
// |InitEditableCombobox| and then owned by |widget_|.
raw_ptr<EditableCombobox> combobox_ = nullptr;
raw_ptr<View> dummy_focusable_view_ = nullptr;
// We make |combobox_| a child of another View to test different removal
// scenarios.
raw_ptr<View> parent_of_combobox_ = nullptr;
int change_count_ = 0;
std::unique_ptr<ui::test::EventGenerator> event_generator_;
};
void EditableComboboxTest::SetUp() {
ViewsTestBase::SetUp();
#if BUILDFLAG(IS_OZONE)
// Setting up the keyboard layout engine depends on the implementation and may
// be asynchronous. We ensure that it is ready to use so that tests could
// handle key events properly.
ui::WaitUntilLayoutEngineIsReadyForTest();
#endif
}
void EditableComboboxTest::TearDown() {
if (IsMenuOpen()) {
GetMenuRunner()->Cancel();
WaitForMenuClosureAnimation();
}
if (widget_)
widget_->Close();
ViewsTestBase::TearDown();
}
// Initializes the combobox with the given number of items.
void EditableComboboxTest::InitEditableCombobox(const int item_count,
const bool filter_on_edit,
const bool show_on_empty) {
std::vector<ui::SimpleComboboxModel::Item> items;
for (int i = 0; i < item_count; ++i)
items.emplace_back(ASCIIToUTF16(base::StringPrintf("item[%i]", i)));
InitEditableCombobox(items, filter_on_edit, show_on_empty);
}
void EditableComboboxTest::InitEditableCombobox(
const std::vector<std::u16string>& strings,
bool filter_on_edit,
bool show_on_empty) {
std::vector<ui::SimpleComboboxModel::Item> items;
for (const auto& item_str : strings)
items.emplace_back(item_str);
InitEditableCombobox(items, filter_on_edit, show_on_empty);
}
// Initializes the combobox with the given items.
void EditableComboboxTest::InitEditableCombobox(
const std::vector<ui::SimpleComboboxModel::Item>& items,
const bool filter_on_edit,
const bool show_on_empty) {
parent_of_combobox_ = new View();
parent_of_combobox_->SetID(1);
combobox_ =
new EditableCombobox(std::make_unique<ui::SimpleComboboxModel>(items),
filter_on_edit, show_on_empty);
combobox_->SetCallback(base::BindRepeating(
&EditableComboboxTest::OnContentChanged, base::Unretained(this)));
combobox_->SetID(2);
combobox_->SetAccessibleName(u"abc");
dummy_focusable_view_ = new View();
dummy_focusable_view_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
dummy_focusable_view_->SetID(3);
InitWidget();
}
// Initializes the widget where the combobox and the dummy control live.
void EditableComboboxTest::InitWidget() {
widget_ = new Widget();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(0, 0, 1000, 1000);
parent_of_combobox_->SetBoundsRect(gfx::Rect(0, 0, 500, 40));
combobox_->SetBoundsRect(gfx::Rect(0, 0, 500, 40));
widget_->Init(std::move(params));
View* container = widget_->SetContentsView(std::make_unique<View>());
container->AddChildView(parent_of_combobox_.get());
parent_of_combobox_->AddChildView(combobox_.get());
container->AddChildView(dummy_focusable_view_.get());
widget_->Show();
#if BUILDFLAG(IS_MAC)
// The event loop needs to be flushed here, otherwise in various tests:
// 1. The actual showing of the native window backing the widget gets delayed
// until a spin of the event loop.
// 2. The combobox menu object is triggered, and it starts listening for the
// "window did become key" notification as a sign that it lost focus and
// should close.
// 3. The event loop is spun, and the actual showing of the native window
// triggers the close of the menu opened from within the window.
base::RunLoop().RunUntilIdle();
#endif
event_generator_ =
std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_));
event_generator_->set_target(ui::test::EventGenerator::Target::WINDOW);
}
// static
size_t EditableComboboxTest::GetItemCount(const EditableCombobox* combobox) {
return combobox->GetMenuModelForTesting()->GetItemCount();
}
size_t EditableComboboxTest::GetItemCount() const {
return GetItemCount(combobox_);
}
std::u16string EditableComboboxTest::GetItemAt(size_t index) const {
return combobox_->GetItemTextForTesting(index);
}
ui::ImageModel EditableComboboxTest::GetIconAt(size_t index,
IconSource icon_source) const {
switch (icon_source) {
case IconSource::kMenuModel:
return combobox_->GetMenuModelForTesting()->GetIconAt(index);
case IconSource::kComboboxModel:
return combobox_->GetMenuModelForTesting()->GetIconAt(index);
}
}
void EditableComboboxTest::ClickArrow() {
ui::MouseEvent e(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
views::test::ButtonTestApi test_api(combobox_->GetArrowButtonForTesting());
test_api.NotifyClick(e);
}
void EditableComboboxTest::FocusTextfield() {
combobox_->textfield_->RequestFocus();
}
bool EditableComboboxTest::IsTextfieldFocused() const {
return combobox_->textfield_->HasFocus();
}
std::u16string EditableComboboxTest::GetSelectedText() const {
return combobox_->textfield_->GetSelectedText();
}
void EditableComboboxTest::SetContextMenuController(
ContextMenuController* controller) {
combobox_->textfield_->set_context_menu_controller(controller);
}
void EditableComboboxTest::ClickTextfield() {
const gfx::Point textfield(combobox_->x() + 1, combobox_->y() + 1);
PerformClick(widget_, textfield);
}
void EditableComboboxTest::DragMouseTo(const gfx::Point& location) {
ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
combobox_->textfield_->OnMouseDragged(drag);
}
MenuRunner* EditableComboboxTest::GetMenuRunner() {
return combobox_->menu_runner_.get();
}
bool EditableComboboxTest::IsMenuOpen() {
return combobox_ && GetMenuRunner() && GetMenuRunner()->IsRunning();
}
void EditableComboboxTest::PerformMouseEvent(Widget* widget,
const gfx::Point& point,
const ui::EventType type) {
ui::MouseEvent event = ui::MouseEvent(
type, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_NUM_LOCK_ON, ui::EF_LEFT_MOUSE_BUTTON);
widget->OnMouseEvent(&event);
}
void EditableComboboxTest::PerformClick(Widget* widget,
const gfx::Point& point) {
PerformMouseEvent(widget, point, ui::ET_MOUSE_PRESSED);
PerformMouseEvent(widget, point, ui::ET_MOUSE_RELEASED);
}
void EditableComboboxTest::SendKeyEvent(ui::KeyboardCode key_code,
const bool alt,
const bool shift,
const bool ctrl_cmd) {
#if BUILDFLAG(IS_MAC)
bool command = ctrl_cmd;
bool control = false;
#else
bool command = false;
bool control = ctrl_cmd;
#endif
int flags = (shift ? ui::EF_SHIFT_DOWN : 0) |
(control ? ui::EF_CONTROL_DOWN : 0) |
(alt ? ui::EF_ALT_DOWN : 0) | (command ? ui::EF_COMMAND_DOWN : 0);
event_generator_->PressKey(key_code, flags);
}
TEST_F(EditableComboboxTest, FocusOnTextfieldDoesntOpenMenu) {
InitEditableCombobox();
EXPECT_FALSE(IsMenuOpen());
FocusTextfield();
EXPECT_FALSE(IsMenuOpen());
}
TEST_F(EditableComboboxTest, ArrowDownOpensMenu) {
InitEditableCombobox();
EXPECT_FALSE(IsMenuOpen());
FocusTextfield();
SendKeyEvent(ui::VKEY_DOWN);
EXPECT_TRUE(IsMenuOpen());
}
TEST_F(EditableComboboxTest, TabMovesToOtherViewAndClosesMenu) {
InitEditableCombobox();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
EXPECT_TRUE(IsTextfieldFocused());
SendKeyEvent(ui::VKEY_TAB);
EXPECT_FALSE(IsTextfieldFocused());
// In Chrome Refresh the drop down arrow will behave more like a normal button
// and therefore will be focusable.
if (!features::IsChromeRefresh2023()) {
EXPECT_TRUE(dummy_focusable_view_->HasFocus());
}
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
}
TEST_F(EditableComboboxTest,
ClickOutsideEditableComboboxWithoutLosingFocusClosesMenu) {
InitEditableCombobox();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
EXPECT_TRUE(IsTextfieldFocused());
const gfx::Point outside_point(combobox_->x() + combobox_->width() + 1,
combobox_->y() + 1);
PerformClick(widget_, outside_point);
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
EXPECT_TRUE(IsTextfieldFocused());
}
TEST_F(EditableComboboxTest, ClickTextfieldDoesntCloseMenu) {
InitEditableCombobox();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
MenuRunner* menu_runner1 = GetMenuRunner();
ClickTextfield();
MenuRunner* menu_runner2 = GetMenuRunner();
EXPECT_TRUE(IsMenuOpen());
// Making sure the menu didn't close and reopen (causing a flicker).
EXPECT_EQ(menu_runner1, menu_runner2);
}
TEST_F(EditableComboboxTest, RemovingControlWhileMenuOpenClosesMenu) {
InitEditableCombobox();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
auto combobox = parent_of_combobox_->RemoveChildViewT(combobox_);
EXPECT_EQ(nullptr, GetMenuRunner());
combobox_ = nullptr;
}
TEST_F(EditableComboboxTest, RemovingParentOfControlWhileMenuOpenClosesMenu) {
InitEditableCombobox();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
auto parent =
widget_->GetContentsView()->RemoveChildViewT(parent_of_combobox_);
EXPECT_EQ(nullptr, GetMenuRunner());
combobox_ = nullptr;
parent_of_combobox_ = nullptr;
}
TEST_F(EditableComboboxTest, LeftOrRightKeysMoveInTextfield) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_E);
SendKeyEvent(ui::VKEY_LEFT);
SendKeyEvent(ui::VKEY_LEFT);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_RIGHT);
SendKeyEvent(ui::VKEY_D);
EXPECT_EQ(u"abcde", combobox_->GetText());
}
#if BUILDFLAG(IS_WIN)
// Flaky on Windows. https://crbug.com/965601
#define MAYBE_UpOrDownKeysMoveInMenu DISABLED_UpOrDownKeysMoveInMenu
#else
#define MAYBE_UpOrDownKeysMoveInMenu UpOrDownKeysMoveInMenu
#endif
TEST_F(EditableComboboxTest, MAYBE_UpOrDownKeysMoveInMenu) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_UP);
SendKeyEvent(ui::VKEY_RETURN);
WaitForMenuClosureAnimation();
EXPECT_EQ(u"item[1]", combobox_->GetText());
}
TEST_F(EditableComboboxTest, EndOrHomeMovesToBeginningOrEndOfText) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_HOME);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_END);
SendKeyEvent(ui::VKEY_Y);
EXPECT_EQ(u"xabcy", combobox_->GetText());
}
#if BUILDFLAG(IS_MAC)
TEST_F(EditableComboboxTest, AltLeftOrRightMovesToNextWords) {
InitEditableCombobox();
FocusTextfield();
combobox_->SetText(u"foo bar foobar");
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/true, /*shift=*/false,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/true, /*shift=*/false,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_RIGHT, /*alt=*/true, /*shift=*/false,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_Y);
EXPECT_EQ(u"foo xbary foobar", combobox_->GetText());
}
TEST_F(EditableComboboxTest, CtrlLeftOrRightMovesToBeginningOrEndOfText) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/false, /*shift=*/false,
/*ctrl_cmd=*/true);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_RIGHT, /*alt=*/false, /*shift=*/false,
/*ctrl_cmd=*/true);
SendKeyEvent(ui::VKEY_Y);
EXPECT_EQ(u"xabcy", combobox_->GetText());
}
#else
TEST_F(EditableComboboxTest, AltLeftOrRightDoesNothing) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/true, /*shift=*/false,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_LEFT);
SendKeyEvent(ui::VKEY_RIGHT, /*alt=*/true, /*shift=*/false,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_Y);
EXPECT_EQ(u"abcyx", combobox_->GetText());
}
TEST_F(EditableComboboxTest, CtrlLeftOrRightMovesToNextWords) {
InitEditableCombobox();
FocusTextfield();
combobox_->SetText(u"foo bar foobar");
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/false, /*shift=*/false,
/*ctrl_cmd=*/true);
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/false, /*shift=*/false,
/*ctrl_cmd=*/true);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_RIGHT, /*alt=*/false, /*shift=*/false,
/*ctrl_cmd=*/true);
SendKeyEvent(ui::VKEY_Y);
#if BUILDFLAG(IS_WIN)
// Matches Windows-specific logic in
// RenderTextHarfBuzz::AdjacentWordSelectionModel.
EXPECT_EQ(u"foo xbar yfoobar", combobox_->GetText());
#else
EXPECT_EQ(u"foo xbary foobar", combobox_->GetText());
#endif
}
#endif
TEST_F(EditableComboboxTest, ShiftLeftOrRightSelectsCharInTextfield) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_LEFT, /*alt=*/false, /*shift=*/true,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_X);
SendKeyEvent(ui::VKEY_LEFT);
SendKeyEvent(ui::VKEY_LEFT);
SendKeyEvent(ui::VKEY_RIGHT, /*alt=*/false, /*shift=*/true,
/*ctrl_cmd=*/false);
SendKeyEvent(ui::VKEY_Y);
EXPECT_EQ(u"ayx", combobox_->GetText());
}
TEST_F(EditableComboboxTest, EnterClosesMenuWhileSelectingHighlightedMenuItem) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_DOWN);
EXPECT_TRUE(IsMenuOpen());
SendKeyEvent(ui::VKEY_RETURN);
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
EXPECT_EQ(u"item[0]", combobox_->GetText());
}
#if BUILDFLAG(IS_WIN)
// Flaky on Windows. https://crbug.com/965601
#define MAYBE_F4ClosesMenuWhileSelectingHighlightedMenuItem \
DISABLED_F4ClosesMenuWhileSelectingHighlightedMenuItem
#else
#define MAYBE_F4ClosesMenuWhileSelectingHighlightedMenuItem \
F4ClosesMenuWhileSelectingHighlightedMenuItem
#endif
TEST_F(EditableComboboxTest,
MAYBE_F4ClosesMenuWhileSelectingHighlightedMenuItem) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_DOWN);
EXPECT_TRUE(IsMenuOpen());
SendKeyEvent(ui::VKEY_F4);
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
EXPECT_EQ(u"item[0]", combobox_->GetText());
}
TEST_F(EditableComboboxTest, EscClosesMenuWithoutSelectingHighlightedMenuItem) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_DOWN);
EXPECT_TRUE(IsMenuOpen());
SendKeyEvent(ui::VKEY_ESCAPE);
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
EXPECT_EQ(u"a", combobox_->GetText());
}
TEST_F(EditableComboboxTest, TypingInTextfieldUnhighlightsMenuItem) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_B);
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_C);
SendKeyEvent(ui::VKEY_RETURN);
EXPECT_EQ(u"abc", combobox_->GetText());
}
// This is different from the regular read-only Combobox, where SPACE
// opens/closes the menu.
TEST_F(EditableComboboxTest, SpaceIsReflectedInTextfield) {
InitEditableCombobox();
FocusTextfield();
SendKeyEvent(ui::VKEY_A);
SendKeyEvent(ui::VKEY_SPACE);
SendKeyEvent(ui::VKEY_SPACE);
SendKeyEvent(ui::VKEY_B);
EXPECT_EQ(u"a b", combobox_->GetText());
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
// Flaky on Windows and Linux. https://crbug.com/965601
#define MAYBE_MenuCanAdaptToContentChange DISABLED_MenuCanAdaptToContentChange
#else
#define MAYBE_MenuCanAdaptToContentChange MenuCanAdaptToContentChange
#endif
// We test that the menu can adapt to content change by using an
// EditableCombobox with |filter_on_edit| set to true, which will change the
// menu's content as the user types.
TEST_F(EditableComboboxTest, MAYBE_MenuCanAdaptToContentChange) {
std::vector<std::u16string> items = {u"abc", u"abd", u"bac", u"bad"};
InitEditableCombobox(items, /*filter_on_edit=*/true);
ClickArrow();
ASSERT_TRUE(IsMenuOpen());
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_RETURN);
WaitForMenuClosureAnimation();
EXPECT_EQ(u"abc", combobox_->GetText());
SendKeyEvent(ui::VKEY_BACK);
SendKeyEvent(ui::VKEY_BACK);
SendKeyEvent(ui::VKEY_BACK);
MenuRunner* menu_runner1 = GetMenuRunner();
SendKeyEvent(ui::VKEY_B);
MenuRunner* menu_runner2 = GetMenuRunner();
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_RETURN);
WaitForMenuClosureAnimation();
EXPECT_EQ(u"bac", combobox_->GetText());
// Even though the items shown change, the menu runner shouldn't have been
// reset, otherwise there could be a flicker when the menu closes and reopens.
EXPECT_EQ(menu_runner1, menu_runner2);
}
#if BUILDFLAG(IS_LINUX)
// Flaky on Linux. https://crbug.com/1204584
#define MAYBE_RefocusingReopensMenuBasedOnLatestContent \
DISABLED_RefocusingReopensMenuBasedOnLatestContent
#else
#define MAYBE_RefocusingReopensMenuBasedOnLatestContent \
RefocusingReopensMenuBasedOnLatestContent
#endif
TEST_F(EditableComboboxTest, MAYBE_RefocusingReopensMenuBasedOnLatestContent) {
std::vector<std::u16string> items = {u"abc", u"abd", u"bac", u"bad", u"bac2"};
InitEditableCombobox(items, /*filter_on_edit=*/true);
FocusTextfield();
SendKeyEvent(ui::VKEY_B);
ASSERT_EQ(3u, GetItemCount());
SendKeyEvent(ui::VKEY_DOWN);
SendKeyEvent(ui::VKEY_RETURN);
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
EXPECT_EQ(u"bac", combobox_->GetText());
// Blur then focus to make the menu reopen. It should only show completions of
// "bac", the selected item, instead of showing completions of "b", what we
// had typed.
dummy_focusable_view_->RequestFocus();
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
ASSERT_EQ(2u, GetItemCount());
}
TEST_F(EditableComboboxTest, GetItemsWithoutFiltering) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/false, /*show_on_empty=*/true);
combobox_->SetText(u"z");
ASSERT_EQ(2u, GetItemCount());
ASSERT_EQ(u"item0", GetItemAt(0));
ASSERT_EQ(u"item1", GetItemAt(1));
}
TEST_F(EditableComboboxTest, FilteringEffectOnGetItems) {
std::vector<std::u16string> items = {u"abc", u"abd", u"bac", u"bad"};
InitEditableCombobox(items, /*filter_on_edit=*/true, /*show_on_empty=*/true);
ASSERT_EQ(4u, GetItemCount());
ASSERT_EQ(u"abc", GetItemAt(0));
ASSERT_EQ(u"abd", GetItemAt(1));
ASSERT_EQ(u"bac", GetItemAt(2));
ASSERT_EQ(u"bad", GetItemAt(3));
combobox_->SetText(u"b");
ASSERT_EQ(2u, GetItemCount());
ASSERT_EQ(u"bac", GetItemAt(0));
ASSERT_EQ(u"bad", GetItemAt(1));
combobox_->SetText(u"bc");
ASSERT_EQ(0u, GetItemCount());
combobox_->SetText(std::u16string());
ASSERT_EQ(4u, GetItemCount());
ASSERT_EQ(u"abc", GetItemAt(0));
ASSERT_EQ(u"abd", GetItemAt(1));
ASSERT_EQ(u"bac", GetItemAt(2));
ASSERT_EQ(u"bad", GetItemAt(3));
}
TEST_F(EditableComboboxTest, FilteringEffectOnIcons) {
ui::SimpleComboboxModel::Item item1(
u"abc", std::u16string(),
ui::ImageModel::FromImage(gfx::test::CreateImage(16, 16)));
ui::SimpleComboboxModel::Item item2(
u"def", std::u16string(),
ui::ImageModel::FromImage(gfx::test::CreateImage(20, 20)));
InitEditableCombobox({item1, item2},
/*filter_on_edit=*/true,
/*show_on_empty=*/true);
ASSERT_EQ(2u, GetItemCount());
EXPECT_EQ(16, GetIconAt(0, IconSource::kComboboxModel).Size().width());
EXPECT_EQ(20, GetIconAt(1, IconSource::kComboboxModel).Size().width());
combobox_->SetText(u"a");
ASSERT_EQ(1u, GetItemCount());
EXPECT_EQ(16, GetIconAt(0, IconSource::kMenuModel).Size().width());
combobox_->SetText(u"d");
ASSERT_EQ(1u, GetItemCount());
EXPECT_EQ(20, GetIconAt(0, IconSource::kMenuModel).Size().width());
}
TEST_F(EditableComboboxTest, FilteringWithMismatchedCase) {
std::vector<std::u16string> items = {u"AbCd", u"aBcD", u"xyz"};
InitEditableCombobox(items, /*filter_on_edit=*/true, /*show_on_empty=*/true);
ASSERT_EQ(3u, GetItemCount());
ASSERT_EQ(u"AbCd", GetItemAt(0));
ASSERT_EQ(u"aBcD", GetItemAt(1));
ASSERT_EQ(u"xyz", GetItemAt(2));
combobox_->SetText(u"abcd");
ASSERT_EQ(2u, GetItemCount());
ASSERT_EQ(u"AbCd", GetItemAt(0));
ASSERT_EQ(u"aBcD", GetItemAt(1));
combobox_->SetText(u"ABCD");
ASSERT_EQ(2u, GetItemCount());
ASSERT_EQ(u"AbCd", GetItemAt(0));
ASSERT_EQ(u"aBcD", GetItemAt(1));
}
TEST_F(EditableComboboxTest, DontShowOnEmpty) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/false,
/*show_on_empty=*/false);
ASSERT_EQ(0u, GetItemCount());
combobox_->SetText(u"a");
ASSERT_EQ(2u, GetItemCount());
ASSERT_EQ(u"item0", GetItemAt(0));
ASSERT_EQ(u"item1", GetItemAt(1));
}
TEST_F(EditableComboboxTest, NoFilteringNotifiesCallback) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/false, /*show_on_empty=*/true);
ASSERT_EQ(0, change_count());
combobox_->SetText(u"a");
ASSERT_EQ(1, change_count());
combobox_->SetText(u"ab");
ASSERT_EQ(2, change_count());
}
TEST_F(EditableComboboxTest, FilteringNotifiesCallback) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/true, /*show_on_empty=*/true);
ASSERT_EQ(0, change_count());
combobox_->SetText(u"i");
ASSERT_EQ(1, change_count());
combobox_->SetText(u"ix");
ASSERT_EQ(2, change_count());
combobox_->SetText(u"ixy");
ASSERT_EQ(3, change_count());
}
TEST_F(EditableComboboxTest, ArrowButtonOpensAndClosesMenu) {
InitEditableCombobox();
dummy_focusable_view_->RequestFocus();
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
ClickArrow();
EXPECT_TRUE(IsMenuOpen());
ClickArrow();
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
}
TEST_F(EditableComboboxTest, ShowContextMenuOnMouseRelease) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/false,
/*show_on_empty=*/true);
EXPECT_FALSE(IsMenuOpen());
TestContextMenuController context_menu_controller;
SetContextMenuController(&context_menu_controller);
const gfx::Point textfield_point(combobox_->x() + 1, combobox_->y() + 1);
ui::MouseEvent click_mouse_event(ui::ET_MOUSE_PRESSED, textfield_point,
textfield_point, ui::EventTimeForNow(),
ui::EF_RIGHT_MOUSE_BUTTON,
ui::EF_RIGHT_MOUSE_BUTTON);
widget_->OnMouseEvent(&click_mouse_event);
EXPECT_FALSE(IsMenuOpen());
ui::MouseEvent release_mouse_event(ui::ET_MOUSE_RELEASED, textfield_point,
textfield_point, ui::EventTimeForNow(),
ui::EF_RIGHT_MOUSE_BUTTON,
ui::EF_RIGHT_MOUSE_BUTTON);
widget_->OnMouseEvent(&release_mouse_event);
// The context menu should appear, not the combobox dropdown.
EXPECT_FALSE(IsMenuOpen());
EXPECT_TRUE(context_menu_controller.opened_menu());
}
TEST_F(EditableComboboxTest, DragToSelectDoesntOpenTheMenu) {
std::vector<std::u16string> items = {u"item0", u"item1"};
InitEditableCombobox(items, /*filter_on_edit=*/false,
/*show_on_empty=*/true);
combobox_->SetText(u"abc");
dummy_focusable_view_->RequestFocus();
WaitForMenuClosureAnimation();
EXPECT_FALSE(IsMenuOpen());
const int kCursorXStart = 0;
const int kCursorXEnd = combobox_->x() + combobox_->width();
const int kCursorY = combobox_->y() + 1;
gfx::Point start_point(kCursorXStart, kCursorY);
gfx::Point end_point(kCursorXEnd, kCursorY);
PerformMouseEvent(widget_, start_point, ui::ET_MOUSE_PRESSED);
EXPECT_TRUE(GetSelectedText().empty());
DragMouseTo(end_point);
ASSERT_EQ(u"abc", GetSelectedText());
EXPECT_FALSE(IsMenuOpen());
PerformMouseEvent(widget_, end_point, ui::ET_MOUSE_RELEASED);
ASSERT_EQ(u"abc", GetSelectedText());
EXPECT_FALSE(IsMenuOpen());
}
TEST_F(EditableComboboxTest, AccessibleNameAndRole) {
InitEditableCombobox();
ui::AXNodeData data;
combobox_->GetAccessibleNodeData(&data);
EXPECT_EQ(data.role, ax::mojom::Role::kComboBoxGrouping);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"abc");
EXPECT_EQ(combobox_->GetAccessibleName(), u"abc");
data = ui::AXNodeData();
combobox_->SetAccessibleName(u"New name");
combobox_->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"New name");
EXPECT_EQ(combobox_->GetAccessibleName(), u"New name");
}
using EditableComboboxDefaultTest = ViewsTestBase;
class ConfigurableComboboxModel final : public ui::ComboboxModel {
public:
explicit ConfigurableComboboxModel(bool* destroyed = nullptr)
: destroyed_(destroyed) {
if (destroyed_)
*destroyed_ = false;
}
ConfigurableComboboxModel(ConfigurableComboboxModel&) = delete;
ConfigurableComboboxModel& operator=(const ConfigurableComboboxModel&) =
delete;
~ConfigurableComboboxModel() override {
if (destroyed_)
*destroyed_ = true;
}
// ui::ComboboxModel:
size_t GetItemCount() const override { return item_count_; }
std::u16string GetItemAt(size_t index) const override {
DCHECK_LT(index, item_count_);
return base::NumberToString16(index);
}
void SetItemCount(size_t item_count) { item_count_ = item_count; }
private:
const raw_ptr<bool> destroyed_;
size_t item_count_ = 0;
};
TEST_F(EditableComboboxDefaultTest, Default) {
auto combobox = std::make_unique<EditableCombobox>();
EXPECT_EQ(0u, EditableComboboxTest::GetItemCount(combobox.get()));
}
TEST_F(EditableComboboxDefaultTest, SetModel) {
std::unique_ptr<ConfigurableComboboxModel> model =
std::make_unique<ConfigurableComboboxModel>();
model->SetItemCount(42);
auto combobox = std::make_unique<EditableCombobox>();
combobox->SetModel(std::move(model));
EXPECT_EQ(42u, EditableComboboxTest::GetItemCount(combobox.get()));
}
TEST_F(EditableComboboxDefaultTest, SetModelOverwrite) {
bool destroyed_first = false;
bool destroyed_second = false;
{
auto combobox = std::make_unique<EditableCombobox>();
combobox->SetModel(
std::make_unique<ConfigurableComboboxModel>(&destroyed_first));
ASSERT_FALSE(destroyed_first);
combobox->SetModel(
std::make_unique<ConfigurableComboboxModel>(&destroyed_second));
EXPECT_TRUE(destroyed_first);
ASSERT_FALSE(destroyed_second);
}
EXPECT_TRUE(destroyed_second);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_combobox_unittest.cc | C++ | unknown | 32,206 |
// 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 "ui/views/controls/editable_combobox/editable_password_combobox.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/combobox_model.h"
#include "ui/gfx/render_text.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/image_button_factory.h"
#include "ui/views/controls/combobox/combobox_util.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/vector_icons.h"
namespace views {
namespace {
constexpr int kEyePaddingWidth = 4;
// Creates the eye-styled icon that serves as a button to toggle the password
// visibility.
std::unique_ptr<ToggleImageButton> CreateEye(
ImageButton::PressedCallback callback) {
auto button = Builder<ToggleImageButton>()
.SetInstallFocusRingOnFocus(true)
.SetRequestFocusOnPress(true)
.SetImageVerticalAlignment(ImageButton::ALIGN_MIDDLE)
.SetImageHorizontalAlignment(ImageButton::ALIGN_CENTER)
.SetCallback(std::move(callback))
.SetBorder(CreateEmptyBorder(kEyePaddingWidth))
.Build();
SetImageFromVectorIconWithColorId(button.get(), kEyeIcon, ui::kColorIcon,
ui::kColorIconDisabled);
SetToggledImageFromVectorIconWithColorId(
button.get(), kEyeCrossedIcon, ui::kColorIcon, ui::kColorIconDisabled);
ConfigureComboboxButtonInkDrop(button.get());
return button;
}
class PasswordMenuDecorationStrategy
: public EditableCombobox::MenuDecorationStrategy {
public:
explicit PasswordMenuDecorationStrategy(
const EditablePasswordCombobox* parent)
: parent_(parent) {
DCHECK(parent);
}
std::u16string DecorateItemText(std::u16string text) const override {
return parent_->ArePasswordsRevealed()
? text
: std::u16string(text.length(),
gfx::RenderText::kPasswordReplacementChar);
}
private:
const raw_ptr<const EditablePasswordCombobox> parent_;
};
} // namespace
EditablePasswordCombobox::EditablePasswordCombobox() = default;
EditablePasswordCombobox::EditablePasswordCombobox(
std::unique_ptr<ui::ComboboxModel> combobox_model,
int text_context,
int text_style,
bool display_arrow,
Button::PressedCallback eye_callback)
: EditableCombobox(std::move(combobox_model),
/*filter_on_edit=*/false,
/*show_on_empty=*/true,
text_context,
text_style,
display_arrow) {
// If there is no arrow for a dropdown element, then the eye is too close to
// the border of the textarea - therefore add additional padding.
std::unique_ptr<ToggleImageButton> eye = CreateEye(std::move(eye_callback));
eye_ = eye.get();
if (!display_arrow) {
// Add the insets to an additional container instead of directly to the
// button's border so that the focus ring around the pressed button is not
// affected by this additional padding.
auto container =
Builder<BoxLayoutView>()
.SetInsideBorderInsets(gfx::Insets().set_right(
std::max(0, LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING) -
kEyePaddingWidth)))
.Build();
container->AddChildView(std::move(eye));
AddControlElement(std::move(container));
} else {
AddControlElement(std::move(eye));
}
GetTextfield().SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
SetMenuDecorationStrategy(
std::make_unique<PasswordMenuDecorationStrategy>(this));
}
EditablePasswordCombobox::~EditablePasswordCombobox() = default;
void EditablePasswordCombobox::SetPasswordIconTooltips(
const std::u16string& tooltip_text,
const std::u16string& toggled_tooltip_text) {
eye_->SetTooltipText(tooltip_text);
eye_->SetToggledTooltipText(toggled_tooltip_text);
}
void EditablePasswordCombobox::RevealPasswords(bool revealed) {
if (revealed == are_passwords_revealed_) {
return;
}
are_passwords_revealed_ = revealed;
GetTextfield().SetTextInputType(revealed ? ui::TEXT_INPUT_TYPE_TEXT
: ui::TEXT_INPUT_TYPE_PASSWORD);
eye_->SetToggled(revealed);
UpdateMenu();
}
bool EditablePasswordCombobox::ArePasswordsRevealed() const {
return are_passwords_revealed_;
}
BEGIN_METADATA(EditablePasswordCombobox, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_password_combobox.cc | C++ | unknown | 5,181 |
// 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.
#ifndef UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_PASSWORD_COMBOBOX_H_
#define UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_PASSWORD_COMBOBOX_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
namespace views {
class ToggleImageButton;
// Textfield that also shows a drop-down list with suggestions and can switch
// between visible and obfuscated text.
class VIEWS_EXPORT EditablePasswordCombobox : public EditableCombobox {
public:
METADATA_HEADER(EditablePasswordCombobox);
static constexpr int kDefaultTextContext = style::CONTEXT_BUTTON;
static constexpr int kDefaultTextStyle = style::STYLE_PRIMARY;
EditablePasswordCombobox();
// `combobox_model`: The ComboboxModel that gives us the items to show in the
// menu.
// `text_context` and `text_style`: Together these indicate the font to use.
// `display_arrow`: Whether to display an arrow in the combobox to indicate
// that there is a drop-down list. `eye_callback` is called when the eye icon
// is clicked.
explicit EditablePasswordCombobox(
std::unique_ptr<ui::ComboboxModel> combobox_model,
int text_context = kDefaultTextContext,
int text_style = kDefaultTextStyle,
bool display_arrow = true,
Button::PressedCallback eye_callback = Button::PressedCallback());
EditablePasswordCombobox(const EditablePasswordCombobox&) = delete;
EditablePasswordCombobox& operator=(const EditablePasswordCombobox&) = delete;
~EditablePasswordCombobox() override;
// Sets the tooltips for the password eye icon.
void SetPasswordIconTooltips(const std::u16string& tooltip_text,
const std::u16string& toggled_tooltip_text);
// Sets and gets whether the textfield and drop-down menu reveal their current
// content.
void RevealPasswords(bool revealed);
bool ArePasswordsRevealed() const;
private:
friend class EditablePasswordComboboxTest;
// Toggles the password visibility. If the password is currently unrevealed,
// a `PasswordRevealCheck` is set and returns false, then the password remains
// unrevealed.
void RequestTogglePasswordVisibility();
ToggleImageButton* GetEyeButtonForTesting() { return eye_.get(); }
raw_ptr<ToggleImageButton> eye_ = nullptr;
// Indicates whether the passwords are currently revealed.
bool are_passwords_revealed_ = false;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_EDITABLE_COMBOBOX_EDITABLE_PASSWORD_COMBOBOX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_password_combobox.h | C++ | unknown | 2,773 |
// 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 "ui/views/controls/editable_combobox/editable_password_combobox.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_piece.h"
#include "base/test/mock_callback.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/models/simple_combobox_model.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/render_text.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_utils.h"
namespace views {
using ::testing::Return;
using ::testing::StrictMock;
class EditablePasswordComboboxTest : public ViewsTestBase {
public:
EditablePasswordComboboxTest() = default;
EditablePasswordComboboxTest(const EditablePasswordComboboxTest&) = delete;
EditablePasswordComboboxTest& operator=(const EditablePasswordComboboxTest&) =
delete;
// Initializes the combobox and the widget containing it.
void SetUp() override;
void TearDown() override;
protected:
size_t GetItemCount() const {
return combobox_->GetMenuModelForTesting()->GetItemCount();
}
std::u16string GetItemAt(size_t index) const {
return combobox_->GetItemTextForTesting(index);
}
// Clicks the eye button to reveal or obscure the password.
void ClickEye() {
ToggleImageButton* eye = combobox_->GetEyeButtonForTesting();
generator_->MoveMouseTo(eye->GetBoundsInScreen().CenterPoint());
generator_->ClickLeftButton();
}
EditablePasswordCombobox* combobox() { return combobox_.get(); }
base::MockCallback<Button::PressedCallback::Callback>* eye_mock_callback() {
return &eye_callback_;
}
private:
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<EditablePasswordCombobox> combobox_ = nullptr;
base::MockCallback<Button::PressedCallback::Callback> eye_callback_;
// Used for simulating eye button clicks.
std::unique_ptr<ui::test::EventGenerator> generator_;
};
// Initializes the combobox with the given items.
void EditablePasswordComboboxTest::SetUp() {
ViewsTestBase::SetUp();
auto combobox = std::make_unique<EditablePasswordCombobox>(
std::make_unique<ui::SimpleComboboxModel>(
std::vector<ui::SimpleComboboxModel::Item>{
ui::SimpleComboboxModel::Item(u"item0"),
ui::SimpleComboboxModel::Item(u"item1")}),
style::CONTEXT_BUTTON, style::STYLE_PRIMARY, /* display_arrow=*/true,
Button::PressedCallback(eye_callback_.Get()));
// Set dummy tooltips and name to avoid running into a11y-related DCHECKs.
combobox->SetPasswordIconTooltips(u"Show password", u"Hide password");
combobox->SetAccessibleName(u"Password field");
widget_ = new Widget();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(0, 0, 1000, 1000);
combobox->SetBoundsRect(gfx::Rect(0, 0, 500, 40));
widget_->Init(std::move(params));
View* container = widget_->SetContentsView(std::make_unique<View>());
combobox_ = container->AddChildView(std::move(combobox));
generator_ =
std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_));
widget_->Show();
#if BUILDFLAG(IS_MAC)
// The event loop needs to be flushed here, otherwise in various tests:
// 1. The actual showing of the native window backing the widget gets delayed
// until a spin of the event loop.
// 2. The combobox menu object is triggered, and it starts listening for the
// "window did become key" notification as a sign that it lost focus and
// should close.
// 3. The event loop is spun, and the actual showing of the native window
// triggers the close of the menu opened from within the window.
base::RunLoop().RunUntilIdle();
#endif
}
void EditablePasswordComboboxTest::TearDown() {
generator_.reset();
if (widget_) {
widget_->Close();
}
ViewsTestBase::TearDown();
}
TEST_F(EditablePasswordComboboxTest, PasswordCanBeHiddenAndRevealed) {
const std::u16string kObscuredPassword(
5, gfx::RenderText::kPasswordReplacementChar);
ASSERT_EQ(2u, GetItemCount());
EXPECT_FALSE(combobox()->ArePasswordsRevealed());
EXPECT_EQ(kObscuredPassword, GetItemAt(0));
EXPECT_EQ(kObscuredPassword, GetItemAt(1));
combobox()->RevealPasswords(/*revealed=*/true);
EXPECT_TRUE(combobox()->ArePasswordsRevealed());
EXPECT_EQ(u"item0", GetItemAt(0));
EXPECT_EQ(u"item1", GetItemAt(1));
combobox()->RevealPasswords(/*revealed=*/false);
EXPECT_FALSE(combobox()->ArePasswordsRevealed());
EXPECT_EQ(kObscuredPassword, GetItemAt(0));
EXPECT_EQ(kObscuredPassword, GetItemAt(1));
}
TEST_F(EditablePasswordComboboxTest, EyeButtonClickInvokesCallback) {
EXPECT_CALL(*eye_mock_callback(), Run);
ClickEye();
}
TEST_F(EditablePasswordComboboxTest, NoCrashWithoutWidget) {
auto combobox = std::make_unique<EditablePasswordCombobox>(
std::make_unique<ui::SimpleComboboxModel>(
std::vector<ui::SimpleComboboxModel::Item>{
ui::SimpleComboboxModel::Item(u"item0"),
ui::SimpleComboboxModel::Item(u"item1")}));
// Showing the dropdown should silently fail.
combobox->RevealPasswords(true);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/editable_combobox/editable_password_combobox_unittest.cc | C++ | unknown | 5,827 |
// Copyright 2016 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/focus_ring.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/i18n/rtl.h"
#include "base/memory/ptr_util.h"
#include "base/notreached.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/theme_provider.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/cascading_property.h"
#include "ui/views/controls/focusable_border.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_utils.h"
DEFINE_UI_CLASS_PROPERTY_TYPE(views::FocusRing*)
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(bool, kDrawFocusRingBackgroundOutline, false)
namespace {
DEFINE_UI_CLASS_PROPERTY_KEY(FocusRing*, kFocusRingIdKey, nullptr)
constexpr int kMinFocusRingInset = 2;
constexpr float kOutlineThickness = 1.0f;
constexpr float kFocusRingOutset = 2.0f;
bool IsPathUsable(const SkPath& path) {
return !path.isEmpty() && (path.isRect(nullptr) || path.isOval(nullptr) ||
path.isRRect(nullptr));
}
SkColor GetPaintColor(FocusRing* focus_ring, bool valid) {
const auto* cp = focus_ring->GetColorProvider();
if (!valid)
return cp->GetColor(ui::kColorAlertHighSeverity);
if (auto color_id = focus_ring->GetColorId(); color_id.has_value())
return cp->GetColor(color_id.value());
return GetCascadingAccentColor(focus_ring);
}
double GetCornerRadius(float halo_thickness) {
const double thickness = halo_thickness / 2.f;
return FocusRing::kDefaultCornerRadiusDp + thickness;
}
SkPath GetHighlightPathInternal(const View* view, float halo_thickness) {
HighlightPathGenerator* path_generator =
view->GetProperty(kHighlightPathGeneratorKey);
if (path_generator) {
SkPath highlight_path = path_generator->GetHighlightPath(view);
// The generated path might be empty or otherwise unusable. If that's the
// case we should fall back on the default path.
if (IsPathUsable(highlight_path))
return highlight_path;
}
gfx::Rect client_rect = view->GetLocalBounds();
const double corner_radius = GetCornerRadius(halo_thickness);
// Make sure we don't return an empty focus ring. This covers narrow views and
// the case where view->GetLocalBounds() are empty. Doing so prevents
// DCHECK(IsPathUsable(path)) from failing in GetRingRoundRect() because the
// resulting path is empty.
if (client_rect.IsEmpty()) {
client_rect.Outset(kMinFocusRingInset);
}
return SkPath().addRRect(SkRRect::MakeRectXY(RectToSkRect(client_rect),
corner_radius, corner_radius));
}
} // namespace
constexpr float FocusRing::kDefaultHaloThickness;
constexpr float FocusRing::kDefaultHaloInset;
// static
void FocusRing::Install(View* host) {
FocusRing::Remove(host);
auto ring = base::WrapUnique<FocusRing>(new FocusRing());
ring->InvalidateLayout();
ring->SchedulePaint();
host->SetProperty(kFocusRingIdKey, host->AddChildView(std::move(ring)));
}
FocusRing* FocusRing::Get(View* host) {
return host->GetProperty(kFocusRingIdKey);
}
const FocusRing* FocusRing::Get(const View* host) {
return host->GetProperty(kFocusRingIdKey);
}
void FocusRing::Remove(View* host) {
// Note that the FocusRing is owned by the View hierarchy, so we can't just
// clear the key.
FocusRing* const focus_ring = FocusRing::Get(host);
if (!focus_ring)
return;
host->RemoveChildViewT(focus_ring);
host->ClearProperty(kFocusRingIdKey);
}
FocusRing::~FocusRing() = default;
void FocusRing::SetPathGenerator(
std::unique_ptr<HighlightPathGenerator> generator) {
path_generator_ = std::move(generator);
InvalidateLayout();
SchedulePaint();
}
void FocusRing::SetInvalid(bool invalid) {
invalid_ = invalid;
SchedulePaint();
}
void FocusRing::SetHasFocusPredicate(const ViewPredicate& predicate) {
has_focus_predicate_ = predicate;
RefreshLayer();
}
absl::optional<ui::ColorId> FocusRing::GetColorId() const {
return color_id_;
}
void FocusRing::SetColorId(absl::optional<ui::ColorId> color_id) {
if (color_id_ == color_id)
return;
color_id_ = color_id;
OnPropertyChanged(&color_id_, PropertyEffects::kPropertyEffectsPaint);
}
float FocusRing::GetHaloThickness() const {
return halo_thickness_;
}
float FocusRing::GetHaloInset() const {
return halo_inset_;
}
void FocusRing::SetHaloThickness(float halo_thickness) {
if (halo_thickness_ == halo_thickness)
return;
halo_thickness_ = halo_thickness;
OnPropertyChanged(&halo_thickness_, PropertyEffects::kPropertyEffectsPaint);
}
void FocusRing::SetHaloInset(float halo_inset) {
if (halo_inset_ == halo_inset)
return;
halo_inset_ = halo_inset;
OnPropertyChanged(&halo_inset_, PropertyEffects::kPropertyEffectsPaint);
}
void FocusRing::SetOutsetFocusRingDisabled(bool disable) {
outset_focus_ring_disabled_ = disable;
}
bool FocusRing::GetOutsetFocusRingDisabled() const {
return outset_focus_ring_disabled_;
}
bool FocusRing::ShouldPaintForTesting() {
return ShouldPaint();
}
void FocusRing::Layout() {
// The focus ring handles its own sizing, which is simply to fill the parent
// and extend a little beyond its borders.
gfx::Rect focus_bounds = parent()->GetLocalBounds();
// Make sure the focus-ring path fits.
// TODO(pbos): Chase down use cases where this path is not in a usable state
// by the time layout happens. This may be due to synchronous Layout() calls.
const SkPath path = GetPath();
if (IsPathUsable(path)) {
const gfx::Rect path_bounds =
gfx::ToEnclosingRect(gfx::SkRectToRectF(path.getBounds()));
const gfx::Rect expanded_bounds =
gfx::UnionRects(focus_bounds, path_bounds);
// These insets are how much we need to inset `focus_bounds` to enclose the
// path as well. They'll be either zero or negative (we're effectively
// outsetting).
gfx::Insets expansion_insets = focus_bounds.InsetsFrom(expanded_bounds);
// Make sure we extend the focus-ring bounds symmetrically on the X axis to
// retain the shared center point with parent(). This is required for canvas
// flipping to position the focus-ring path correctly after the RTL flip.
const int min_x_inset =
std::min(expansion_insets.left(), expansion_insets.right());
expansion_insets.set_left(min_x_inset);
expansion_insets.set_right(min_x_inset);
focus_bounds.Inset(expansion_insets);
}
if (ShouldSetOutsetFocusRing()) {
focus_bounds.Outset(halo_thickness_ + kFocusRingOutset);
} else {
focus_bounds.Inset(gfx::Insets(halo_inset_));
if (parent()->GetProperty(kDrawFocusRingBackgroundOutline)) {
focus_bounds.Inset(gfx::Insets(-2 * kOutlineThickness));
}
}
SetBoundsRect(focus_bounds);
// Need to match canvas direction with the parent. This is required to ensure
// asymmetric focus ring shapes match their respective buttons in RTL mode.
SetFlipCanvasOnPaintForRTLUI(parent()->GetFlipCanvasOnPaintForRTLUI());
}
void FocusRing::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.child != this)
return;
if (details.is_add) {
// Need to start observing the parent.
view_observation_.Observe(details.parent);
RefreshLayer();
} else if (view_observation_.IsObservingSource(details.parent)) {
// This view is being removed from its parent. It needs to remove itself
// from its parent's observer list in the case where the FocusView is
// removed from its parent but not deleted.
view_observation_.Reset();
}
}
void FocusRing::OnPaint(gfx::Canvas* canvas) {
if (!ShouldPaint()) {
return;
}
SkRRect ring_rect = GetRingRoundRect();
cc::PaintFlags paint;
paint.setAntiAlias(true);
paint.setStyle(cc::PaintFlags::kStroke_Style);
if (!ShouldSetOutsetFocusRing()) {
// TODO(crbug.com/1417057): kDrawFocusRingBackgroundOutline should be
// removed when ChromeRefresh is fully rolled out.
if (parent()->GetProperty(kDrawFocusRingBackgroundOutline)) {
// Draw with full stroke width + 2x outline thickness to effectively paint
// the outline thickness on both sides of the FocusRing.
paint.setStrokeWidth(halo_thickness_ + 2 * kOutlineThickness);
paint.setColor(GetCascadingBackgroundColor(this));
canvas->sk_canvas()->drawRRect(ring_rect, paint);
}
}
paint.setColor(GetPaintColor(this, !invalid_));
paint.setStrokeWidth(halo_thickness_);
canvas->sk_canvas()->drawRRect(ring_rect, paint);
}
SkRRect FocusRing::GetRingRoundRect() const {
const SkPath path = GetPath();
DCHECK(IsPathUsable(path));
DCHECK_EQ(GetFlipCanvasOnPaintForRTLUI(),
parent()->GetFlipCanvasOnPaintForRTLUI());
SkRect bounds;
SkRRect rbounds;
if (path.isRect(&bounds)) {
AdjustBounds(bounds);
return RingRectFromPathRect(bounds);
}
if (path.isOval(&bounds)) {
AdjustBounds(bounds);
gfx::RectF rect = gfx::SkRectToRectF(bounds);
View::ConvertRectToTarget(parent(), this, &rect);
return SkRRect::MakeOval(gfx::RectFToSkRect(rect));
}
CHECK(path.isRRect(&rbounds));
AdjustBounds(rbounds);
return RingRectFromPathRect(rbounds);
}
void FocusRing::OnThemeChanged() {
View::OnThemeChanged();
if (invalid_ || color_id_.has_value())
SchedulePaint();
}
void FocusRing::OnViewFocused(View* view) {
RefreshLayer();
}
void FocusRing::OnViewBlurred(View* view) {
RefreshLayer();
}
FocusRing::FocusRing() {
// Don't allow the view to process events.
SetCanProcessEventsWithinSubtree(false);
// This should never be included in the accessibility tree.
GetViewAccessibility().OverrideIsIgnored(true);
}
void FocusRing::AdjustBounds(SkRect& rect) const {
if (ShouldSetOutsetFocusRing()) {
float focus_ring_adjustment = halo_thickness_ / 2 + kFocusRingOutset;
rect.outset(focus_ring_adjustment, focus_ring_adjustment);
}
}
void FocusRing::AdjustBounds(SkRRect& rect) const {
if (ShouldSetOutsetFocusRing()) {
float focus_ring_adjustment = halo_thickness_ / 2 + kFocusRingOutset;
rect.outset(focus_ring_adjustment, focus_ring_adjustment);
}
}
SkPath FocusRing::GetPath() const {
SkPath path;
if (path_generator_) {
path = path_generator_->GetHighlightPath(parent());
if (IsPathUsable(path))
return path;
}
// If there's no path generator or the generated path is unusable, fall back
// to the default.
return GetHighlightPathInternal(parent(), halo_thickness_);
}
void FocusRing::RefreshLayer() {
// TODO(pbos): This always keeps the layer alive if |has_focus_predicate_| is
// set. This is done because we're not notified when the predicate might
// return a different result and there are call sites that call SchedulePaint
// on FocusRings and expect that to be sufficient.
// The cleanup would be to always call has_focus_predicate_ here and make sure
// that RefreshLayer gets called somehow whenever |has_focused_predicate_|
// returns a new value.
const bool should_paint =
has_focus_predicate_.has_value() || (parent() && parent()->HasFocus());
SetVisible(should_paint);
if (should_paint) {
// A layer is necessary to paint beyond the parent's bounds.
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
} else {
DestroyLayer();
}
}
bool FocusRing::ShouldSetOutsetFocusRing() const {
// TODO(crbug.com/1417057): Some places set a custom `halo_inset_` value to
// move the focus ring away from the host. If those places want to outset the
// focus ring in the chrome refresh style, they need to be audited separately
// with UX.
return features::IsChromeRefresh2023() && !outset_focus_ring_disabled_ &&
halo_inset_ == FocusRing::kDefaultHaloInset;
}
bool FocusRing::ShouldPaint() {
// TODO(pbos): Reevaluate if this can turn into a DCHECK, e.g. we should
// never paint if there's no parent focus.
return (!has_focus_predicate_ || (*has_focus_predicate_)(parent())) &&
(has_focus_predicate_ || parent()->HasFocus());
}
SkRRect FocusRing::RingRectFromPathRect(const SkRect& rect) const {
const double corner_radius = GetCornerRadius(halo_thickness_);
return RingRectFromPathRect(
SkRRect::MakeRectXY(rect, corner_radius, corner_radius));
}
SkRRect FocusRing::RingRectFromPathRect(const SkRRect& rrect) const {
const double thickness = halo_thickness_ / 2.f;
gfx::RectF r = gfx::SkRectToRectF(rrect.rect());
View::ConvertRectToTarget(parent(), this, &r);
SkRRect skr =
rrect.makeOffset(r.x() - rrect.rect().x(), r.y() - rrect.rect().y());
// The focus indicator should hug the normal border, when present (as in the
// case of text buttons). Since it's drawn outside the parent view, increase
// the rounding slightly by adding half the ring thickness.
skr.inset(halo_inset_, halo_inset_);
skr.inset(thickness, thickness);
return skr;
}
SkPath GetHighlightPath(const View* view, float halo_thickness) {
SkPath path = GetHighlightPathInternal(view, halo_thickness);
if (view->GetFlipCanvasOnPaintForRTLUI() && base::i18n::IsRTL()) {
gfx::Point center = view->GetLocalBounds().CenterPoint();
SkMatrix flip;
flip.setScale(-1, 1, center.x(), center.y());
path.transform(flip);
}
return path;
}
BEGIN_METADATA(FocusRing, View)
ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, ColorId)
ADD_PROPERTY_METADATA(float, HaloInset)
ADD_PROPERTY_METADATA(float, HaloThickness)
ADD_PROPERTY_METADATA(bool, OutsetFocusRingDisabled)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/focus_ring.cc | C++ | unknown | 14,075 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_FOCUS_RING_H_
#define UI_VIEWS_CONTROLS_FOCUS_RING_H_
#include <memory>
#include "base/scoped_observation.h"
#include "ui/base/class_property.h"
#include "ui/color/color_id.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/focusable_border.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/views_export.h"
namespace views {
class HighlightPathGenerator;
// FocusRing is a View that is designed to act as an indicator of focus for its
// parent. It is a view that paints to a layer which extends beyond the bounds
// of its parent view.
// If MyView should show a rounded rectangular focus ring when it has focus and
// hide the ring when it loses focus, no other configuration is necessary. In
// other cases, it might be necessary to use the Set*() functions on FocusRing;
// these take care of repainting it when the state changes.
// TODO(tluk): FocusRing should not be a view but instead a new concept which
// only participates in view painting ( https://crbug.com/840796 ).
class VIEWS_EXPORT FocusRing : public View, public ViewObserver {
public:
METADATA_HEADER(FocusRing);
static constexpr float kDefaultCornerRadiusDp = 2.0f;
using ViewPredicate = std::function<bool(View* view)>;
// The default thickness and inset amount of focus ring halos. If you need
// the thickness of a specific focus ring, call halo_thickness() instead.
static constexpr float kDefaultHaloThickness = 2.0f;
// The default inset for the focus ring. Moves the ring slightly out from the
// edge of the host view, so that the halo doesn't significantly overlap the
// host view's contents. If you need a value for a specific focus ring, call
// halo_inset() instead.
static constexpr float kDefaultHaloInset = kDefaultHaloThickness * -0.5f;
// Creates a FocusRing and adds it to `host`.
static void Install(View* host);
// Gets the FocusRing, if present, from `host`.
static FocusRing* Get(View* host);
static const FocusRing* Get(const View* host);
// Removes the FocusRing, if present, from `host`.
static void Remove(View* host);
FocusRing(const FocusRing&) = delete;
FocusRing& operator=(const FocusRing&) = delete;
~FocusRing() override;
// Sets the HighlightPathGenerator to draw this FocusRing around.
// Note: This method should only be used if the focus ring needs to differ
// from the highlight shape used for InkDrops.
// Otherwise install a HighlightPathGenerator on the parent and FocusRing will
// use it as well.
void SetPathGenerator(std::unique_ptr<HighlightPathGenerator> generator);
// Sets whether the FocusRing should show an invalid state for the View it
// encloses.
void SetInvalid(bool invalid);
// Sets the predicate function used to tell when the parent has focus. The
// parent is passed into this predicate; it should return whether the parent
// should be treated as focused. This is useful when, for example, the parent
// wraps an inner view and the inner view is the one that actually receives
// focus, but the FocusRing sits on the parent instead of the inner view.
void SetHasFocusPredicate(const ViewPredicate& predicate);
absl::optional<ui::ColorId> GetColorId() const;
void SetColorId(absl::optional<ui::ColorId> color_id);
float GetHaloThickness() const;
float GetHaloInset() const;
void SetHaloThickness(float halo_thickness);
void SetHaloInset(float halo_inset);
// Explicitly disable using style of focus ring that is drawn with a 2dp gap
// between the focus ring and component.
void SetOutsetFocusRingDisabled(bool disable);
bool GetOutsetFocusRingDisabled() const;
bool ShouldPaintForTesting();
// View:
void Layout() override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
void OnPaint(gfx::Canvas* canvas) override;
void OnThemeChanged() override;
// ViewObserver:
void OnViewFocused(View* view) override;
void OnViewBlurred(View* view) override;
private:
FocusRing();
// Outset the input bounds if conditions are met.
void AdjustBounds(SkRect& rect) const;
void AdjustBounds(SkRRect& rect) const;
SkPath GetPath() const;
SkRRect GetRingRoundRect() const;
void RefreshLayer();
// Returns whether we should outset by `kFocusRingOutset` dp before drawing
// the focus ring.
bool ShouldSetOutsetFocusRing() const;
bool ShouldPaint();
// Translates the provided SkRect or SkRRect, which is in the parent's
// coordinate system, into this view's coordinate system, then insets it
// appropriately to produce the focus ring "halo" effect. If the supplied rect
// is an SkRect, it will have the default focus ring corner radius applied as
// well.
SkRRect RingRectFromPathRect(const SkRect& rect) const;
SkRRect RingRectFromPathRect(const SkRRect& rect) const;
// The path generator used to draw this focus ring.
std::unique_ptr<HighlightPathGenerator> path_generator_;
bool outset_focus_ring_disabled_ = false;
// Whether the enclosed View is in an invalid state, which controls whether
// the focus ring shows an invalid appearance (usually a different color).
bool invalid_ = false;
// Overriding color_id for the focus ring.
absl::optional<ui::ColorId> color_id_;
// The predicate used to determine whether the parent has focus.
absl::optional<ViewPredicate> has_focus_predicate_;
// The thickness of the focus ring halo, in DIP.
float halo_thickness_ = kDefaultHaloThickness;
// The adjustment from the visible border of the host view to render the
// focus ring.
//
// At -0.5 * halo_thickness_ (the default), the inner edge of the focus
// ring will align with the outer edge of the default inkdrop. For very thin
// focus rings, a zero value may provide better visual results.
float halo_inset_ = kDefaultHaloInset;
base::ScopedObservation<View, ViewObserver> view_observation_{this};
};
VIEWS_EXPORT SkPath
GetHighlightPath(const View* view,
float halo_thickness = FocusRing::kDefaultHaloThickness);
// Set this on the FocusRing host to have the FocusRing paint an outline around
// itself. This ensures that the FocusRing has sufficient contrast with its
// surroundings (this is used for prominent MdTextButtons because they are blue,
// while the background is light/dark, and the FocusRing doesn't contrast well
// with both the interior and exterior of the button). This may need some polish
// (such as blur?) in order to be expandable to all controls. For now it solves
// color contrast on prominent buttons which is an a11y issue. See
// https://crbug.com/1197631.
// TODO(pbos): Consider polishing this well enough that this can be
// unconditional. This may require rolling out `kCascadingBackgroundColor` to
// more surfaces to have an accurate background color.
VIEWS_EXPORT extern const ui::ClassProperty<bool>* const
kDrawFocusRingBackgroundOutline;
} // namespace views
#endif // UI_VIEWS_CONTROLS_FOCUS_RING_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/focus_ring.h | C++ | unknown | 7,184 |
// 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/focusable_border.h"
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/textfield/textfield.h"
namespace {
constexpr int kInsetSize = 1;
} // namespace
namespace views {
FocusableBorder::FocusableBorder()
: insets_(kInsetSize), corner_radius_(FocusRing::kDefaultCornerRadiusDp) {}
FocusableBorder::~FocusableBorder() = default;
void FocusableBorder::SetColorId(const absl::optional<ui::ColorId>& color_id) {
override_color_id_ = color_id;
}
void FocusableBorder::Paint(const View& view, gfx::Canvas* canvas) {
cc::PaintFlags flags;
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setColor(GetCurrentColor(view));
gfx::ScopedCanvas scoped(canvas);
float dsf = canvas->UndoDeviceScaleFactor();
constexpr int kStrokeWidthPx = 1;
flags.setStrokeWidth(SkIntToScalar(kStrokeWidthPx));
// Scale the rect and snap to pixel boundaries.
gfx::RectF rect(gfx::ScaleToEnclosedRect(view.GetLocalBounds(), dsf));
rect.Inset(gfx::InsetsF(kStrokeWidthPx / 2.0f));
SkPath path;
flags.setAntiAlias(true);
float corner_radius_px = corner_radius_ * dsf;
path.addRoundRect(gfx::RectFToSkRect(rect), corner_radius_px,
corner_radius_px);
canvas->DrawPath(path, flags);
}
gfx::Insets FocusableBorder::GetInsets() const {
return insets_;
}
gfx::Size FocusableBorder::GetMinimumSize() const {
return gfx::Size();
}
void FocusableBorder::SetInsets(const gfx::Insets& insets) {
insets_ = insets;
}
void FocusableBorder::SetCornerRadius(float radius) {
corner_radius_ = radius;
}
SkColor FocusableBorder::GetCurrentColor(const View& view) const {
ui::ColorId color_id = ui::kColorFocusableBorderUnfocused;
if (override_color_id_)
color_id = *override_color_id_;
SkColor color = view.GetColorProvider()->GetColor(color_id);
return view.GetEnabled() ? color
: color_utils::BlendTowardMaxContrast(
color, gfx::kDisabledControlAlpha);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/focusable_border.cc | C++ | unknown | 2,577 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_
#define UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/color/color_id.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/border.h"
#include "ui/views/view.h"
namespace gfx {
class Canvas;
} // namespace gfx
namespace views {
// A Border class to draw a focused border around a field (e.g textfield).
class VIEWS_EXPORT FocusableBorder : public Border {
public:
FocusableBorder();
FocusableBorder(const FocusableBorder&) = delete;
FocusableBorder& operator=(const FocusableBorder&) = delete;
~FocusableBorder() override;
// Sets the insets of the border.
void SetInsets(const gfx::Insets& insets);
// Sets the color id to use for this border. When unsupplied, the color will
// depend on the focus state.
void SetColorId(const absl::optional<ui::ColorId>& color_id);
// Sets the corner radius.
void SetCornerRadius(float corner_radius);
// Overridden from Border:
void Paint(const View& view, gfx::Canvas* canvas) override;
gfx::Insets GetInsets() const override;
gfx::Size GetMinimumSize() const override;
protected:
SkColor GetCurrentColor(const View& view) const;
private:
gfx::Insets insets_;
float corner_radius_;
absl::optional<ui::ColorId> override_color_id_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/focusable_border.h | C++ | unknown | 1,553 |
// Copyright 2019 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/highlight_path_generator.h"
#include <algorithm>
#include <utility>
#include "third_party/skia/include/core/SkRect.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/geometry/rrect_f.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
namespace views {
HighlightPathGenerator::HighlightPathGenerator()
: HighlightPathGenerator(gfx::Insets()) {}
HighlightPathGenerator::HighlightPathGenerator(const gfx::Insets& insets)
: insets_(insets) {}
HighlightPathGenerator::~HighlightPathGenerator() = default;
// static
void HighlightPathGenerator::Install(
View* host,
std::unique_ptr<HighlightPathGenerator> generator) {
host->SetProperty(kHighlightPathGeneratorKey, std::move(generator));
}
// static
absl::optional<gfx::RRectF> HighlightPathGenerator::GetRoundRectForView(
const View* view) {
HighlightPathGenerator* path_generator =
view->GetProperty(kHighlightPathGeneratorKey);
return path_generator ? path_generator->GetRoundRect(view) : absl::nullopt;
}
SkPath HighlightPathGenerator::GetHighlightPath(const View* view) {
// A rounded rectangle must be supplied if using this default implementation.
absl::optional<gfx::RRectF> round_rect = GetRoundRect(view);
DCHECK(round_rect);
return SkPath().addRRect(SkRRect{*round_rect});
}
absl::optional<gfx::RRectF> HighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
return absl::nullopt;
}
absl::optional<gfx::RRectF> HighlightPathGenerator::GetRoundRect(
const View* view) {
gfx::Rect bounds =
use_contents_bounds_ ? view->GetContentsBounds() : view->GetLocalBounds();
bounds.Inset(insets_);
if (use_mirrored_rect_)
bounds = view->GetMirroredRect(bounds);
return GetRoundRect(gfx::RectF(bounds));
}
absl::optional<gfx::RRectF> EmptyHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
return gfx::RRectF();
}
void InstallEmptyHighlightPathGenerator(View* view) {
HighlightPathGenerator::Install(
view, std::make_unique<EmptyHighlightPathGenerator>());
}
absl::optional<gfx::RRectF> RectHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
return gfx::RRectF(rect);
}
void InstallRectHighlightPathGenerator(View* view) {
HighlightPathGenerator::Install(
view, std::make_unique<RectHighlightPathGenerator>());
}
CircleHighlightPathGenerator::CircleHighlightPathGenerator(
const gfx::Insets& insets)
: HighlightPathGenerator(insets) {}
absl::optional<gfx::RRectF> CircleHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
gfx::RectF bounds = rect;
const float corner_radius = std::min(bounds.width(), bounds.height()) / 2.f;
bounds.ClampToCenteredSize(
gfx::SizeF(corner_radius * 2.f, corner_radius * 2.f));
return gfx::RRectF(bounds, corner_radius);
}
void InstallCircleHighlightPathGenerator(View* view) {
InstallCircleHighlightPathGenerator(view, gfx::Insets());
}
void InstallCircleHighlightPathGenerator(View* view,
const gfx::Insets& insets) {
HighlightPathGenerator::Install(
view, std::make_unique<CircleHighlightPathGenerator>(insets));
}
absl::optional<gfx::RRectF> PillHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
gfx::RectF bounds = rect;
const float corner_radius = std::min(bounds.width(), bounds.height()) / 2.f;
return gfx::RRectF(bounds, corner_radius);
}
void InstallPillHighlightPathGenerator(View* view) {
HighlightPathGenerator::Install(
view, std::make_unique<PillHighlightPathGenerator>());
}
FixedSizeCircleHighlightPathGenerator::FixedSizeCircleHighlightPathGenerator(
int radius)
: radius_(radius) {}
absl::optional<gfx::RRectF> FixedSizeCircleHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
gfx::RectF bounds = rect;
bounds.ClampToCenteredSize(gfx::SizeF(radius_ * 2, radius_ * 2));
return gfx::RRectF(bounds, radius_);
}
void InstallFixedSizeCircleHighlightPathGenerator(View* view, int radius) {
HighlightPathGenerator::Install(
view, std::make_unique<FixedSizeCircleHighlightPathGenerator>(radius));
}
RoundRectHighlightPathGenerator::RoundRectHighlightPathGenerator(
const gfx::Insets& insets,
int corner_radius)
: RoundRectHighlightPathGenerator(insets,
gfx::RoundedCornersF(corner_radius)) {}
RoundRectHighlightPathGenerator::RoundRectHighlightPathGenerator(
const gfx::Insets& insets,
const gfx::RoundedCornersF& rounded_corners)
: HighlightPathGenerator(insets), rounded_corners_(rounded_corners) {}
absl::optional<gfx::RRectF> RoundRectHighlightPathGenerator::GetRoundRect(
const gfx::RectF& rect) {
return gfx::RRectF(rect, rounded_corners_);
}
void InstallRoundRectHighlightPathGenerator(View* view,
const gfx::Insets& insets,
int corner_radius) {
HighlightPathGenerator::Install(
view,
std::make_unique<RoundRectHighlightPathGenerator>(insets, corner_radius));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/highlight_path_generator.cc | C++ | unknown | 5,320 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_HIGHLIGHT_PATH_GENERATOR_H_
#define UI_VIEWS_CONTROLS_HIGHLIGHT_PATH_GENERATOR_H_
#include <memory>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/views_export.h"
namespace gfx {
class RRectF;
}
namespace views {
class View;
// HighlightPathGenerators are used to generate its highlight path. This
// highlight path is used to generate the View's focus ring and ink-drop
// effects.
class VIEWS_EXPORT HighlightPathGenerator {
public:
HighlightPathGenerator();
explicit HighlightPathGenerator(const gfx::Insets& insets);
virtual ~HighlightPathGenerator();
HighlightPathGenerator(const HighlightPathGenerator&) = delete;
HighlightPathGenerator& operator=(const HighlightPathGenerator&) = delete;
static void Install(View* host,
std::unique_ptr<HighlightPathGenerator> generator);
static absl::optional<gfx::RRectF> GetRoundRectForView(const View* view);
// TODO(http://crbug.com/1056490): Deprecate |GetHighlightPath()| in favor of
// |GetRoundRect()|.
virtual SkPath GetHighlightPath(const View* view);
// Optionally returns a gfx::RRectF which contains data for drawing a
// highlight. Note that |rect| is in the coordinate system of the view.
// TODO(http://crbug.com/1056490): Once |GetHighlightPath()| is deprecated,
// make this a pure virtual function and make the return not optional.
virtual absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect);
absl::optional<gfx::RRectF> GetRoundRect(const View* view);
void set_use_contents_bounds(bool use_contents_bounds) {
use_contents_bounds_ = use_contents_bounds;
}
void set_use_mirrored_rect(bool use_mirrored_rect) {
use_mirrored_rect_ = use_mirrored_rect;
}
private:
const gfx::Insets insets_;
// When set uses the view's content bounds instead of its local bounds.
// TODO(http://crbug.com/1056490): Investigate removing this and seeing if all
// ink drops / focus rings should use the content bounds.
bool use_contents_bounds_ = false;
// When set uses the mirror rect in RTL. This should not be needed for focus
// rings paths as they handle RTL themselves.
// TODO(http://crbug.com/1056490): Investigate moving FocusRing RTL to this
// class and removing this bool.
bool use_mirrored_rect_ = false;
};
// Sets a highlight path that is empty. This is used for ink drops that want to
// rely on the size of their created ripples/highlights and not have any
// clipping applied to them.
class VIEWS_EXPORT EmptyHighlightPathGenerator : public HighlightPathGenerator {
public:
EmptyHighlightPathGenerator() = default;
EmptyHighlightPathGenerator(const EmptyHighlightPathGenerator&) = delete;
EmptyHighlightPathGenerator& operator=(const EmptyHighlightPathGenerator&) =
delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
};
void VIEWS_EXPORT InstallEmptyHighlightPathGenerator(View* view);
// Sets a rectangular highlight path.
class VIEWS_EXPORT RectHighlightPathGenerator : public HighlightPathGenerator {
public:
RectHighlightPathGenerator() = default;
RectHighlightPathGenerator(const RectHighlightPathGenerator&) = delete;
RectHighlightPathGenerator& operator=(const RectHighlightPathGenerator&) =
delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
};
void VIEWS_EXPORT InstallRectHighlightPathGenerator(View* view);
// Sets a centered circular highlight path.
class VIEWS_EXPORT CircleHighlightPathGenerator
: public HighlightPathGenerator {
public:
explicit CircleHighlightPathGenerator(const gfx::Insets& insets);
CircleHighlightPathGenerator(const CircleHighlightPathGenerator&) = delete;
CircleHighlightPathGenerator& operator=(const CircleHighlightPathGenerator&) =
delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
};
void VIEWS_EXPORT InstallCircleHighlightPathGenerator(View* view);
void VIEWS_EXPORT
InstallCircleHighlightPathGenerator(View* view, const gfx::Insets& insets);
// Sets a pill-shaped highlight path.
class VIEWS_EXPORT PillHighlightPathGenerator : public HighlightPathGenerator {
public:
PillHighlightPathGenerator() = default;
PillHighlightPathGenerator(const PillHighlightPathGenerator&) = delete;
PillHighlightPathGenerator& operator=(const PillHighlightPathGenerator&) =
delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
};
void VIEWS_EXPORT InstallPillHighlightPathGenerator(View* view);
// Sets a centered fixed-size circular highlight path.
class VIEWS_EXPORT FixedSizeCircleHighlightPathGenerator
: public HighlightPathGenerator {
public:
explicit FixedSizeCircleHighlightPathGenerator(int radius);
FixedSizeCircleHighlightPathGenerator(
const FixedSizeCircleHighlightPathGenerator&) = delete;
FixedSizeCircleHighlightPathGenerator& operator=(
const FixedSizeCircleHighlightPathGenerator&) = delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
private:
const int radius_;
};
void VIEWS_EXPORT InstallFixedSizeCircleHighlightPathGenerator(View* view,
int radius);
// Sets a rounded rectangle highlight path with optional insets.
class VIEWS_EXPORT RoundRectHighlightPathGenerator
: public HighlightPathGenerator {
public:
RoundRectHighlightPathGenerator(const gfx::Insets& insets, int corner_radius);
RoundRectHighlightPathGenerator(const gfx::Insets& insets,
const gfx::RoundedCornersF& rounded_corners);
RoundRectHighlightPathGenerator(const RoundRectHighlightPathGenerator&) =
delete;
RoundRectHighlightPathGenerator& operator=(
const RoundRectHighlightPathGenerator&) = delete;
// HighlightPathGenerator:
absl::optional<gfx::RRectF> GetRoundRect(const gfx::RectF& rect) override;
private:
const gfx::RoundedCornersF rounded_corners_;
};
void VIEWS_EXPORT
InstallRoundRectHighlightPathGenerator(View* view,
const gfx::Insets& insets,
int corner_radius);
} // namespace views
#endif // UI_VIEWS_CONTROLS_HIGHLIGHT_PATH_GENERATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/highlight_path_generator.h | C++ | unknown | 6,744 |
// 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/image_view.h"
#include <utility>
#include "base/check_op.h"
#include "base/i18n/rtl.h"
#include "base/numerics/safe_conversions.h"
#include "base/trace_event/trace_event.h"
#include "cc/paint/paint_flags.h"
#include "skia/ext/image_operations.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/themed_vector_icon.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/gfx/paint_vector_icon.h"
namespace views {
namespace {
// Returns the pixels for the bitmap in |image| at scale |image_scale|.
void* GetBitmapPixels(const gfx::ImageSkia& image, float image_scale) {
DCHECK_NE(0.0f, image_scale);
return image.GetRepresentation(image_scale).GetBitmap().getPixels();
}
} // namespace
ImageView::ImageView() = default;
ImageView::ImageView(const ui::ImageModel& image_model) {
SetImage(image_model);
}
ImageView::~ImageView() = default;
void ImageView::SetImage(const ui::ImageModel& image_model) {
if (IsImageEqual(image_model))
return;
const gfx::Size pref_size = GetPreferredSize();
image_model_ = image_model;
scaled_image_ = gfx::ImageSkia();
if (pref_size != GetPreferredSize())
PreferredSizeChanged();
SchedulePaint();
}
gfx::ImageSkia ImageView::GetImage() const {
return image_model_.Rasterize(GetColorProvider());
}
ui::ImageModel ImageView::GetImageModel() const {
return image_model_;
}
bool ImageView::IsImageEqual(const ui::ImageModel& image_model) const {
if (image_model != image_model_)
return false;
// It's not feasible to run the old and new generators and compare output
// here, so for safety, simply assume the new generator's output differs.
if (image_model.IsImageGenerator())
return false;
if (!image_model.IsImage())
return true;
// An ImageModel's Image holds a handle to a backing store, which may have
// changed since the last call to SetImage(). The expectation is that
// SetImage() with different pixels is treated as though the image changed.
// For this reason we compare not only the Image but also the pixels we last
// painted.
return last_paint_scale_ != 0.0f &&
last_painted_bitmap_pixels_ ==
GetBitmapPixels(image_model.GetImage().AsImageSkia(),
last_paint_scale_);
}
gfx::Size ImageView::GetImageSize() const {
return image_size_.value_or(image_model_.Size());
}
void ImageView::OnPaint(gfx::Canvas* canvas) {
// This inlines View::OnPaint in order to OnPaintBorder() after OnPaintImage
// so the border can paint over content (for rounded corners that overlap
// content).
TRACE_EVENT1("views", "ImageView::OnPaint", "class", GetClassName());
OnPaintBackground(canvas);
OnPaintImage(canvas);
OnPaintBorder(canvas);
}
void ImageView::OnThemeChanged() {
View::OnThemeChanged();
if (image_model_.IsImageGenerator() ||
(image_model_.IsVectorIcon() &&
!image_model_.GetVectorIcon().has_color())) {
scaled_image_ = gfx::ImageSkia();
SchedulePaint();
}
}
void ImageView::OnPaintImage(gfx::Canvas* canvas) {
last_paint_scale_ = canvas->image_scale();
last_painted_bitmap_pixels_ = nullptr;
gfx::ImageSkia image = GetPaintImage(last_paint_scale_);
if (image.isNull())
return;
gfx::Rect image_bounds(GetImageBounds());
if (image_bounds.IsEmpty())
return;
if (image_bounds.size() != gfx::Size(image.width(), image.height())) {
// Resize case
cc::PaintFlags flags;
flags.setFilterQuality(cc::PaintFlags::FilterQuality::kLow);
canvas->DrawImageInt(image, 0, 0, image.width(), image.height(),
image_bounds.x(), image_bounds.y(),
image_bounds.width(), image_bounds.height(), true,
flags);
} else {
canvas->DrawImageInt(image, image_bounds.x(), image_bounds.y());
}
last_painted_bitmap_pixels_ = GetBitmapPixels(image, last_paint_scale_);
}
gfx::ImageSkia ImageView::GetPaintImage(float scale) {
if (image_model_.IsEmpty())
return gfx::ImageSkia();
if (image_model_.IsImage() || image_model_.IsImageGenerator()) {
const gfx::ImageSkia image = image_model_.Rasterize(GetColorProvider());
if (image.isNull())
return image;
const gfx::ImageSkiaRep& rep = image.GetRepresentation(scale);
if (rep.scale() == scale || rep.unscaled())
return image;
if (scaled_image_.HasRepresentation(scale))
return scaled_image_;
// Only caches one image rep for the current scale.
scaled_image_ = gfx::ImageSkia();
gfx::Size scaled_size =
gfx::ScaleToCeiledSize(rep.pixel_size(), scale / rep.scale());
scaled_image_.AddRepresentation(gfx::ImageSkiaRep(
skia::ImageOperations::Resize(
rep.GetBitmap(), skia::ImageOperations::RESIZE_BEST,
scaled_size.width(), scaled_size.height()),
scale));
} else if (scaled_image_.isNull()) {
scaled_image_ = image_model_.Rasterize(GetColorProvider());
}
return scaled_image_;
}
BEGIN_METADATA(ImageView, ImageViewBase)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/image_view.cc | C++ | unknown | 5,250 |
// 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.
#ifndef UI_VIEWS_CONTROLS_IMAGE_VIEW_H_
#define UI_VIEWS_CONTROLS_IMAGE_VIEW_H_
#include "base/memory/raw_ptr.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/controls/image_view_base.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/views_export.h"
namespace gfx {
class Canvas;
}
namespace views {
/////////////////////////////////////////////////////////////////////////////
//
// ImageView class.
//
// An ImageView can display an image from an ImageSkia. If a size is provided,
// the ImageView will resize the provided image to fit if it is too big or will
// center the image if smaller. Otherwise, the preferred size matches the
// provided image size.
//
/////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT ImageView : public ImageViewBase {
public:
METADATA_HEADER(ImageView);
ImageView();
explicit ImageView(const ui::ImageModel& image_model);
ImageView(const ImageView&) = delete;
ImageView& operator=(const ImageView&) = delete;
~ImageView() override;
// Set the image that should be displayed.
// TODO(pkasting): Change callers to pass an ImageModel and eliminate this.
void SetImage(const gfx::ImageSkia& image) {
SetImage(ui::ImageModel::FromImageSkia(image));
}
// Set the image that should be displayed from a pointer. Reset the image
// if the pointer is NULL.
// TODO(pkasting): Change callers to pass an ImageModel and eliminate this.
void SetImage(const gfx::ImageSkia* image_skia) {
SetImage(image_skia ? *image_skia : gfx::ImageSkia());
}
// Sets the image that should be displayed.
void SetImage(const ui::ImageModel& image_model);
// Returns the image currently displayed, which can be empty if not set.
// TODO(pkasting): Convert to an ImageModel getter.
gfx::ImageSkia GetImage() const;
ui::ImageModel GetImageModel() const;
// Overridden from View:
void OnPaint(gfx::Canvas* canvas) override;
protected:
// Overridden from ImageViewBase:
gfx::Size GetImageSize() const override;
void OnThemeChanged() override;
private:
friend class ImageViewTest;
void OnPaintImage(gfx::Canvas* canvas);
// Gets an ImageSkia to paint that has proper rep for |scale|. Note that if
// there is no existing rep of `scale`, we will utilize the image resize
// operation to create one. The resize may be time consuming for a big image.
gfx::ImageSkia GetPaintImage(float scale);
// Returns true if |image_model| is the same as the last image we painted.
// This is intended to be a quick check, not exhaustive. In other words it's
// possible for this to return false even though the images are in fact equal.
bool IsImageEqual(const ui::ImageModel& image_model) const;
// The underlying image.
ui::ImageModel image_model_;
// Caches the scaled image reps.
gfx::ImageSkia scaled_image_;
// Scale last painted at.
float last_paint_scale_ = 0.f;
// Address of bytes we last painted. This is used only for comparison, so its
// safe to cache.
raw_ptr<void, DanglingUntriaged> last_painted_bitmap_pixels_ = nullptr;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ImageView, ImageViewBase)
VIEW_BUILDER_OVERLOAD_METHOD(SetImage, const gfx::ImageSkia&)
VIEW_BUILDER_OVERLOAD_METHOD(SetImage, const gfx::ImageSkia*)
VIEW_BUILDER_OVERLOAD_METHOD(SetImage, const ui::ImageModel&)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ImageView)
#endif // UI_VIEWS_CONTROLS_IMAGE_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/image_view.h | C++ | unknown | 3,731 |
// Copyright 2018 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/image_view_base.h"
#include <utility>
#include "base/i18n/rtl.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/accessibility/view_accessibility.h"
namespace views {
ImageViewBase::ImageViewBase() {
SetAccessibilityProperties(ax::mojom::Role::kImage);
// The role of an object should not change over its lifetime. Therefore,
// rather than changing the role to `kNone` when there is no presentable
// information, set it to ignored. This will result in the same tree
// inclusion/exclusion behavior without unexpected platform-specific
// side effects related to the role changing.
if (GetAccessibleName().empty() && tooltip_text_.empty()) {
GetViewAccessibility().OverrideIsIgnored(true);
}
}
ImageViewBase::~ImageViewBase() = default;
void ImageViewBase::SetImageSize(const gfx::Size& image_size) {
image_size_ = image_size;
PreferredSizeChanged();
}
gfx::Rect ImageViewBase::GetImageBounds() const {
return gfx::Rect(image_origin_, GetImageSize());
}
void ImageViewBase::ResetImageSize() {
image_size_.reset();
PreferredSizeChanged();
}
void ImageViewBase::SetHorizontalAlignment(Alignment alignment) {
if (alignment != horizontal_alignment_) {
horizontal_alignment_ = alignment;
UpdateImageOrigin();
OnPropertyChanged(&horizontal_alignment_, kPropertyEffectsPaint);
}
}
ImageViewBase::Alignment ImageViewBase::GetHorizontalAlignment() const {
return horizontal_alignment_;
}
void ImageViewBase::SetVerticalAlignment(Alignment alignment) {
if (alignment != vertical_alignment_) {
vertical_alignment_ = alignment;
UpdateImageOrigin();
OnPropertyChanged(&horizontal_alignment_, kPropertyEffectsPaint);
}
}
ImageViewBase::Alignment ImageViewBase::GetVerticalAlignment() const {
return vertical_alignment_;
}
void ImageViewBase::SetTooltipText(const std::u16string& tooltip) {
if (tooltip_text_ == tooltip) {
return;
}
std::u16string current_tooltip = tooltip_text_;
tooltip_text_ = tooltip;
if (GetAccessibleName().empty() || GetAccessibleName() == current_tooltip) {
SetAccessibleName(tooltip);
}
TooltipTextChanged();
OnPropertyChanged(&tooltip_text_, kPropertyEffectsNone);
}
const std::u16string& ImageViewBase::GetTooltipText() const {
return tooltip_text_;
}
void ImageViewBase::AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) {
if (new_name.empty()) {
new_name = tooltip_text_;
}
GetViewAccessibility().OverrideIsIgnored(new_name.empty());
}
std::u16string ImageViewBase::GetTooltipText(const gfx::Point& p) const {
return tooltip_text_;
}
gfx::Size ImageViewBase::CalculatePreferredSize() const {
gfx::Size size = GetImageSize();
size.Enlarge(GetInsets().width(), GetInsets().height());
return size;
}
views::PaintInfo::ScaleType ImageViewBase::GetPaintScaleType() const {
// ImageViewBase contains an image which is rastered at the device scale
// factor. By default, the paint commands are recorded at a scale factor
// slightly different from the device scale factor. Re-rastering the image at
// this paint recording scale will result in a distorted image. Paint
// recording scale might also not be uniform along the x & y axis, thus
// resulting in further distortion in the aspect ratio of the final image.
// |kUniformScaling| ensures that the paint recording scale is uniform along
// the x & y axis and keeps the scale equal to the device scale factor.
// See http://crbug.com/754010 for more details.
return views::PaintInfo::ScaleType::kUniformScaling;
}
void ImageViewBase::OnBoundsChanged(const gfx::Rect& previous_bounds) {
UpdateImageOrigin();
}
void ImageViewBase::UpdateImageOrigin() {
gfx::Size image_size = GetImageSize();
gfx::Insets insets = GetInsets();
int x = 0;
// In order to properly handle alignment of images in RTL locales, we need
// to flip the meaning of trailing and leading. For example, if the
// horizontal alignment is set to trailing, then we'll use left alignment for
// the image instead of right alignment if the UI layout is RTL.
Alignment actual_horizontal_alignment = horizontal_alignment_;
if (base::i18n::IsRTL() && (horizontal_alignment_ != Alignment::kCenter)) {
actual_horizontal_alignment = (horizontal_alignment_ == Alignment::kLeading)
? Alignment::kTrailing
: Alignment::kLeading;
}
switch (actual_horizontal_alignment) {
case Alignment::kLeading:
x = insets.left();
break;
case Alignment::kTrailing:
x = width() - insets.right() - image_size.width();
break;
case Alignment::kCenter:
x = (width() - insets.width() - image_size.width()) / 2 + insets.left();
break;
}
int y = 0;
switch (vertical_alignment_) {
case Alignment::kLeading:
y = insets.top();
break;
case Alignment::kTrailing:
y = height() - insets.bottom() - image_size.height();
break;
case Alignment::kCenter:
y = (height() - insets.height() - image_size.height()) / 2 + insets.top();
break;
}
image_origin_ = gfx::Point(x, y);
}
void ImageViewBase::PreferredSizeChanged() {
View::PreferredSizeChanged();
UpdateImageOrigin();
}
BEGIN_METADATA(ImageViewBase, View)
ADD_PROPERTY_METADATA(Alignment, HorizontalAlignment)
ADD_PROPERTY_METADATA(Alignment, VerticalAlignment)
ADD_PROPERTY_METADATA(std::u16string, TooltipText)
END_METADATA
} // namespace views
DEFINE_ENUM_CONVERTERS(views::ImageViewBase::Alignment,
{views::ImageViewBase::Alignment::kLeading, u"kLeading"},
{views::ImageViewBase::Alignment::kCenter, u"kCenter"},
{views::ImageViewBase::Alignment::kTrailing,
u"kTrailing"})
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/image_view_base.cc | C++ | unknown | 6,128 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_IMAGE_VIEW_BASE_H_
#define UI_VIEWS_CONTROLS_IMAGE_VIEW_BASE_H_
#include <string>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
namespace views {
class VIEWS_EXPORT ImageViewBase : public View {
public:
METADATA_HEADER(ImageViewBase);
enum class Alignment { kLeading, kCenter, kTrailing };
ImageViewBase();
ImageViewBase(const ImageViewBase&) = delete;
ImageViewBase& operator=(const ImageViewBase&) = delete;
~ImageViewBase() override;
// Set the desired image size for the receiving ImageView.
void SetImageSize(const gfx::Size& image_size);
// Returns the actual bounds of the visible image inside the view.
gfx::Rect GetImageBounds() const;
// Reset the image size to the current image dimensions.
void ResetImageSize();
// Set / Get the horizontal alignment.
void SetHorizontalAlignment(Alignment ha);
Alignment GetHorizontalAlignment() const;
// Set / Get the vertical alignment.
void SetVerticalAlignment(Alignment va);
Alignment GetVerticalAlignment() const;
// Set the tooltip text.
void SetTooltipText(const std::u16string& tooltip);
const std::u16string& GetTooltipText() const;
// Overridden from View:
void AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) override;
std::u16string GetTooltipText(const gfx::Point& p) const override;
gfx::Size CalculatePreferredSize() const override;
views::PaintInfo::ScaleType GetPaintScaleType() const override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void PreferredSizeChanged() override;
protected:
// Returns the size the image will be painted.
virtual gfx::Size GetImageSize() const = 0;
// The requested image size.
absl::optional<gfx::Size> image_size_;
private:
friend class ImageViewTest;
// Recomputes and updates the |image_origin_|.
void UpdateImageOrigin();
// The origin of the image.
gfx::Point image_origin_;
// Horizontal alignment.
Alignment horizontal_alignment_ = Alignment::kCenter;
// Vertical alignment.
Alignment vertical_alignment_ = Alignment::kCenter;
// The current tooltip text.
std::u16string tooltip_text_;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ImageViewBase, View)
VIEW_BUILDER_PROPERTY(gfx::Size, ImageSize)
VIEW_BUILDER_PROPERTY(ImageViewBase::Alignment, HorizontalAlignment)
VIEW_BUILDER_PROPERTY(ImageViewBase::Alignment, VerticalAlignment)
VIEW_BUILDER_PROPERTY(std::u16string, TooltipText)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ImageViewBase)
#endif // UI_VIEWS_CONTROLS_IMAGE_VIEW_BASE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/image_view_base.h | C++ | unknown | 2,979 |
// Copyright 2018 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/image_view.h"
#include <memory>
#include <string>
#include <utility>
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/border.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/widget/widget.h"
namespace {
enum class Axis {
kHorizontal,
kVertical,
};
// A test utility function to set the application default text direction.
void SetRTL(bool rtl) {
// Override the current locale/direction.
base::i18n::SetICUDefaultLocale(rtl ? "he" : "en");
EXPECT_EQ(rtl, base::i18n::IsRTL());
}
} // namespace
namespace views {
class ImageViewTest : public ViewsTestBase,
public ::testing::WithParamInterface<Axis> {
public:
ImageViewTest() = default;
ImageViewTest(const ImageViewTest&) = delete;
ImageViewTest& operator=(const ImageViewTest&) = delete;
// ViewsTestBase:
void SetUp() override {
ViewsTestBase::SetUp();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(200, 200);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_.Init(std::move(params));
auto container = std::make_unique<View>();
// Make sure children can take up exactly as much space as they require.
BoxLayout::Orientation orientation =
GetParam() == Axis::kHorizontal ? BoxLayout::Orientation::kHorizontal
: BoxLayout::Orientation::kVertical;
container->SetLayoutManager(std::make_unique<BoxLayout>(orientation));
image_view_ = container->AddChildView(std::make_unique<ImageView>());
widget_.SetContentsView(std::move(container));
widget_.Show();
}
void TearDown() override {
widget_.Close();
ViewsTestBase::TearDown();
}
int CurrentImageOriginForParam() {
image_view()->UpdateImageOrigin();
gfx::Point origin = image_view()->GetImageBounds().origin();
return GetParam() == Axis::kHorizontal ? origin.x() : origin.y();
}
protected:
ImageView* image_view() { return image_view_; }
Widget* widget() { return &widget_; }
private:
raw_ptr<ImageView> image_view_ = nullptr;
Widget widget_;
};
// Test the image origin of the internal ImageSkia is correct when it is
// center-aligned (both horizontally and vertically).
TEST_P(ImageViewTest, CenterAlignment) {
image_view()->SetHorizontalAlignment(ImageView::Alignment::kCenter);
constexpr int kImageSkiaSize = 4;
SkBitmap bitmap;
bitmap.allocN32Pixels(kImageSkiaSize, kImageSkiaSize);
gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
image_view()->SetImage(image_skia);
views::test::RunScheduledLayout(image_view());
EXPECT_NE(gfx::Size(), image_skia.size());
// With no changes to the size / padding of |image_view|, the origin of
// |image_skia| is the same as the origin of |image_view|.
EXPECT_EQ(0, CurrentImageOriginForParam());
// Test insets are always respected in LTR and RTL.
constexpr int kInset = 5;
image_view()->SetBorder(CreateEmptyBorder(kInset));
views::test::RunScheduledLayout(image_view());
EXPECT_EQ(kInset, CurrentImageOriginForParam());
SetRTL(true);
views::test::RunScheduledLayout(image_view());
EXPECT_EQ(kInset, CurrentImageOriginForParam());
// Check this still holds true when the insets are asymmetrical.
constexpr int kLeadingInset = 4;
constexpr int kTrailingInset = 6;
image_view()->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(
kLeadingInset, kLeadingInset, kTrailingInset, kTrailingInset)));
views::test::RunScheduledLayout(image_view());
EXPECT_EQ(kLeadingInset, CurrentImageOriginForParam());
SetRTL(false);
views::test::RunScheduledLayout(image_view());
EXPECT_EQ(kLeadingInset, CurrentImageOriginForParam());
}
TEST_P(ImageViewTest, ImageOriginForCustomViewBounds) {
gfx::Rect image_view_bounds(10, 10, 80, 80);
image_view()->SetHorizontalAlignment(ImageView::Alignment::kCenter);
image_view()->SetBoundsRect(image_view_bounds);
SkBitmap bitmap;
constexpr int kImageSkiaSize = 20;
bitmap.allocN32Pixels(kImageSkiaSize, kImageSkiaSize);
gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
image_view()->SetImage(image_skia);
EXPECT_EQ(gfx::Point(30, 30), image_view()->GetImageBounds().origin());
EXPECT_EQ(image_view_bounds, image_view()->bounds());
}
// Verifies setting the accessible name will be call NotifyAccessibilityEvent.
TEST_P(ImageViewTest, SetAccessibleNameNotifiesAccessibilityEvent) {
std::u16string test_tooltip_text = u"Test Tooltip Text";
test::AXEventCounter counter(views::AXEventManager::Get());
EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged));
image_view()->SetAccessibleName(test_tooltip_text);
EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged));
EXPECT_EQ(test_tooltip_text, image_view()->GetAccessibleName());
ui::AXNodeData data;
image_view()->GetAccessibleNodeData(&data);
const std::string& name =
data.GetStringAttribute(ax::mojom::StringAttribute::kName);
EXPECT_EQ(test_tooltip_text, base::ASCIIToUTF16(name));
}
TEST_P(ImageViewTest, AccessibleNameFromTooltipText) {
// Initially there is no name and no tooltip text.
// The role should always be image, regardless of whether or not there is
// presentable information. It's the "ignored" state which should change.
ui::AXNodeData data;
image_view()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
std::u16string());
EXPECT_EQ(image_view()->GetAccessibleName(), std::u16string());
EXPECT_EQ(image_view()->GetTooltipText(), std::u16string());
EXPECT_EQ(data.role, ax::mojom::Role::kImage);
EXPECT_TRUE(image_view()->GetViewAccessibility().IsIgnored());
// Setting the tooltip text when there is no accessible name should result in
// the tooltip text being used for the accessible name and the "ignored" state
// being removed.
data = ui::AXNodeData();
std::u16string tooltip_text = u"Tooltip Text";
image_view()->SetTooltipText(tooltip_text);
image_view()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
tooltip_text);
EXPECT_EQ(image_view()->GetAccessibleName(), tooltip_text);
EXPECT_EQ(image_view()->GetTooltipText(), tooltip_text);
EXPECT_EQ(data.role, ax::mojom::Role::kImage);
EXPECT_FALSE(image_view()->GetViewAccessibility().IsIgnored());
// Setting the accessible name to a non-empty string should replace the name
// from the tooltip text.
data = ui::AXNodeData();
std::u16string accessible_name = u"Accessible Name";
image_view()->SetAccessibleName(accessible_name);
image_view()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
accessible_name);
EXPECT_EQ(image_view()->GetAccessibleName(), accessible_name);
EXPECT_EQ(image_view()->GetTooltipText(), tooltip_text);
EXPECT_EQ(data.role, ax::mojom::Role::kImage);
EXPECT_FALSE(image_view()->GetViewAccessibility().IsIgnored());
// Setting the accessible name to an empty string should cause the tooltip
// text to be used as the name.
data = ui::AXNodeData();
image_view()->SetAccessibleName(std::u16string());
image_view()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
tooltip_text);
EXPECT_EQ(image_view()->GetAccessibleName(), tooltip_text);
EXPECT_EQ(image_view()->GetTooltipText(), tooltip_text);
EXPECT_EQ(data.role, ax::mojom::Role::kImage);
EXPECT_FALSE(image_view()->GetViewAccessibility().IsIgnored());
// Setting the tooltip to an empty string without setting a new accessible
// name should cause the view to become "ignored" again.
data = ui::AXNodeData();
image_view()->SetTooltipText(std::u16string());
image_view()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
std::u16string());
EXPECT_EQ(image_view()->GetAccessibleName(), std::u16string());
EXPECT_EQ(image_view()->GetTooltipText(), std::u16string());
EXPECT_EQ(data.role, ax::mojom::Role::kImage);
EXPECT_TRUE(image_view()->GetViewAccessibility().IsIgnored());
}
INSTANTIATE_TEST_SUITE_P(All,
ImageViewTest,
::testing::Values(Axis::kHorizontal, Axis::kVertical));
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/image_view_unittest.cc | C++ | unknown | 9,204 |
// 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/label.h"
#include <stddef.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <utility>
#include <vector>
#include "base/i18n/rtl.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/default_style.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/text_elider.h"
#include "ui/gfx/text_utils.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/cascading_property.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/selection_controller.h"
namespace {
// An enum giving different RenderText properties unique keys for the
// OnPropertyChanged call.
enum LabelPropertyKey {
kLabelText = 1,
kLabelShadows,
kLabelHorizontalAlignment,
kLabelVerticalAlignment,
kLabelLineHeight,
kLabelObscured,
kLabelAllowCharacterBreak,
kLabelDrawStringsFlags,
};
bool IsOpaque(SkColor color) {
return SkColorGetA(color) == SK_AlphaOPAQUE;
}
// Strips accelerator character prefixes in |text| if needed, based on |flags|.
// Returns a range in |text| to underline or Range::InvalidRange() if
// underlining is not needed.
gfx::Range StripAcceleratorChars(int flags, std::u16string* text) {
if (flags & (gfx::Canvas::SHOW_PREFIX | gfx::Canvas::HIDE_PREFIX)) {
int char_pos = -1;
int char_span = 0;
*text = gfx::LocateAndRemoveAcceleratorChar(*text, &char_pos, &char_span);
if ((flags & gfx::Canvas::SHOW_PREFIX) && char_pos != -1) {
return gfx::Range(static_cast<size_t>(char_pos),
static_cast<size_t>(char_pos + char_span));
}
}
return gfx::Range::InvalidRange();
}
} // namespace
namespace views {
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(CascadingProperty<SkColor>,
kCascadingLabelEnabledColor,
nullptr)
Label::Label() : Label(std::u16string()) {}
Label::Label(const std::u16string& text)
: Label(text, style::CONTEXT_LABEL, style::STYLE_PRIMARY) {}
Label::Label(const std::u16string& text,
int text_context,
int text_style,
gfx::DirectionalityMode directionality_mode)
: text_context_(text_context),
text_style_(text_style),
context_menu_contents_(this) {
Init(text, style::GetFont(text_context, text_style), directionality_mode);
}
Label::Label(const std::u16string& text, const CustomFont& font)
: text_context_(style::CONTEXT_LABEL),
text_style_(style::STYLE_PRIMARY),
context_menu_contents_(this) {
Init(text, font.font_list, gfx::DirectionalityMode::DIRECTIONALITY_FROM_TEXT);
}
Label::~Label() = default;
// static
const gfx::FontList& Label::GetDefaultFontList() {
return style::GetFont(style::CONTEXT_LABEL, style::STYLE_PRIMARY);
}
void Label::SetFontList(const gfx::FontList& font_list) {
full_text_->SetFontList(font_list);
ClearDisplayText();
PreferredSizeChanged();
}
const std::u16string& Label::GetText() const {
return full_text_->text();
}
void Label::SetText(const std::u16string& new_text) {
if (new_text == GetText())
return;
std::u16string current_text = GetText();
full_text_->SetText(new_text);
ClearDisplayText();
if (GetAccessibleName().empty() || GetAccessibleName() == current_text) {
SetAccessibleName(new_text);
}
OnPropertyChanged(&full_text_ + kLabelText,
kPropertyEffectsPreferredSizeChanged);
stored_selection_range_ = gfx::Range::InvalidRange();
}
void Label::AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) {
if (new_name.empty()) {
new_name = full_text_->GetDisplayText();
}
}
int Label::GetTextContext() const {
return text_context_;
}
void Label::SetTextContext(int text_context) {
if (text_context == text_context_)
return;
text_context_ = text_context;
full_text_->SetFontList(style::GetFont(text_context_, text_style_));
full_text_->SetMinLineHeight(GetLineHeight());
ClearDisplayText();
if (GetWidget())
UpdateColorsFromTheme();
SetAccessibleRole(text_context_ == style::CONTEXT_DIALOG_TITLE
? ax::mojom::Role::kTitleBar
: ax::mojom::Role::kStaticText);
OnPropertyChanged(&text_context_, kPropertyEffectsPreferredSizeChanged);
}
int Label::GetTextStyle() const {
return text_style_;
}
void Label::SetTextStyle(int style) {
if (style == text_style_)
return;
text_style_ = style;
ApplyBaselineTextStyle();
}
void Label::ApplyBaselineTextStyle() {
full_text_->SetFontList(style::GetFont(text_context_, text_style_));
full_text_->SetMinLineHeight(GetLineHeight());
ClearDisplayText();
if (GetWidget())
UpdateColorsFromTheme();
OnPropertyChanged(&text_style_, kPropertyEffectsPreferredSizeChanged);
}
void Label::SetTextStyleRange(int style, const gfx::Range& range) {
if (style == text_style_ || !range.IsValid() || range.is_empty() ||
!gfx::Range(0, GetText().size()).Contains(range)) {
return;
}
const auto details = style::GetFontDetails(text_context_, style);
// This function is not prepared to handle style requests that vary by
// anything other than weight.
DCHECK_EQ(details.typeface,
style::GetFontDetails(text_context_, text_style_).typeface);
DCHECK_EQ(details.size_delta,
style::GetFontDetails(text_context_, text_style_).size_delta);
full_text_->ApplyWeight(details.weight, range);
ClearDisplayText();
PreferredSizeChanged();
}
bool Label::GetAutoColorReadabilityEnabled() const {
return auto_color_readability_enabled_;
}
void Label::SetAutoColorReadabilityEnabled(
bool auto_color_readability_enabled) {
if (auto_color_readability_enabled_ == auto_color_readability_enabled)
return;
auto_color_readability_enabled_ = auto_color_readability_enabled;
RecalculateColors();
OnPropertyChanged(&auto_color_readability_enabled_, kPropertyEffectsPaint);
}
SkColor Label::GetEnabledColor() const {
return actual_enabled_color_;
}
void Label::SetEnabledColor(SkColor color) {
if (enabled_color_set_ && requested_enabled_color_ == color)
return;
enabled_color_set_ = true;
requested_enabled_color_ = color;
enabled_color_id_.reset();
RecalculateColors();
OnPropertyChanged(&requested_enabled_color_, kPropertyEffectsPaint);
}
absl::optional<ui::ColorId> Label::GetEnabledColorId() const {
return enabled_color_id_;
}
void Label::SetEnabledColorId(absl::optional<ui::ColorId> enabled_color_id) {
if (enabled_color_id_ == enabled_color_id)
return;
enabled_color_id_ = enabled_color_id;
if (GetWidget()) {
UpdateColorsFromTheme();
enabled_color_set_ = true;
}
OnPropertyChanged(&enabled_color_id_, kPropertyEffectsPaint);
}
SkColor Label::GetBackgroundColor() const {
return background_color_;
}
void Label::SetBackgroundColor(SkColor color) {
if (background_color_set_ && background_color_ == color)
return;
background_color_ = color;
background_color_set_ = true;
if (GetWidget()) {
UpdateColorsFromTheme();
} else {
RecalculateColors();
}
OnPropertyChanged(&background_color_, kPropertyEffectsPaint);
}
void Label::SetBackgroundColorId(
absl::optional<ui::ColorId> background_color_id) {
if (background_color_id_ == background_color_id)
return;
background_color_id_ = background_color_id;
if (GetWidget()) {
UpdateColorsFromTheme();
}
OnPropertyChanged(&background_color_id_, kPropertyEffectsPaint);
}
SkColor Label::GetSelectionTextColor() const {
return actual_selection_text_color_;
}
void Label::SetSelectionTextColor(SkColor color) {
if (selection_text_color_set_ && requested_selection_text_color_ == color)
return;
requested_selection_text_color_ = color;
selection_text_color_set_ = true;
RecalculateColors();
OnPropertyChanged(&requested_selection_text_color_, kPropertyEffectsPaint);
}
SkColor Label::GetSelectionBackgroundColor() const {
return selection_background_color_;
}
void Label::SetSelectionBackgroundColor(SkColor color) {
if (selection_background_color_set_ && selection_background_color_ == color)
return;
selection_background_color_ = color;
selection_background_color_set_ = true;
RecalculateColors();
OnPropertyChanged(&selection_background_color_, kPropertyEffectsPaint);
}
const gfx::ShadowValues& Label::GetShadows() const {
return full_text_->shadows();
}
void Label::SetShadows(const gfx::ShadowValues& shadows) {
if (full_text_->shadows() == shadows)
return;
full_text_->set_shadows(shadows);
ClearDisplayText();
OnPropertyChanged(&full_text_ + kLabelShadows,
kPropertyEffectsPreferredSizeChanged);
}
bool Label::GetSubpixelRenderingEnabled() const {
return subpixel_rendering_enabled_;
}
void Label::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) {
if (subpixel_rendering_enabled_ == subpixel_rendering_enabled)
return;
subpixel_rendering_enabled_ = subpixel_rendering_enabled;
ApplyTextColors();
OnPropertyChanged(&subpixel_rendering_enabled_, kPropertyEffectsPaint);
}
bool Label::GetSkipSubpixelRenderingOpacityCheck() const {
return skip_subpixel_rendering_opacity_check_;
}
void Label::SetSkipSubpixelRenderingOpacityCheck(
bool skip_subpixel_rendering_opacity_check) {
if (skip_subpixel_rendering_opacity_check_ ==
skip_subpixel_rendering_opacity_check) {
return;
}
skip_subpixel_rendering_opacity_check_ =
skip_subpixel_rendering_opacity_check;
OnPropertyChanged(&skip_subpixel_rendering_opacity_check_,
kPropertyEffectsNone);
}
gfx::HorizontalAlignment Label::GetHorizontalAlignment() const {
return full_text_->horizontal_alignment();
}
void Label::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) {
alignment = gfx::MaybeFlipForRTL(alignment);
if (GetHorizontalAlignment() == alignment)
return;
full_text_->SetHorizontalAlignment(alignment);
ClearDisplayText();
OnPropertyChanged(&full_text_ + kLabelHorizontalAlignment,
kPropertyEffectsPaint);
}
gfx::VerticalAlignment Label::GetVerticalAlignment() const {
return full_text_->vertical_alignment();
}
void Label::SetVerticalAlignment(gfx::VerticalAlignment alignment) {
if (GetVerticalAlignment() == alignment)
return;
full_text_->SetVerticalAlignment(alignment);
ClearDisplayText();
OnPropertyChanged(&full_text_ + kLabelVerticalAlignment,
kPropertyEffectsPaint);
}
int Label::GetLineHeight() const {
// TODO(pkasting): If we can replace SetFontList() with context/style setter
// calls, we can eliminate the reference to font_list().GetHeight() here.
return line_height_.value_or(
std::max(style::GetLineHeight(text_context_, text_style_),
font_list().GetHeight()));
}
void Label::SetLineHeight(int line_height) {
if (line_height_ == line_height)
return;
line_height_ = line_height;
full_text_->SetMinLineHeight(line_height);
ClearDisplayText();
OnPropertyChanged(&full_text_ + kLabelLineHeight,
kPropertyEffectsPreferredSizeChanged);
}
bool Label::GetMultiLine() const {
return multi_line_;
}
void Label::SetMultiLine(bool multi_line) {
DCHECK(!multi_line || (elide_behavior_ == gfx::ELIDE_TAIL ||
elide_behavior_ == gfx::NO_ELIDE));
if (this->GetMultiLine() == multi_line)
return;
multi_line_ = multi_line;
// `max_width_` and `max_width_single_line_` are mutually exclusive.
max_width_single_line_ = 0;
full_text_->SetMultiline(multi_line);
ClearDisplayText();
OnPropertyChanged(&multi_line_, kPropertyEffectsPreferredSizeChanged);
}
size_t Label::GetMaxLines() const {
return max_lines_;
}
void Label::SetMaxLines(size_t max_lines) {
if (max_lines_ == max_lines)
return;
max_lines_ = max_lines;
OnPropertyChanged(&max_lines_, kPropertyEffectsPreferredSizeChanged);
}
bool Label::GetObscured() const {
return full_text_->obscured();
}
void Label::SetObscured(bool obscured) {
if (this->GetObscured() == obscured)
return;
full_text_->SetObscured(obscured);
ClearDisplayText();
if (obscured)
SetSelectable(false);
OnPropertyChanged(&full_text_ + kLabelObscured,
kPropertyEffectsPreferredSizeChanged);
}
bool Label::IsDisplayTextTruncated() const {
MaybeBuildDisplayText();
if (!full_text_ || full_text_->text().empty())
return false;
auto text_bounds = GetTextBounds();
return (display_text_ &&
display_text_->text() != display_text_->GetDisplayText()) ||
text_bounds.width() > GetContentsBounds().width() ||
text_bounds.height() > GetContentsBounds().height();
}
bool Label::GetAllowCharacterBreak() const {
return full_text_->word_wrap_behavior() == gfx::WRAP_LONG_WORDS;
}
void Label::SetAllowCharacterBreak(bool allow_character_break) {
const gfx::WordWrapBehavior behavior =
allow_character_break ? gfx::WRAP_LONG_WORDS : gfx::TRUNCATE_LONG_WORDS;
if (full_text_->word_wrap_behavior() == behavior)
return;
full_text_->SetWordWrapBehavior(behavior);
ClearDisplayText();
OnPropertyChanged(&full_text_ + kLabelAllowCharacterBreak,
kPropertyEffectsPreferredSizeChanged);
}
size_t Label::GetTextIndexOfLine(size_t line) const {
return full_text_->GetTextIndexOfLine(line);
}
void Label::SetTruncateLength(size_t truncate_length) {
return full_text_->set_truncate_length(truncate_length);
}
gfx::ElideBehavior Label::GetElideBehavior() const {
return elide_behavior_;
}
void Label::SetElideBehavior(gfx::ElideBehavior elide_behavior) {
DCHECK(!GetMultiLine() || (elide_behavior == gfx::ELIDE_TAIL ||
elide_behavior == gfx::NO_ELIDE));
if (elide_behavior_ == elide_behavior)
return;
elide_behavior_ = elide_behavior;
UpdateFullTextElideBehavior();
ClearDisplayText();
OnPropertyChanged(&elide_behavior_, kPropertyEffectsPreferredSizeChanged);
}
void Label::SetDrawStringsFlags(int flags) {
if (draw_strings_flags_ == flags)
return;
draw_strings_flags_ = flags;
full_text_->SetDrawStringsFlags(draw_strings_flags_);
OnPropertyChanged(&full_text_ + kLabelDrawStringsFlags,
kPropertyEffectsPreferredSizeChanged);
}
std::u16string Label::GetTooltipText() const {
return tooltip_text_;
}
void Label::SetTooltipText(const std::u16string& tooltip_text) {
DCHECK(handles_tooltips_);
if (tooltip_text_ == tooltip_text)
return;
tooltip_text_ = tooltip_text;
TooltipTextChanged();
OnPropertyChanged(&tooltip_text_, kPropertyEffectsNone);
}
bool Label::GetHandlesTooltips() const {
return handles_tooltips_;
}
void Label::SetHandlesTooltips(bool enabled) {
if (handles_tooltips_ == enabled)
return;
handles_tooltips_ = enabled;
OnPropertyChanged(&handles_tooltips_, kPropertyEffectsNone);
}
void Label::SizeToFit(int fixed_width) {
DCHECK(GetMultiLine());
DCHECK_EQ(0, max_width_);
fixed_width_ = fixed_width;
SizeToPreferredSize();
}
int Label::GetMaximumWidth() const {
return max_width_;
}
void Label::SetMaximumWidth(int max_width) {
DCHECK(GetMultiLine());
DCHECK_EQ(0, fixed_width_);
if (max_width_ == max_width)
return;
max_width_ = max_width;
OnPropertyChanged(&max_width_, kPropertyEffectsPreferredSizeChanged);
}
void Label::SetMaximumWidthSingleLine(int max_width) {
DCHECK(!GetMultiLine());
if (max_width_single_line_ == max_width)
return;
max_width_single_line_ = max_width;
UpdateFullTextElideBehavior();
OnPropertyChanged(&max_width_single_line_,
kPropertyEffectsPreferredSizeChanged);
}
bool Label::GetCollapseWhenHidden() const {
return collapse_when_hidden_;
}
void Label::SetCollapseWhenHidden(bool value) {
if (collapse_when_hidden_ == value)
return;
collapse_when_hidden_ = value;
OnPropertyChanged(&collapse_when_hidden_,
kPropertyEffectsPreferredSizeChanged);
}
size_t Label::GetRequiredLines() const {
return full_text_->GetNumLines();
}
std::u16string Label::GetDisplayTextForTesting() {
MaybeBuildDisplayText();
return display_text_ ? display_text_->GetDisplayText() : std::u16string();
}
base::i18n::TextDirection Label::GetTextDirectionForTesting() {
return full_text_->GetDisplayTextDirection();
}
bool Label::IsSelectionSupported() const {
return !GetObscured();
}
bool Label::GetSelectable() const {
return !!selection_controller_;
}
bool Label::SetSelectable(bool value) {
if (value == GetSelectable())
return true;
if (!value) {
ClearSelection();
stored_selection_range_ = gfx::Range::InvalidRange();
selection_controller_.reset();
return true;
}
DCHECK(!stored_selection_range_.IsValid());
if (!IsSelectionSupported())
return false;
selection_controller_ = std::make_unique<SelectionController>(this);
return true;
}
bool Label::HasSelection() const {
const gfx::RenderText* render_text = GetRenderTextForSelectionController();
return render_text ? !render_text->selection().is_empty() : false;
}
void Label::SelectAll() {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
if (!render_text)
return;
render_text->SelectAll(false);
SchedulePaint();
}
void Label::ClearSelection() {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
if (!render_text)
return;
render_text->ClearSelection();
SchedulePaint();
}
void Label::SelectRange(const gfx::Range& range) {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
if (render_text && render_text->SelectRange(range))
SchedulePaint();
}
std::vector<gfx::Rect> Label::GetSubstringBounds(const gfx::Range& range) {
auto substring_bounds = full_text_->GetSubstringBounds(range);
for (auto& bound : substring_bounds) {
bound.Offset(GetInsets().left(), GetInsets().top());
}
return substring_bounds;
}
base::CallbackListSubscription Label::AddTextChangedCallback(
views::PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&full_text_ + kLabelText,
std::move(callback));
}
int Label::GetBaseline() const {
return GetInsets().top() + font_list().GetBaseline();
}
gfx::Size Label::CalculatePreferredSize() const {
return CalculatePreferredSize({width(), {}});
}
gfx::Size Label::CalculatePreferredSize(
const SizeBounds& available_size) const {
// Return a size of (0, 0) if the label is not visible and if the
// |collapse_when_hidden_| flag is set.
// TODO(munjal): This logic probably belongs to the View class. But for now,
// put it here since putting it in View class means all inheriting classes
// need to respect the |collapse_when_hidden_| flag.
if (!GetVisible() && collapse_when_hidden_)
return gfx::Size();
if (GetMultiLine() && fixed_width_ != 0 && !GetText().empty())
return gfx::Size(fixed_width_, GetHeightForWidth(fixed_width_));
gfx::Size size(GetBoundedTextSize(available_size));
const gfx::Insets insets = GetInsets();
size.Enlarge(insets.width(), insets.height());
if (GetMultiLine() && max_width_ != 0 && max_width_ < size.width())
return gfx::Size(max_width_, GetHeightForWidth(max_width_));
if (GetMultiLine() && GetMaxLines() > 0)
return gfx::Size(size.width(), GetHeightForWidth(size.width()));
return size;
}
gfx::Size Label::GetMinimumSize() const {
if (!GetVisible() && collapse_when_hidden_)
return gfx::Size();
// Always reserve vertical space for at least one line.
gfx::Size size(0, GetLineHeight());
if (elide_behavior_ == gfx::ELIDE_HEAD ||
elide_behavior_ == gfx::ELIDE_MIDDLE ||
elide_behavior_ == gfx::ELIDE_TAIL ||
elide_behavior_ == gfx::ELIDE_EMAIL) {
size.set_width(gfx::Canvas::GetStringWidth(
std::u16string(gfx::kEllipsisUTF16), font_list()));
}
if (!GetMultiLine()) {
if (elide_behavior_ == gfx::NO_ELIDE) {
// If elision is disabled on single-line Labels, use text size as minimum.
// This is OK because clients can use |gfx::ElideBehavior::TRUNCATE|
// to get a non-eliding Label that should size itself less aggressively.
size.SetToMax(GetTextSize());
} else {
size.SetToMin(GetTextSize());
}
}
size.Enlarge(GetInsets().width(), GetInsets().height());
return size;
}
int Label::GetHeightForWidth(int w) const {
if (!GetVisible() && collapse_when_hidden_)
return 0;
w -= GetInsets().width();
int height = 0;
int base_line_height = GetLineHeight();
if (!GetMultiLine() || GetText().empty() || w < 0) {
height = base_line_height;
} else if (w == 0) {
height =
std::max(base::checked_cast<int>(GetMaxLines()), 1) * base_line_height;
} else {
// SetDisplayRect() has a side effect for later calls of GetStringSize().
// Be careful to invoke full_text_->SetDisplayRect(gfx::Rect()) to
// cancel this effect before the next time GetStringSize() is called.
// It's beneficial not to cancel here, considering that some layout managers
// invoke GetHeightForWidth() for the same width multiple times and
// |full_text_| can cache the height.
full_text_->SetDisplayRect(gfx::Rect(0, 0, w, 0));
int string_height = full_text_->GetStringSize().height();
// Cap the number of lines to GetMaxLines() if that's set.
height = GetMaxLines() > 0
? std::min(base::checked_cast<int>(GetMaxLines()) *
base_line_height,
string_height)
: string_height;
}
height -= gfx::ShadowValue::GetMargin(full_text_->shadows()).height();
return height + GetInsets().height();
}
View* Label::GetTooltipHandlerForPoint(const gfx::Point& point) {
if (!handles_tooltips_ ||
(tooltip_text_.empty() && !ShouldShowDefaultTooltip())) {
return nullptr;
}
return HitTestPoint(point) ? this : nullptr;
}
bool Label::GetCanProcessEventsWithinSubtree() const {
return !!GetRenderTextForSelectionController();
}
WordLookupClient* Label::GetWordLookupClient() {
return this;
}
std::u16string Label::GetTooltipText(const gfx::Point& p) const {
if (handles_tooltips_) {
if (!tooltip_text_.empty())
return tooltip_text_;
if (ShouldShowDefaultTooltip())
return full_text_->GetDisplayText();
}
return std::u16string();
}
std::unique_ptr<gfx::RenderText> Label::CreateRenderText() const {
// Multi-line labels only support NO_ELIDE and ELIDE_TAIL for now.
// TODO(warx): Investigate more elide text support.
gfx::ElideBehavior elide_behavior =
GetMultiLine() && (elide_behavior_ != gfx::NO_ELIDE) ? gfx::ELIDE_TAIL
: elide_behavior_;
std::unique_ptr<gfx::RenderText> render_text =
full_text_->CreateInstanceOfSameStyle(GetText());
render_text->SetHorizontalAlignment(GetHorizontalAlignment());
render_text->SetVerticalAlignment(GetVerticalAlignment());
render_text->SetElideBehavior(elide_behavior);
render_text->SetObscured(GetObscured());
render_text->SetMinLineHeight(GetLineHeight());
render_text->set_shadows(GetShadows());
const bool multiline = GetMultiLine();
render_text->SetMultiline(multiline);
render_text->SetMaxLines(multiline ? GetMaxLines() : size_t{0});
render_text->SetWordWrapBehavior(full_text_->word_wrap_behavior());
// Setup render text for selection controller.
if (GetSelectable()) {
render_text->set_focused(HasFocus());
if (stored_selection_range_.IsValid())
render_text->SelectRange(stored_selection_range_);
}
if (draw_strings_flags_ != 0) {
auto text_str = GetText();
gfx::Range range = StripAcceleratorChars(draw_strings_flags_, &text_str);
render_text->SetText(text_str);
if (range.IsValid()) {
render_text->SetDisplayRect(bounds());
render_text->ApplyStyle(gfx::TEXT_STYLE_UNDERLINE, true, range);
}
}
return render_text;
}
gfx::Rect Label::GetTextBounds() const {
MaybeBuildDisplayText();
if (!display_text_)
return gfx::Rect(GetTextSize());
return gfx::Rect(gfx::Point() + display_text_->GetLineOffset(0),
display_text_->GetStringSize());
}
int Label::GetFontListY() const {
MaybeBuildDisplayText();
if (!display_text_)
return 0;
return GetInsets().top() + display_text_->GetBaseline() -
font_list().GetBaseline();
}
void Label::PaintText(gfx::Canvas* canvas) {
MaybeBuildDisplayText();
if (display_text_)
display_text_->Draw(canvas);
#if DCHECK_IS_ON() && !BUILDFLAG(IS_CHROMEOS_ASH) && \
!BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(crbug.com/1139395): Enable this DCHECK on ChromeOS and LaCrOS by
// fixing either this check (to correctly idenfify more paints-on-opaque
// cases), refactoring parents to use background() or by fixing
// subpixel-rendering issues that the DCHECK detects.
if (!display_text_ || display_text_->subpixel_rendering_suppressed() ||
skip_subpixel_rendering_opacity_check_) {
return;
}
// Ensure that, if we're using subpixel rendering, we're painted to an opaque
// region. Subpixel rendering will sample from the r,g,b color channels of the
// canvas. These values are incorrect when sampling from transparent pixels.
// Note that these checks may need to be amended for other methods of painting
// opaquely underneath the Label. For now, individual cases can skip this
// DCHECK by calling Label::SetSkipSubpixelRenderingOpacityCheck().
for (View* view = this; view; view = view->parent()) {
// This is our approximation of being painted on an opaque region. If any
// parent has an opaque background we assume that that background covers the
// text bounds. This is not necessarily true as the background could be
// inset from the parent bounds, and get_color() does not imply that all of
// the background is painted with the same opaque color.
if (view->background() && IsOpaque(view->background()->get_color()))
break;
if (view->layer()) {
// If we aren't painted to an opaque background, we must paint to an
// opaque layer.
DCHECK(view->layer()->fills_bounds_opaquely());
break;
}
}
#endif
}
void Label::OnBoundsChanged(const gfx::Rect& previous_bounds) {
ClearDisplayText();
}
void Label::OnPaint(gfx::Canvas* canvas) {
View::OnPaint(canvas);
PaintText(canvas);
}
void Label::OnThemeChanged() {
View::OnThemeChanged();
UpdateColorsFromTheme();
}
ui::Cursor Label::GetCursor(const ui::MouseEvent& event) {
return GetRenderTextForSelectionController() ? ui::mojom::CursorType::kIBeam
: ui::Cursor();
}
void Label::OnFocus() {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
if (render_text) {
render_text->set_focused(true);
SchedulePaint();
}
View::OnFocus();
}
void Label::OnBlur() {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
if (render_text) {
render_text->set_focused(false);
SchedulePaint();
}
View::OnBlur();
}
bool Label::OnMousePressed(const ui::MouseEvent& event) {
if (!GetRenderTextForSelectionController())
return false;
const bool had_focus = HasFocus();
// RequestFocus() won't work when the label has FocusBehavior::NEVER. Hence
// explicitly set the focused view.
// TODO(karandeepb): If a widget with a label having FocusBehavior::NEVER as
// the currently focused view (due to selection) was to lose focus, focus
// won't be restored to the label (and hence a text selection won't be drawn)
// when the widget gets focus again. Fix this.
// Tracked in https://crbug.com/630365.
if ((event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
GetFocusManager() && !had_focus) {
GetFocusManager()->SetFocusedView(this);
}
if (ui::Clipboard::IsSupportedClipboardBuffer(
ui::ClipboardBuffer::kSelection)) {
if (event.IsOnlyMiddleMouseButton() && GetFocusManager() && !had_focus)
GetFocusManager()->SetFocusedView(this);
}
return selection_controller_->OnMousePressed(
event, false,
had_focus
? SelectionController::InitialFocusStateOnMousePress::kFocused
: SelectionController::InitialFocusStateOnMousePress::kUnFocused);
}
bool Label::OnMouseDragged(const ui::MouseEvent& event) {
if (!GetRenderTextForSelectionController())
return false;
return selection_controller_->OnMouseDragged(event);
}
void Label::OnMouseReleased(const ui::MouseEvent& event) {
if (!GetRenderTextForSelectionController())
return;
selection_controller_->OnMouseReleased(event);
}
void Label::OnMouseCaptureLost() {
if (!GetRenderTextForSelectionController())
return;
selection_controller_->OnMouseCaptureLost();
}
bool Label::OnKeyPressed(const ui::KeyEvent& event) {
if (!GetRenderTextForSelectionController())
return false;
const bool shift = event.IsShiftDown();
const bool control = event.IsControlDown();
const bool alt = event.IsAltDown() || event.IsAltGrDown();
switch (event.key_code()) {
case ui::VKEY_C:
if (control && !alt && HasSelection()) {
CopyToClipboard();
return true;
}
break;
case ui::VKEY_INSERT:
if (control && !shift && HasSelection()) {
CopyToClipboard();
return true;
}
break;
case ui::VKEY_A:
if (control && !alt && !GetText().empty()) {
SelectAll();
DCHECK(HasSelection());
UpdateSelectionClipboard();
return true;
}
break;
default:
break;
}
return false;
}
bool Label::AcceleratorPressed(const ui::Accelerator& accelerator) {
// Allow the "Copy" action from the Chrome menu to be invoked. E.g., if a user
// selects a Label on a web modal dialog. "Select All" doesn't appear in the
// Chrome menu so isn't handled here.
if (accelerator.key_code() == ui::VKEY_C && accelerator.IsCtrlDown()) {
CopyToClipboard();
return true;
}
return false;
}
bool Label::CanHandleAccelerators() const {
// Focus needs to be checked since the accelerator for the Copy command from
// the Chrome menu should only be handled when the current view has focus. See
// related comment in BrowserView::CutCopyPaste.
return HasFocus() && GetRenderTextForSelectionController() &&
View::CanHandleAccelerators();
}
void Label::OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
View::OnDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
// When the device scale factor is changed, some font rendering parameters is
// changed (especially, hinting). The bounding box of the text has to be
// re-computed based on the new parameters. See crbug.com/441439
PreferredSizeChanged();
}
void Label::VisibilityChanged(View* starting_from, bool is_visible) {
if (!is_visible)
ClearDisplayText();
}
void Label::ShowContextMenuForViewImpl(View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) {
if (!GetRenderTextForSelectionController())
return;
context_menu_runner_ = std::make_unique<MenuRunner>(
&context_menu_contents_,
MenuRunner::HAS_MNEMONICS | MenuRunner::CONTEXT_MENU);
context_menu_runner_->RunMenuAt(GetWidget(), nullptr,
gfx::Rect(point, gfx::Size()),
MenuAnchorPosition::kTopLeft, source_type);
}
bool Label::GetWordLookupDataAtPoint(const gfx::Point& point,
gfx::DecoratedText* decorated_word,
gfx::Point* baseline_point) {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
return render_text ? render_text->GetWordLookupDataAtPoint(
point, decorated_word, baseline_point)
: false;
}
bool Label::GetWordLookupDataFromSelection(gfx::DecoratedText* decorated_text,
gfx::Point* baseline_point) {
gfx::RenderText* render_text = GetRenderTextForSelectionController();
return render_text
? render_text->GetLookupDataForRange(
render_text->selection(), decorated_text, baseline_point)
: false;
}
gfx::RenderText* Label::GetRenderTextForSelectionController() {
return const_cast<gfx::RenderText*>(
static_cast<const Label*>(this)->GetRenderTextForSelectionController());
}
bool Label::IsReadOnly() const {
return true;
}
bool Label::SupportsDrag() const {
// TODO(crbug.com/661379): Labels should support dragging selected text.
return false;
}
bool Label::HasTextBeingDragged() const {
return false;
}
void Label::SetTextBeingDragged(bool value) {
NOTREACHED_NORETURN();
}
int Label::GetViewHeight() const {
return height();
}
int Label::GetViewWidth() const {
return width();
}
int Label::GetDragSelectionDelay() const {
// Labels don't need to use a repeating timer to update the drag selection.
// Since the cursor is disabled for labels, a selection outside the display
// area won't change the text in the display area. It is expected that all the
// text will fit in the display area for labels anyway.
return 0;
}
void Label::OnBeforePointerAction() {}
void Label::OnAfterPointerAction(bool text_changed, bool selection_changed) {
DCHECK(!text_changed);
if (selection_changed)
SchedulePaint();
}
bool Label::PasteSelectionClipboard() {
NOTREACHED_NORETURN();
}
void Label::UpdateSelectionClipboard() {
if (ui::Clipboard::IsSupportedClipboardBuffer(
ui::ClipboardBuffer::kSelection)) {
if (!GetObscured()) {
ui::ScopedClipboardWriter(ui::ClipboardBuffer::kSelection)
.WriteText(GetSelectedText());
}
}
}
bool Label::IsCommandIdChecked(int command_id) const {
return true;
}
bool Label::IsCommandIdEnabled(int command_id) const {
switch (command_id) {
case MenuCommands::kCopy:
return HasSelection() && !GetObscured();
case MenuCommands::kSelectAll:
return GetRenderTextForSelectionController() && !GetText().empty();
}
return false;
}
void Label::ExecuteCommand(int command_id, int event_flags) {
switch (command_id) {
case MenuCommands::kCopy:
CopyToClipboard();
break;
case MenuCommands::kSelectAll:
SelectAll();
DCHECK(HasSelection());
UpdateSelectionClipboard();
break;
default:
NOTREACHED_NORETURN();
}
}
bool Label::GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) const {
switch (command_id) {
case MenuCommands::kCopy:
*accelerator = ui::Accelerator(ui::VKEY_C, ui::EF_CONTROL_DOWN);
return true;
case MenuCommands::kSelectAll:
*accelerator = ui::Accelerator(ui::VKEY_A, ui::EF_CONTROL_DOWN);
return true;
default:
return false;
}
}
const gfx::RenderText* Label::GetRenderTextForSelectionController() const {
if (!GetSelectable())
return nullptr;
MaybeBuildDisplayText();
// This may be null when the content bounds of the view are empty.
return display_text_.get();
}
void Label::Init(const std::u16string& text,
const gfx::FontList& font_list,
gfx::DirectionalityMode directionality_mode) {
full_text_ = gfx::RenderText::CreateRenderText();
full_text_->SetHorizontalAlignment(gfx::ALIGN_CENTER);
full_text_->SetFontList(font_list);
full_text_->SetCursorEnabled(false);
full_text_->SetWordWrapBehavior(gfx::TRUNCATE_LONG_WORDS);
full_text_->SetMinLineHeight(GetLineHeight());
UpdateFullTextElideBehavior();
full_text_->SetDirectionalityMode(directionality_mode);
SetAccessibilityProperties(text_context_ == style::CONTEXT_DIALOG_TITLE
? ax::mojom::Role::kTitleBar
: ax::mojom::Role::kStaticText,
text);
SetText(text);
// Only selectable labels will get requests to show the context menu, due to
// GetCanProcessEventsWithinSubtree().
BuildContextMenuContents();
set_context_menu_controller(this);
// This allows the BrowserView to pass the copy command from the Chrome menu
// to the Label.
AddAccelerator(ui::Accelerator(ui::VKEY_C, ui::EF_CONTROL_DOWN));
}
void Label::MaybeBuildDisplayText() const {
if (display_text_)
return;
gfx::Rect rect = GetContentsBounds();
if (rect.IsEmpty())
return;
rect.Inset(-gfx::ShadowValue::GetMargin(GetShadows()));
display_text_ = CreateRenderText();
display_text_->SetDisplayRect(rect);
stored_selection_range_ = gfx::Range::InvalidRange();
ApplyTextColors();
}
gfx::Size Label::GetTextSize() const {
return GetBoundedTextSize({width(), {}});
}
gfx::Size Label::GetBoundedTextSize(const SizeBounds& available_size) const {
gfx::Size size;
if (GetText().empty()) {
size = gfx::Size(0, GetLineHeight());
} else if (max_width_single_line_ > 0) {
DCHECK(!GetMultiLine());
// Enable eliding during text width calculation. This allows the RenderText
// to report an accurate width given the constraints and how it determines
// to elide the text. If we simply clamp the width to the max after the
// fact, then there may be some empty space left over *after* an ellipsis.
// TODO(kerenzhu): `available_size` should be respected, but doing so will
// break tests. Fix that.
full_text_->SetDisplayRect(
gfx::Rect(0, 0, max_width_single_line_ - GetInsets().width(), 0));
size = full_text_->GetStringSize();
} else {
const int width = available_size.width().is_bounded()
? available_size.width().value()
: 0;
// SetDisplayRect() has side-effect. The text height will change to respect
// width.
// TODO(crbug.com/1347330): `width` should respect insets, but doing so
// will break LabelTest.MultiLineSizing. Fix that.
full_text_->SetDisplayRect(gfx::Rect(0, 0, width, 0));
size = full_text_->GetStringSize();
}
const gfx::Insets shadow_margin = -gfx::ShadowValue::GetMargin(GetShadows());
size.Enlarge(shadow_margin.width(), shadow_margin.height());
return size;
}
SkColor Label::GetForegroundColor(SkColor foreground,
SkColor background) const {
return (auto_color_readability_enabled_ && IsOpaque(background))
? color_utils::BlendForMinContrast(foreground, background).color
: foreground;
}
void Label::RecalculateColors() {
actual_enabled_color_ =
GetForegroundColor(requested_enabled_color_, background_color_);
// Using GetResultingPaintColor() here allows non-opaque selection backgrounds
// to still participate in auto color readability, assuming
// |background_color_| is itself opaque.
actual_selection_text_color_ =
GetForegroundColor(requested_selection_text_color_,
color_utils::GetResultingPaintColor(
selection_background_color_, background_color_));
ApplyTextColors();
SchedulePaint();
}
void Label::ApplyTextColors() const {
if (!display_text_)
return;
display_text_->SetColor(actual_enabled_color_);
display_text_->set_selection_color(actual_selection_text_color_);
display_text_->set_selection_background_focused_color(
selection_background_color_);
const bool subpixel_rendering_enabled =
subpixel_rendering_enabled_ && IsOpaque(background_color_);
display_text_->set_subpixel_rendering_suppressed(!subpixel_rendering_enabled);
}
void Label::UpdateColorsFromTheme() {
ui::ColorProvider* color_provider = GetColorProvider();
if (enabled_color_id_.has_value()) {
requested_enabled_color_ = color_provider->GetColor(*enabled_color_id_);
} else if (!enabled_color_set_) {
const absl::optional<SkColor> cascading_color =
GetCascadingProperty(this, kCascadingLabelEnabledColor);
requested_enabled_color_ =
cascading_color.value_or(GetColorProvider()->GetColor(
style::GetColorId(text_context_, text_style_)));
}
if (background_color_id_.has_value()) {
background_color_ = color_provider->GetColor(*background_color_id_);
} else if (!background_color_set_) {
background_color_ = color_provider->GetColor(ui::kColorDialogBackground);
}
if (!selection_text_color_set_) {
requested_selection_text_color_ =
color_provider->GetColor(ui::kColorLabelSelectionForeground);
}
if (!selection_background_color_set_) {
selection_background_color_ =
color_provider->GetColor(ui::kColorLabelSelectionBackground);
}
RecalculateColors();
}
bool Label::ShouldShowDefaultTooltip() const {
const gfx::Size text_size = GetTextSize();
const gfx::Size size = GetContentsBounds().size();
return !GetObscured() &&
(text_size.width() > size.width() ||
(GetMultiLine() && text_size.height() > size.height()));
}
void Label::ClearDisplayText() {
// The HasSelection() call below will build |display_text_| in case it is
// empty. Return early to avoid this.
if (!display_text_)
return;
// Persist the selection range if there is an active selection.
if (HasSelection()) {
stored_selection_range_ =
GetRenderTextForSelectionController()->selection();
}
display_text_ = nullptr;
SchedulePaint();
}
std::u16string Label::GetSelectedText() const {
const gfx::RenderText* render_text = GetRenderTextForSelectionController();
return render_text ? render_text->GetTextFromRange(render_text->selection())
: std::u16string();
}
void Label::CopyToClipboard() {
if (!HasSelection() || GetObscured())
return;
ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste)
.WriteText(GetSelectedText());
}
void Label::BuildContextMenuContents() {
context_menu_contents_.AddItemWithStringId(MenuCommands::kCopy, IDS_APP_COPY);
context_menu_contents_.AddItemWithStringId(MenuCommands::kSelectAll,
IDS_APP_SELECT_ALL);
}
void Label::UpdateFullTextElideBehavior() {
// In single line mode when a max width has been set, |full_text_| uses
// elision to properly calculate the text size. Otherwise, it is not elided.
full_text_->SetElideBehavior(max_width_single_line_ > 0 ? elide_behavior_
: gfx::NO_ELIDE);
}
BEGIN_METADATA(Label, View)
ADD_PROPERTY_METADATA(std::u16string, Text)
ADD_PROPERTY_METADATA(int, TextContext)
ADD_PROPERTY_METADATA(int, TextStyle)
ADD_PROPERTY_METADATA(bool, AutoColorReadabilityEnabled)
ADD_PROPERTY_METADATA(SkColor, EnabledColor, ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(gfx::ElideBehavior, ElideBehavior)
ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(SkColor,
SelectionTextColor,
ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(SkColor,
SelectionBackgroundColor,
ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(bool, SubpixelRenderingEnabled)
ADD_PROPERTY_METADATA(bool, SkipSubpixelRenderingOpacityCheck)
ADD_PROPERTY_METADATA(gfx::ShadowValues, Shadows)
ADD_PROPERTY_METADATA(gfx::HorizontalAlignment, HorizontalAlignment)
ADD_PROPERTY_METADATA(gfx::VerticalAlignment, VerticalAlignment)
ADD_PROPERTY_METADATA(int, LineHeight)
ADD_PROPERTY_METADATA(bool, MultiLine)
ADD_PROPERTY_METADATA(size_t, MaxLines)
ADD_PROPERTY_METADATA(bool, Obscured)
ADD_PROPERTY_METADATA(bool, AllowCharacterBreak)
ADD_PROPERTY_METADATA(std::u16string, TooltipText)
ADD_PROPERTY_METADATA(bool, HandlesTooltips)
ADD_PROPERTY_METADATA(bool, CollapseWhenHidden)
ADD_PROPERTY_METADATA(int, MaximumWidth)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/label.cc | C++ | unknown | 44,776 |
// 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.
#ifndef UI_VIEWS_CONTROLS_LABEL_H_
#define UI_VIEWS_CONTROLS_LABEL_H_
#include <memory>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/color/color_id.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/render_text.h"
#include "ui/gfx/text_constants.h"
#include "ui/views/cascading_property.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/selection_controller_delegate.h"
#include "ui/views/style/typography.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
#include "ui/views/word_lookup_client.h"
namespace views {
class LabelSelectionTest;
class MenuRunner;
class SelectionController;
VIEWS_EXPORT extern const ui::ClassProperty<CascadingProperty<SkColor>*>* const
kCascadingLabelEnabledColor;
// A view subclass that can display a string.
class VIEWS_EXPORT Label : public View,
public ContextMenuController,
public WordLookupClient,
public SelectionControllerDelegate,
public ui::SimpleMenuModel::Delegate {
public:
METADATA_HEADER(Label);
enum MenuCommands {
kCopy = 1,
kSelectAll,
kLastCommandId = kSelectAll,
};
// Helper to construct a Label that doesn't use the views typography spec.
// Using this causes Label to obtain colors from ui::NativeTheme and line
// spacing from gfx::FontList::GetHeight().
// TODO(tapted): Audit users of this class when MD is default. Then add
// foreground/background colors, line spacing and everything else that
// views::TextContext abstracts away so the separate setters can be removed.
struct CustomFont {
// TODO(tapted): Change this to a size delta and font weight since that's
// typically all the callers really care about, and would allow Label to
// guarantee caching of the FontList in ResourceBundle.
//
// Exclude from `raw_ref` rewriter because there are usages (e.g.
// `indexed_suggestion_candidate_button.cc` that attempt to bind
// temporaries (`T&&`) to `font_list`, which `raw_ref` forbids.
RAW_PTR_EXCLUSION const gfx::FontList& font_list;
};
// Create Labels with style::CONTEXT_CONTROL_LABEL and style::STYLE_PRIMARY.
// TODO(tapted): Remove these. Callers must specify a context or use the
// constructor taking a CustomFont.
Label();
explicit Label(const std::u16string& text);
// Construct a Label in the given |text_context|. The |text_style| can change
// later, so provide a default. The |text_context| is fixed.
// By default text directionality will be derived from the label text, however
// it can be overriden with |directionality_mode|.
Label(const std::u16string& text,
int text_context,
int text_style = style::STYLE_PRIMARY,
gfx::DirectionalityMode directionality_mode =
gfx::DirectionalityMode::DIRECTIONALITY_FROM_TEXT);
// Construct a Label with the given |font| description.
Label(const std::u16string& text, const CustomFont& font);
Label(const Label&) = delete;
Label& operator=(const Label&) = delete;
~Label() override;
static const gfx::FontList& GetDefaultFontList();
// Gets or sets the fonts used by this label.
const gfx::FontList& font_list() const { return full_text_->font_list(); }
// TODO(tapted): Replace this with a private method, e.g., OnFontChanged().
virtual void SetFontList(const gfx::FontList& font_list);
// Get or set the label text.
const std::u16string& GetText() const;
virtual void SetText(const std::u16string& text);
void AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) override;
// Where the label appears in the UI. Passed in from the constructor. This is
// a value from views::style::TextContext or an enum that extends it.
int GetTextContext() const;
void SetTextContext(int text_context);
// The style of the label. This is a value from views::style::TextStyle or an
// enum that extends it.
int GetTextStyle() const;
void SetTextStyle(int style);
// Applies |style| to a specific |range|. This is unimplemented for styles
// that vary from the global text style by anything besides weight.
void SetTextStyleRange(int style, const gfx::Range& range);
// Apply the baseline style range across the entire label.
void ApplyBaselineTextStyle();
// Enables or disables auto-color-readability (enabled by default). If this
// is enabled, then calls to set any foreground or background color will
// trigger an automatic mapper that uses color_utils::BlendForMinContrast()
// to ensure that the foreground colors are readable over the background
// color.
bool GetAutoColorReadabilityEnabled() const;
void SetAutoColorReadabilityEnabled(bool enabled);
// Gets/Sets the color. This will automatically force the color to be
// readable over the current background color, if auto color readability is
// enabled.
SkColor GetEnabledColor() const;
virtual void SetEnabledColor(SkColor color);
absl::optional<ui::ColorId> GetEnabledColorId() const;
void SetEnabledColorId(absl::optional<ui::ColorId> enabled_color_id);
// Gets/Sets the background color. This won't be explicitly drawn, but the
// label will force the text color to be readable over it.
SkColor GetBackgroundColor() const;
void SetBackgroundColor(SkColor color);
void SetBackgroundColorId(absl::optional<ui::ColorId> background_color_id);
// Gets/Sets the selection text color. This will automatically force the color
// to be readable over the selection background color, if auto color
// readability is enabled. Initialized with system default.
SkColor GetSelectionTextColor() const;
void SetSelectionTextColor(SkColor color);
// Gets/Sets the selection background color. Initialized with system default.
SkColor GetSelectionBackgroundColor() const;
void SetSelectionBackgroundColor(SkColor color);
// Get/Set drop shadows underneath the text.
const gfx::ShadowValues& GetShadows() const;
void SetShadows(const gfx::ShadowValues& shadows);
// Gets/Sets whether subpixel rendering is used; the default is true, but this
// feature also requires an opaque background color.
// TODO(mukai): rename this as SetSubpixelRenderingSuppressed() to keep the
// consistency with RenderText field name.
bool GetSubpixelRenderingEnabled() const;
void SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled);
// Gets/Sets whether the DCHECK() checking that subpixel-rendered text is
// only drawn onto opaque layers is skipped. Use this to suppress false
// positives - for example, if the label is drawn onto an opaque region of a
// non-opaque layer. If possible, prefer making the layer opaque or painting
// onto an opaque views::Background, as those cases are detected and
// excluded by this DCHECK automatically.
bool GetSkipSubpixelRenderingOpacityCheck() const;
void SetSkipSubpixelRenderingOpacityCheck(
bool skip_subpixel_rendering_opacity_check);
// Gets/Sets the horizontal alignment; the argument value is mirrored in RTL
// UI.
gfx::HorizontalAlignment GetHorizontalAlignment() const;
void SetHorizontalAlignment(gfx::HorizontalAlignment alignment);
// Gets/Sets the vertical alignment. Affects how whitespace is distributed
// vertically around the label text, or if the label is not tall enough to
// render all of the text, what gets cut off. ALIGN_MIDDLE is default and is
// strongly suggested for single-line labels because it produces a consistent
// baseline even when rendering with mixed fonts.
gfx::VerticalAlignment GetVerticalAlignment() const;
void SetVerticalAlignment(gfx::VerticalAlignment alignment);
// Get or set the distance in pixels between baselines of multi-line text.
// Default is the height of the default font.
int GetLineHeight() const;
void SetLineHeight(int line_height);
// Get or set if the label text can wrap on multiple lines; default is false.
bool GetMultiLine() const;
void SetMultiLine(bool multi_line);
// If multi-line, a non-zero value will cap the number of lines rendered, and
// elide the rest (currently only ELIDE_TAIL supported). See gfx::RenderText.
size_t GetMaxLines() const;
void SetMaxLines(size_t max_lines);
// If single-line, a non-zero value will help determine the amount of space
// needed *after* elision, which may be less than the passed |max_width|.
void SetMaximumWidthSingleLine(int max_width);
// Returns the number of lines required to render all text. The actual number
// of rendered lines might be limited by |max_lines_| which elides the rest.
size_t GetRequiredLines() const;
// Get or set if the label text should be obscured before rendering (e.g.
// should "Password!" display as "*********"); default is false.
bool GetObscured() const;
void SetObscured(bool obscured);
// Returns true if some portion of the text is not displayed, either because
// of eliding or clipping.
bool IsDisplayTextTruncated() const;
// Gets/Sets whether multi-line text can wrap mid-word; the default is false.
// TODO(mukai): allow specifying WordWrapBehavior.
bool GetAllowCharacterBreak() const;
void SetAllowCharacterBreak(bool allow_character_break);
// For the provided line index, gets the corresponding rendered line and
// returns the text position of the first character of that line.
size_t GetTextIndexOfLine(size_t line) const;
// Set the truncate length of the |full_text_|.
// NOTE: This does not affect the |display_text_|, since right now the only
// consumer does not need that; if you need this function, you may need to
// implement this.
void SetTruncateLength(size_t truncate_length);
// Gets/Sets the eliding or fading behavior, applied as necessary. The default
// is to elide at the end. Eliding is not well-supported for multi-line
// labels.
gfx::ElideBehavior GetElideBehavior() const;
void SetElideBehavior(gfx::ElideBehavior elide_behavior);
// Get or set the flags that control display of accelerator characters.
void SetDrawStringsFlags(int flags);
int GetDrawStringsFlags() const { return draw_strings_flags_; }
// Gets/Sets the tooltip text. Default behavior for a label (single-line) is
// to show the full text if it is wider than its bounds. Calling this
// overrides the default behavior and lets you set a custom tooltip. To
// revert to default behavior, call this with an empty string.
std::u16string GetTooltipText() const;
void SetTooltipText(const std::u16string& tooltip_text);
// Get or set whether this label can act as a tooltip handler; the default is
// true. Set to false whenever an ancestor view should handle tooltips
// instead.
bool GetHandlesTooltips() const;
void SetHandlesTooltips(bool enabled);
// Resizes the label so its width is set to the fixed width and its height
// deduced accordingly. Even if all widths of the lines are shorter than
// |fixed_width|, the given value is applied to the element's width.
// This is only intended for multi-line labels and is useful when the label's
// text contains several lines separated with \n.
// |fixed_width| is the fixed width that will be used (longer lines will be
// wrapped). If 0, no fixed width is enforced.
void SizeToFit(int fixed_width);
// Like SizeToFit, but uses a smaller width if possible.
int GetMaximumWidth() const;
void SetMaximumWidth(int max_width);
// Gets/Sets whether the preferred size is empty when the label is not
// visible.
bool GetCollapseWhenHidden() const;
void SetCollapseWhenHidden(bool value);
// Get the text as displayed to the user, respecting the obscured flag.
std::u16string GetDisplayTextForTesting();
// Get the text direction, as displayed to the user.
base::i18n::TextDirection GetTextDirectionForTesting();
// Returns true if the label can be made selectable. For example, links do not
// support text selection.
// Subclasses should override this function in case they want to selectively
// support text selection. If a subclass stops supporting text selection, it
// should call SetSelectable(false).
virtual bool IsSelectionSupported() const;
// Returns true if the label is selectable. Default is false.
bool GetSelectable() const;
// Sets whether the label is selectable. False is returned if the call fails,
// i.e. when selection is not supported but |selectable| is true. For example,
// obscured labels do not support text selection.
bool SetSelectable(bool selectable);
// Returns true if the label has a selection.
bool HasSelection() const;
// Selects the entire text. NO-OP if the label is not selectable.
void SelectAll();
// Clears any active selection.
void ClearSelection();
// Selects the given text range. NO-OP if the label is not selectable or the
// |range| endpoints don't lie on grapheme boundaries.
void SelectRange(const gfx::Range& range);
// Get the visual bounds containing the logical substring of the full text
// within the |range|. See gfx::RenderText.
std::vector<gfx::Rect> GetSubstringBounds(const gfx::Range& range);
[[nodiscard]] base::CallbackListSubscription AddTextChangedCallback(
views::PropertyChangedCallback callback);
// View:
int GetBaseline() const override;
gfx::Size CalculatePreferredSize() const override;
gfx::Size CalculatePreferredSize(
const SizeBounds& available_size) const override;
gfx::Size GetMinimumSize() const override;
int GetHeightForWidth(int w) const override;
View* GetTooltipHandlerForPoint(const gfx::Point& point) override;
bool GetCanProcessEventsWithinSubtree() const override;
WordLookupClient* GetWordLookupClient() override;
std::u16string GetTooltipText(const gfx::Point& p) const override;
protected:
// Create a single RenderText instance to actually be painted.
virtual std::unique_ptr<gfx::RenderText> CreateRenderText() const;
// Returns the preferred size and position of the text in local coordinates,
// which may exceed the local bounds of the label.
gfx::Rect GetTextBounds() const;
// Returns the Y coordinate the font_list() will actually be drawn at, in
// local coordinates. This may differ from GetTextBounds().y() since the font
// is positioned inside the display rect.
int GetFontListY() const;
void PaintText(gfx::Canvas* canvas);
// View:
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void VisibilityChanged(View* starting_from, bool is_visible) override;
void OnPaint(gfx::Canvas* canvas) override;
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
void OnThemeChanged() override;
ui::Cursor GetCursor(const ui::MouseEvent& event) override;
void OnFocus() override;
void OnBlur() override;
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnMouseCaptureLost() override;
bool OnKeyPressed(const ui::KeyEvent& event) override;
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
bool CanHandleAccelerators() const override;
private:
FRIEND_TEST_ALL_PREFIXES(LabelTest, ResetRenderTextData);
FRIEND_TEST_ALL_PREFIXES(LabelTest, MultilineSupportedRenderText);
FRIEND_TEST_ALL_PREFIXES(LabelTest, TextChangeWithoutLayout);
FRIEND_TEST_ALL_PREFIXES(LabelTest, EmptyLabel);
FRIEND_TEST_ALL_PREFIXES(LabelTest, FocusBounds);
FRIEND_TEST_ALL_PREFIXES(LabelTest, MultiLineSizingWithElide);
FRIEND_TEST_ALL_PREFIXES(LabelTest, IsDisplayTextTruncated);
FRIEND_TEST_ALL_PREFIXES(LabelTest, ChecksSubpixelRenderingOntoOpaqueSurface);
friend class LabelSelectionTest;
// ContextMenuController overrides:
void ShowContextMenuForViewImpl(View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) override;
// WordLookupClient overrides:
bool GetWordLookupDataAtPoint(const gfx::Point& point,
gfx::DecoratedText* decorated_word,
gfx::Point* baseline_point) override;
bool GetWordLookupDataFromSelection(gfx::DecoratedText* decorated_text,
gfx::Point* baseline_point) override;
// SelectionControllerDelegate overrides:
gfx::RenderText* GetRenderTextForSelectionController() override;
bool IsReadOnly() const override;
bool SupportsDrag() const override;
bool HasTextBeingDragged() const override;
void SetTextBeingDragged(bool value) override;
int GetViewHeight() const override;
int GetViewWidth() const override;
int GetDragSelectionDelay() const override;
void OnBeforePointerAction() override;
void OnAfterPointerAction(bool text_changed, bool selection_changed) override;
bool PasteSelectionClipboard() override;
void UpdateSelectionClipboard() override;
// ui::SimpleMenuModel::Delegate overrides:
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdEnabled(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
bool GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) const override;
const gfx::RenderText* GetRenderTextForSelectionController() const;
void Init(const std::u16string& text,
const gfx::FontList& font_list,
gfx::DirectionalityMode directionality_mode);
// Set up |display_text_| to actually be painted.
void MaybeBuildDisplayText() const;
// Get the text size for the current layout.
gfx::Size GetTextSize() const;
// Get the text size that ignores the current layout and respects
// `available_size`.
gfx::Size GetBoundedTextSize(const SizeBounds& available_size) const;
// Returns the appropriate foreground color to use given the proposed
// |foreground| and |background| colors.
SkColor GetForegroundColor(SkColor foreground, SkColor background) const;
// Updates text and selection colors from requested colors.
void RecalculateColors();
// Applies the foreground color to |display_text_|.
void ApplyTextColors() const;
// Updates any colors that have not been explicitly set from the theme.
void UpdateColorsFromTheme();
bool ShouldShowDefaultTooltip() const;
// Clears |display_text_| and updates |stored_selection_range_|.
// TODO(crbug.com/1103804) Most uses of this function are inefficient; either
// replace with setting attributes on both RenderTexts or collapse them to one
// RenderText.
void ClearDisplayText();
// Returns the currently selected text.
std::u16string GetSelectedText() const;
// Updates the clipboard with the currently selected text.
void CopyToClipboard();
// Builds |context_menu_contents_|.
void BuildContextMenuContents();
// Updates the elide behavior used by |full_text_|.
void UpdateFullTextElideBehavior();
int text_context_;
int text_style_;
absl::optional<int> line_height_;
// An un-elided and single-line RenderText object used for preferred sizing.
std::unique_ptr<gfx::RenderText> full_text_;
// The RenderText instance used for drawing.
mutable std::unique_ptr<gfx::RenderText> display_text_;
// Persists the current selection range between the calls to
// ClearDisplayText() and MaybeBuildDisplayText(). Holds an InvalidRange when
// not in use.
mutable gfx::Range stored_selection_range_ = gfx::Range::InvalidRange();
SkColor requested_enabled_color_ = gfx::kPlaceholderColor;
SkColor actual_enabled_color_ = gfx::kPlaceholderColor;
SkColor background_color_ = gfx::kPlaceholderColor;
SkColor requested_selection_text_color_ = gfx::kPlaceholderColor;
SkColor actual_selection_text_color_ = gfx::kPlaceholderColor;
SkColor selection_background_color_ = gfx::kPlaceholderColor;
absl::optional<ui::ColorId> enabled_color_id_;
absl::optional<ui::ColorId> background_color_id_;
// Set to true once the corresponding setter is invoked.
bool enabled_color_set_ = false;
bool background_color_set_ = false;
bool selection_text_color_set_ = false;
bool selection_background_color_set_ = false;
gfx::ElideBehavior elide_behavior_ = gfx::ELIDE_TAIL;
bool subpixel_rendering_enabled_ = true;
bool skip_subpixel_rendering_opacity_check_ = false;
bool auto_color_readability_enabled_ = true;
// TODO(mukai): remove |multi_line_| when all RenderText can render multiline.
bool multi_line_ = false;
size_t max_lines_ = 0;
std::u16string tooltip_text_;
bool handles_tooltips_ = true;
// Whether to collapse the label when it's not visible.
bool collapse_when_hidden_ = false;
int fixed_width_ = 0;
// This is used only for multi-line mode.
int max_width_ = 0;
// This is used in single-line mode.
int max_width_single_line_ = 0;
int draw_strings_flags_ = 0;
std::unique_ptr<SelectionController> selection_controller_;
// Context menu related members.
ui::SimpleMenuModel context_menu_contents_;
std::unique_ptr<views::MenuRunner> context_menu_runner_;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Label, View)
VIEW_BUILDER_PROPERTY(const gfx::FontList&, FontList)
VIEW_BUILDER_PROPERTY(const std::u16string&, Text)
VIEW_BUILDER_PROPERTY(int, TextStyle)
VIEW_BUILDER_PROPERTY(int, TextContext)
VIEW_BUILDER_PROPERTY(bool, AutoColorReadabilityEnabled)
VIEW_BUILDER_PROPERTY(SkColor, EnabledColor)
VIEW_BUILDER_PROPERTY(SkColor, BackgroundColor)
VIEW_BUILDER_PROPERTY(SkColor, SelectionTextColor)
VIEW_BUILDER_PROPERTY(SkColor, SelectionBackgroundColor)
VIEW_BUILDER_PROPERTY(ui::ColorId, EnabledColorId)
VIEW_BUILDER_PROPERTY(ui::ColorId, BackgroundColorId)
VIEW_BUILDER_PROPERTY(const gfx::ShadowValues&, Shadows)
VIEW_BUILDER_PROPERTY(bool, SubpixelRenderingEnabled)
VIEW_BUILDER_PROPERTY(bool, SkipSubpixelRenderingOpacityCheck)
VIEW_BUILDER_PROPERTY(gfx::HorizontalAlignment, HorizontalAlignment)
VIEW_BUILDER_PROPERTY(gfx::VerticalAlignment, VerticalAlignment)
VIEW_BUILDER_PROPERTY(int, LineHeight)
VIEW_BUILDER_PROPERTY(bool, MultiLine)
VIEW_BUILDER_PROPERTY(int, MaxLines)
VIEW_BUILDER_PROPERTY(bool, Obscured)
VIEW_BUILDER_PROPERTY(bool, AllowCharacterBreak)
VIEW_BUILDER_PROPERTY(size_t, TruncateLength)
VIEW_BUILDER_PROPERTY(gfx::ElideBehavior, ElideBehavior)
VIEW_BUILDER_PROPERTY(const std::u16string&, TooltipText)
VIEW_BUILDER_PROPERTY(bool, HandlesTooltips)
VIEW_BUILDER_PROPERTY(int, MaximumWidth)
VIEW_BUILDER_PROPERTY(bool, CollapseWhenHidden)
VIEW_BUILDER_PROPERTY(bool, Selectable)
VIEW_BUILDER_METHOD(SizeToFit, int)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Label)
#endif // UI_VIEWS_CONTROLS_LABEL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/label.h | C++ | unknown | 23,279 |
// Copyright 2017 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/label.h"
#include "base/strings/utf_string_conversions.h"
#include "base/timer/lap_timer.h"
#include "testing/perf/perf_result_reporter.h"
#include "ui/views/test/views_test_base.h"
namespace views {
using LabelPerfTest = ViewsTestBase;
// Test the number of text size measurements that can be made made per second.
// This should surface any performance regressions in underlying text layout
// system, e.g., failure to cache font structures.
TEST_F(LabelPerfTest, GetPreferredSize) {
Label label;
// Alternate between two strings to ensure caches are cleared.
std::u16string string1 = u"boring ascii string";
std::u16string string2 = u"another uninteresting sequence";
constexpr int kLaps = 5000; // Aim to run in under 3 seconds.
constexpr int kWarmupLaps = 5;
// The time limit is unused. Use kLaps for the check interval so the time is
// only measured once.
base::LapTimer timer(kWarmupLaps, base::TimeDelta(), kLaps);
for (int i = 0; i < kLaps + kWarmupLaps; ++i) {
label.SetText(i % 2 == 0 ? string1 : string2);
label.GetPreferredSize();
timer.NextLap();
}
perf_test::PerfResultReporter reporter("LabelPerfTest", "GetPreferredSize");
reporter.RegisterImportantMetric("", "runs/s");
reporter.AddResult("", timer.LapsPerSecond());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/label_perftest.cc | C++ | unknown | 1,482 |
// 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/label.h"
#include <stddef.h>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/canvas_painter.h"
#include "ui/compositor/layer.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/render_text.h"
#include "ui/gfx/text_constants.h"
#include "ui/gfx/text_elider.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/base_control_test_widget.h"
#include "ui/views/controls/link.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/style/typography.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/test/focus_manager_test.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_utils.h"
using base::WideToUTF16;
namespace views {
namespace {
#if BUILDFLAG(IS_MAC)
const int kControlCommandModifier = ui::EF_COMMAND_DOWN;
#else
const int kControlCommandModifier = ui::EF_CONTROL_DOWN;
#endif
// All text sizing measurements (width and height) should be greater than this.
const int kMinTextDimension = 4;
class TestLabel : public Label {
public:
TestLabel() : Label(u"TestLabel") { SizeToPreferredSize(); }
TestLabel(const TestLabel&) = delete;
TestLabel& operator=(const TestLabel&) = delete;
int schedule_paint_count() const { return schedule_paint_count_; }
void SimulatePaint() {
SkBitmap bitmap;
SkColor color = SK_ColorTRANSPARENT;
Paint(PaintInfo::CreateRootPaintInfo(
ui::CanvasPainter(&bitmap, bounds().size(), 1.f, color, false)
.context(),
bounds().size()));
}
// View:
void OnDidSchedulePaint(const gfx::Rect& r) override {
++schedule_paint_count_;
Label::OnDidSchedulePaint(r);
}
private:
int schedule_paint_count_ = 0;
};
// A test utility function to set the application default text direction.
void SetRTL(bool rtl) {
// Override the current locale/direction.
base::i18n::SetICUDefaultLocale(rtl ? "he" : "en");
EXPECT_EQ(rtl, base::i18n::IsRTL());
}
std::u16string GetClipboardText(ui::ClipboardBuffer clipboard_buffer) {
std::u16string clipboard_text;
ui::Clipboard::GetForCurrentThread()->ReadText(
clipboard_buffer, /* data_dst = */ nullptr, &clipboard_text);
return clipboard_text;
}
// Makes an RTL string by mapping 0..6 to [א,ב,ג,ד,ה,ו,ז].
std::u16string ToRTL(const char* ascii) {
std::u16string rtl;
for (const char* c = ascii; *c; ++c) {
if (*c >= '0' && *c <= '6')
rtl += static_cast<char16_t>(u'א' + (*c - '0'));
else
rtl += static_cast<char16_t>(*c);
}
return rtl;
}
} // namespace
class LabelTest : public test::BaseControlTestWidget {
public:
LabelTest() = default;
LabelTest(const LabelTest&) = delete;
LabelTest& operator=(const LabelTest&) = delete;
~LabelTest() override = default;
protected:
void CreateWidgetContent(View* container) override {
label_ = container->AddChildView(std::make_unique<Label>());
}
Label* label() { return label_; }
private:
raw_ptr<Label> label_ = nullptr;
};
// Test fixture for text selection related tests.
class LabelSelectionTest : public LabelTest {
public:
// Alias this long identifier for more readable tests.
static constexpr bool kExtends =
gfx::RenderText::kDragToEndIfOutsideVerticalBounds;
// Some tests use cardinal directions to index an array of points above and
// below the label in either visual direction.
enum { NW, NORTH, NE, SE, SOUTH, SW };
LabelSelectionTest() = default;
LabelSelectionTest(const LabelSelectionTest&) = delete;
LabelSelectionTest& operator=(const LabelSelectionTest&) = delete;
// LabelTest overrides:
void SetUp() override {
LabelTest::SetUp();
event_generator_ =
std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget()));
}
protected:
View* GetFocusedView() {
return widget()->GetFocusManager()->GetFocusedView();
}
void PerformMousePress(const gfx::Point& point) {
ui::MouseEvent pressed_event = ui::MouseEvent(
ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
label()->OnMousePressed(pressed_event);
}
void PerformMouseRelease(const gfx::Point& point) {
ui::MouseEvent released_event = ui::MouseEvent(
ui::ET_MOUSE_RELEASED, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
label()->OnMouseReleased(released_event);
}
void PerformClick(const gfx::Point& point) {
PerformMousePress(point);
PerformMouseRelease(point);
}
void PerformMouseDragTo(const gfx::Point& point) {
ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
label()->OnMouseDragged(drag);
}
// Used to force layout on the underlying RenderText instance.
void SimulatePaint() {
gfx::Canvas canvas;
label()->OnPaint(&canvas);
}
gfx::Point GetCursorPoint(uint32_t index) {
SimulatePaint();
gfx::RenderText* render_text =
label()->GetRenderTextForSelectionController();
// For single-line text, use the glyph bounds since it gives a better
// representation of the midpoint between glyphs when considering selection.
// TODO(crbug.com/248597): Add multiline support to GetCursorBounds(...).
if (!render_text->multiline()) {
return render_text
->GetCursorBounds(gfx::SelectionModel(index, gfx::CURSOR_FORWARD),
true)
.left_center();
}
// Otherwise, GetCursorBounds() will give incorrect results. Multiline
// editing is not supported (http://crbug.com/248597) so there hasn't been
// a need to draw a cursor. Instead, derive a point from the selection
// bounds, which always rounds up to an integer after the end of a glyph.
// This rounding differs to the glyph bounds, which rounds to nearest
// integer. See http://crbug.com/735346.
auto bounds = render_text->GetSubstringBounds({index, index + 1});
DCHECK_EQ(1u, bounds.size());
const bool rtl =
render_text->GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT;
// Return Point corresponding to the leading edge of the character.
return rtl ? bounds[0].right_center() + gfx::Vector2d(-1, 0)
: bounds[0].left_center() + gfx::Vector2d(1, 0);
}
size_t GetLineCount() {
SimulatePaint();
return label()->GetRenderTextForSelectionController()->GetNumLines();
}
std::u16string GetSelectedText() { return label()->GetSelectedText(); }
ui::test::EventGenerator* event_generator() { return event_generator_.get(); }
bool IsMenuCommandEnabled(int command_id) {
return label()->IsCommandIdEnabled(command_id);
}
private:
std::unique_ptr<ui::test::EventGenerator> event_generator_;
};
TEST_F(LabelTest, Metadata) {
// Calling SetMultiLine() will DCHECK unless the label is in multi-line mode.
label()->SetMultiLine(true);
test::TestViewMetadata(label());
}
TEST_F(LabelTest, FontPropertySymbol) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// On linux, the fonts are mocked with a custom FontConfig. The "Courier New"
// family name is mapped to Cousine-Regular.ttf (see: $build/test_fonts/*).
std::string font_name("Courier New");
#else
std::string font_name("symbol");
#endif
gfx::Font font(font_name, 26);
label()->SetFontList(gfx::FontList(font));
gfx::Font font_used = label()->font_list().GetPrimaryFont();
EXPECT_EQ(font_name, font_used.GetFontName());
EXPECT_EQ(26, font_used.GetFontSize());
}
TEST_F(LabelTest, FontPropertyArial) {
std::string font_name("arial");
gfx::Font font(font_name, 30);
label()->SetFontList(gfx::FontList(font));
gfx::Font font_used = label()->font_list().GetPrimaryFont();
EXPECT_EQ(font_name, font_used.GetFontName());
EXPECT_EQ(30, font_used.GetFontSize());
}
TEST_F(LabelTest, TextProperty) {
std::u16string test_text(u"A random string.");
label()->SetText(test_text);
EXPECT_EQ(test_text, label()->GetText());
}
TEST_F(LabelTest, TextStyleProperty) {
label()->SetTextStyle(views::style::STYLE_DISABLED);
EXPECT_EQ(views::style::STYLE_DISABLED, label()->GetTextStyle());
}
TEST_F(LabelTest, ColorProperty) {
SkColor color = SkColorSetARGB(20, 40, 10, 5);
label()->SetAutoColorReadabilityEnabled(false);
label()->SetEnabledColor(color);
EXPECT_EQ(color, label()->GetEnabledColor());
}
TEST_F(LabelTest, ColorPropertyOnEnabledColorIdChange) {
const auto color = label()->GetWidget()->GetColorProvider()->GetColor(
ui::kColorPrimaryForeground);
label()->SetAutoColorReadabilityEnabled(false);
label()->SetEnabledColorId(ui::kColorPrimaryForeground);
EXPECT_EQ(color, label()->GetEnabledColor());
// Update the enabled id and verify the actual enabled color is updated to
// reflect the color id change. Regression test case for: b/262402965.
label()->SetEnabledColorId(ui::kColorAccent);
EXPECT_EQ(
label()->GetWidget()->GetColorProvider()->GetColor(ui::kColorAccent),
label()->GetEnabledColor());
}
TEST_F(LabelTest, BackgroundColor) {
// The correct default background color is set.
EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorDialogBackground),
label()->GetBackgroundColor());
label()->SetBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(SK_ColorBLUE, label()->GetBackgroundColor());
}
TEST_F(LabelTest, BackgroundColorId) {
// The correct default background color is set.
EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorDialogBackground),
label()->GetBackgroundColor());
label()->SetBackgroundColorId(ui::kColorAlertHighSeverity);
EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorAlertHighSeverity),
label()->GetBackgroundColor());
// A color id takes precedence.
label()->SetBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorAlertHighSeverity),
label()->GetBackgroundColor());
// Once a color id is no longer set, colors can be set again.
label()->SetBackgroundColorId(absl::nullopt);
label()->SetBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(SK_ColorBLUE, label()->GetBackgroundColor());
}
TEST_F(LabelTest, AlignmentProperty) {
const bool was_rtl = base::i18n::IsRTL();
for (size_t i = 0; i < 2; ++i) {
// Toggle the application default text direction (to try each direction).
SetRTL(!base::i18n::IsRTL());
bool reverse_alignment = base::i18n::IsRTL();
// The alignment should be flipped in RTL UI.
label()->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
EXPECT_EQ(reverse_alignment ? gfx::ALIGN_LEFT : gfx::ALIGN_RIGHT,
label()->GetHorizontalAlignment());
label()->SetHorizontalAlignment(gfx::ALIGN_LEFT);
EXPECT_EQ(reverse_alignment ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT,
label()->GetHorizontalAlignment());
label()->SetHorizontalAlignment(gfx::ALIGN_CENTER);
EXPECT_EQ(gfx::ALIGN_CENTER, label()->GetHorizontalAlignment());
for (size_t j = 0; j < 2; ++j) {
label()->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD);
const bool rtl = j == 0;
label()->SetText(rtl ? u"\x5d0" : u"A");
EXPECT_EQ(gfx::ALIGN_TO_HEAD, label()->GetHorizontalAlignment());
}
}
EXPECT_EQ(was_rtl, base::i18n::IsRTL());
}
TEST_F(LabelTest, MinimumSizeRespectsLineHeight) {
std::u16string text(u"This is example text.");
label()->SetText(text);
const gfx::Size minimum_size = label()->GetMinimumSize();
const int expected_height = minimum_size.height() + 10;
label()->SetLineHeight(expected_height);
EXPECT_EQ(expected_height, label()->GetMinimumSize().height());
}
TEST_F(LabelTest, MinimumSizeRespectsLineHeightMultiline) {
std::u16string text(u"This is example text.");
label()->SetText(text);
label()->SetMultiLine(true);
const gfx::Size minimum_size = label()->GetMinimumSize();
const int expected_height = minimum_size.height() + 10;
label()->SetLineHeight(expected_height);
EXPECT_EQ(expected_height, label()->GetMinimumSize().height());
}
TEST_F(LabelTest, MinimumSizeRespectsLineHeightWithInsets) {
std::u16string text(u"This is example text.");
label()->SetText(text);
const gfx::Size minimum_size = label()->GetMinimumSize();
int expected_height = minimum_size.height() + 10;
label()->SetLineHeight(expected_height);
constexpr auto kInsets = gfx::Insets::TLBR(2, 3, 4, 5);
expected_height += kInsets.height();
label()->SetBorder(CreateEmptyBorder(kInsets));
EXPECT_EQ(expected_height, label()->GetMinimumSize().height());
}
TEST_F(LabelTest, MinimumSizeRespectsLineHeightMultilineWithInsets) {
std::u16string text(u"This is example text.");
label()->SetText(text);
label()->SetMultiLine(true);
const gfx::Size minimum_size = label()->GetMinimumSize();
int expected_height = minimum_size.height() + 10;
label()->SetLineHeight(expected_height);
constexpr auto kInsets = gfx::Insets::TLBR(2, 3, 4, 5);
expected_height += kInsets.height();
label()->SetBorder(CreateEmptyBorder(kInsets));
EXPECT_EQ(expected_height, label()->GetMinimumSize().height());
}
TEST_F(LabelTest, ElideBehavior) {
std::u16string text(u"This is example text.");
label()->SetText(text);
EXPECT_EQ(gfx::ELIDE_TAIL, label()->GetElideBehavior());
gfx::Size size = label()->GetPreferredSize();
label()->SetBoundsRect(gfx::Rect(size));
EXPECT_EQ(text, label()->GetDisplayTextForTesting());
size.set_width(size.width() / 2);
label()->SetBoundsRect(gfx::Rect(size));
EXPECT_GT(text.size(), label()->GetDisplayTextForTesting().size());
label()->SetElideBehavior(gfx::NO_ELIDE);
EXPECT_EQ(text, label()->GetDisplayTextForTesting());
}
// Test the minimum width of a Label is correct depending on its ElideBehavior,
// including |gfx::NO_ELIDE|.
TEST_F(LabelTest, ElideBehaviorMinimumWidth) {
std::u16string text(u"This is example text.");
label()->SetText(text);
// Default should be |gfx::ELIDE_TAIL|.
EXPECT_EQ(gfx::ELIDE_TAIL, label()->GetElideBehavior());
gfx::Size size = label()->GetMinimumSize();
// Elidable labels have a minimum width that fits |gfx::kEllipsisUTF16|.
EXPECT_EQ(gfx::Canvas::GetStringWidth(std::u16string(gfx::kEllipsisUTF16),
label()->font_list()),
size.width());
label()->SetSize(label()->GetMinimumSize());
EXPECT_GT(text.length(), label()->GetDisplayTextForTesting().length());
// Truncated labels can take up the size they are given, but not exceed that
// if the text can't fit.
label()->SetElideBehavior(gfx::TRUNCATE);
label()->SetSize(gfx::Size(10, 10));
size = label()->GetMinimumSize();
EXPECT_LT(size.width(), label()->size().width());
EXPECT_GT(text.length(), label()->GetDisplayTextForTesting().length());
// Non-elidable single-line labels should take up their full text size, since
// this behavior implies the text should not be cut off.
EXPECT_FALSE(label()->GetMultiLine());
label()->SetElideBehavior(gfx::NO_ELIDE);
size = label()->GetMinimumSize();
EXPECT_EQ(text.length(), label()->GetDisplayTextForTesting().length());
label()->SetSize(label()->GetMinimumSize());
EXPECT_EQ(text, label()->GetDisplayTextForTesting());
}
TEST_F(LabelTest, MultiLineProperty) {
EXPECT_FALSE(label()->GetMultiLine());
label()->SetMultiLine(true);
EXPECT_TRUE(label()->GetMultiLine());
label()->SetMultiLine(false);
EXPECT_FALSE(label()->GetMultiLine());
}
TEST_F(LabelTest, ObscuredProperty) {
std::u16string test_text(u"Password!");
label()->SetText(test_text);
label()->SizeToPreferredSize();
// The text should be unobscured by default.
EXPECT_FALSE(label()->GetObscured());
EXPECT_EQ(test_text, label()->GetDisplayTextForTesting());
EXPECT_EQ(test_text, label()->GetText());
label()->SetObscured(true);
label()->SizeToPreferredSize();
EXPECT_TRUE(label()->GetObscured());
EXPECT_EQ(std::u16string(test_text.size(),
gfx::RenderText::kPasswordReplacementChar),
label()->GetDisplayTextForTesting());
EXPECT_EQ(test_text, label()->GetText());
label()->SetText(test_text + test_text);
label()->SizeToPreferredSize();
EXPECT_EQ(std::u16string(test_text.size() * 2,
gfx::RenderText::kPasswordReplacementChar),
label()->GetDisplayTextForTesting());
EXPECT_EQ(test_text + test_text, label()->GetText());
label()->SetObscured(false);
label()->SizeToPreferredSize();
EXPECT_FALSE(label()->GetObscured());
EXPECT_EQ(test_text + test_text, label()->GetDisplayTextForTesting());
EXPECT_EQ(test_text + test_text, label()->GetText());
}
TEST_F(LabelTest, ObscuredSurrogatePair) {
// 'MUSICAL SYMBOL G CLEF': represented in UTF-16 as two characters
// forming the surrogate pair 0x0001D11E.
const std::u16string kTestText = u"𝄞";
label()->SetText(kTestText);
label()->SetObscured(true);
label()->SizeToPreferredSize();
EXPECT_EQ(std::u16string(1, gfx::RenderText::kPasswordReplacementChar),
label()->GetDisplayTextForTesting());
EXPECT_EQ(kTestText, label()->GetText());
}
// This test case verifies the label preferred size will change based on the
// current layout, which may seem wrong. However many of our code base assumes
// this behavior, therefore this behavior will have to be kept until the code
// with this assumption is fixed. See http://crbug.com/468494 and
// http://crbug.com/467526.
// TODO(crbug.com/1346889): convert all callsites of GetPreferredSize() to
// call GetPreferredSize(SizeBounds) instead.
TEST_F(LabelTest, MultilinePreferredSizeTest) {
label()->SetText(u"This is an example.");
gfx::Size single_line_size = label()->GetPreferredSize();
label()->SetMultiLine(true);
gfx::Size multi_line_size = label()->GetPreferredSize();
EXPECT_EQ(single_line_size, multi_line_size);
int new_width = multi_line_size.width() / 2;
label()->SetBounds(0, 0, new_width, label()->GetHeightForWidth(new_width));
gfx::Size new_size = label()->GetPreferredSize();
EXPECT_GT(multi_line_size.width(), new_size.width());
EXPECT_LT(multi_line_size.height(), new_size.height());
}
TEST_F(LabelTest, MultilinePreferredSizeWithConstraintTest) {
label()->SetText(u"This is an example.");
const gfx::Size single_line_size =
label()->GetPreferredSize({/* Unbounded */});
// Test the preferred size when the label is not yet laid out.
label()->SetMultiLine(true);
const gfx::Size multi_line_size_unbounded =
label()->GetPreferredSize({/* Unbounded */});
EXPECT_EQ(single_line_size, multi_line_size_unbounded);
const gfx::Size multi_line_size_bounded = label()->GetPreferredSize(
{single_line_size.width() / 2, {/* Unbounded */}});
EXPECT_GT(multi_line_size_unbounded.width(), multi_line_size_bounded.width());
EXPECT_LT(multi_line_size_unbounded.height(),
multi_line_size_bounded.height());
// Test the preferred size after the label is laid out.
// GetPreferredSize(SizeBounds) should ignore the existing bounds.
const int layout_width = multi_line_size_unbounded.width() / 3;
label()->SetBounds(0, 0, layout_width,
label()->GetHeightForWidth(layout_width));
const gfx::Size multi_line_size_unbounded2 =
label()->GetPreferredSize({/* Unbounded */});
const gfx::Size multi_line_size_bounded2 = label()->GetPreferredSize(
{single_line_size.width() / 2, {/* Unbounded */}});
EXPECT_EQ(multi_line_size_unbounded, multi_line_size_unbounded2);
EXPECT_EQ(multi_line_size_bounded, multi_line_size_bounded2);
}
TEST_F(LabelTest, SingleLineGetHeightForWidth) {
// Even an empty label should take one line worth of height.
const int line_height = label()->GetLineHeight();
EXPECT_EQ(line_height, label()->GetHeightForWidth(100));
// Given any amount of width, the label should take one line.
label()->SetText(u"This is an example.");
const int width = label()->GetPreferredSize().width();
EXPECT_EQ(line_height, label()->GetHeightForWidth(width));
EXPECT_EQ(line_height, label()->GetHeightForWidth(width * 2));
EXPECT_EQ(line_height, label()->GetHeightForWidth(width / 2));
EXPECT_EQ(line_height, label()->GetHeightForWidth(0));
}
TEST_F(LabelTest, MultiLineGetHeightForWidth) {
// Even an empty label should take one line worth of height.
label()->SetMultiLine(true);
const int line_height = label()->GetLineHeight();
EXPECT_EQ(line_height, label()->GetHeightForWidth(100));
// Given its preferred width or more, the label should take one line.
label()->SetText(u"This is an example.");
const int width = label()->GetPreferredSize().width();
EXPECT_EQ(line_height, label()->GetHeightForWidth(width));
EXPECT_EQ(line_height, label()->GetHeightForWidth(width * 2));
// Given too little width, the required number of lines should increase.
// Linebreaking will affect this, so sanity-checks are sufficient.
const int height_for_half_width = label()->GetHeightForWidth(width / 2);
EXPECT_GT(height_for_half_width, line_height);
EXPECT_GT(label()->GetHeightForWidth(width / 4), height_for_half_width);
// Given zero width, the label should take GetMaxLines(); if this is not set,
// default to one.
EXPECT_EQ(line_height, label()->GetHeightForWidth(0));
label()->SetMaxLines(10);
EXPECT_EQ(line_height * 10, label()->GetHeightForWidth(0));
}
TEST_F(LabelTest, TooltipProperty) {
label()->SetText(u"My cool string.");
// Initially, label has no bounds, its text does not fit, and therefore its
// text should be returned as the tooltip text.
EXPECT_EQ(label()->GetText(), label()->GetTooltipText(gfx::Point()));
// While tooltip handling is disabled, GetTooltipText() should fail.
label()->SetHandlesTooltips(false);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
label()->SetHandlesTooltips(true);
// When set, custom tooltip text should be returned instead of the label's
// text.
std::u16string tooltip_text(u"The tooltip!");
label()->SetTooltipText(tooltip_text);
EXPECT_EQ(tooltip_text, label()->GetTooltipText(gfx::Point()));
// While tooltip handling is disabled, GetTooltipText() should fail.
label()->SetHandlesTooltips(false);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
label()->SetHandlesTooltips(true);
// When the tooltip text is set to an empty string, the original behavior is
// restored.
label()->SetTooltipText(std::u16string());
EXPECT_EQ(label()->GetText(), label()->GetTooltipText(gfx::Point()));
// While tooltip handling is disabled, GetTooltipText() should fail.
label()->SetHandlesTooltips(false);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
label()->SetHandlesTooltips(true);
// Make the label big enough to hold the text
// and expect there to be no tooltip.
label()->SetBounds(0, 0, 1000, 40);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
// Shrinking the single-line label's height shouldn't trigger a tooltip.
label()->SetBounds(0, 0, 1000, label()->GetPreferredSize().height() / 2);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
// Verify that explicitly set tooltip text is shown, regardless of size.
label()->SetTooltipText(tooltip_text);
EXPECT_EQ(tooltip_text, label()->GetTooltipText(gfx::Point()));
// Clear out the explicitly set tooltip text.
label()->SetTooltipText(std::u16string());
// Shrink the bounds and the tooltip should come back.
label()->SetBounds(0, 0, 10, 10);
EXPECT_FALSE(label()->GetTooltipText(gfx::Point()).empty());
// Make the label obscured and there is no tooltip.
label()->SetObscured(true);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
// Obscuring the text shouldn't permanently clobber the tooltip.
label()->SetObscured(false);
EXPECT_FALSE(label()->GetTooltipText(gfx::Point()).empty());
// Making the label multiline shouldn't eliminate the tooltip.
label()->SetMultiLine(true);
EXPECT_FALSE(label()->GetTooltipText(gfx::Point()).empty());
// Expanding the multiline label bounds should eliminate the tooltip.
label()->SetBounds(0, 0, 1000, 1000);
EXPECT_TRUE(label()->GetTooltipText(gfx::Point()).empty());
// Verify that setting the tooltip still shows it.
label()->SetTooltipText(tooltip_text);
EXPECT_EQ(tooltip_text, label()->GetTooltipText(gfx::Point()));
// Clear out the tooltip.
label()->SetTooltipText(std::u16string());
}
TEST_F(LabelTest, Accessibility) {
const std::u16string accessible_name = u"A11y text.";
label()->SetText(u"Displayed text.");
ui::AXNodeData node_data;
label()->GetAccessibleNodeData(&node_data);
EXPECT_EQ(ax::mojom::Role::kStaticText, node_data.role);
EXPECT_EQ(label()->GetText(),
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
EXPECT_FALSE(
node_data.HasIntAttribute(ax::mojom::IntAttribute::kRestriction));
// Setting a custom accessible name overrides the displayed text in
// screen reader announcements.
label()->SetAccessibleName(accessible_name);
label()->GetAccessibleNodeData(&node_data);
EXPECT_EQ(accessible_name,
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
EXPECT_NE(label()->GetText(),
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
// Changing the displayed text will not impact the non-empty accessible name.
label()->SetText(u"Different displayed Text.");
label()->GetAccessibleNodeData(&node_data);
EXPECT_EQ(accessible_name,
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
EXPECT_NE(label()->GetText(),
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
// Clearing the accessible name will cause the screen reader to default to
// verbalizing the displayed text.
label()->SetAccessibleName(u"");
label()->GetAccessibleNodeData(&node_data);
EXPECT_EQ(label()->GetText(),
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
// If the displayed text is the source of the accessible name, and that text
// is cleared, the accessible name should also be cleared.
label()->SetText(u"");
label()->GetAccessibleNodeData(&node_data);
EXPECT_EQ(label()->GetText(),
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
}
TEST_F(LabelTest, SetTextNotifiesAccessibilityEvent) {
test::AXEventCounter counter(views::AXEventManager::Get());
// Changing the text affects the accessible name, so it should notify.
EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged));
label()->SetText(u"Example");
EXPECT_EQ(u"Example", label()->GetAccessibleName());
EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged));
// Changing the text when it doesn't affect the accessible name should not
// notify.
label()->SetAccessibleName(u"Name");
EXPECT_EQ(2, counter.GetCount(ax::mojom::Event::kTextChanged));
label()->SetText(u"Example2");
EXPECT_EQ(u"Name", label()->GetAccessibleName());
EXPECT_EQ(2, counter.GetCount(ax::mojom::Event::kTextChanged));
}
TEST_F(LabelTest, TextChangeWithoutLayout) {
label()->SetText(u"Example");
label()->SetBounds(0, 0, 200, 200);
gfx::Canvas canvas(gfx::Size(200, 200), 1.0f, true);
label()->OnPaint(&canvas);
EXPECT_TRUE(label()->display_text_);
EXPECT_EQ(u"Example", label()->display_text_->GetDisplayText());
label()->SetText(u"Altered");
// The altered text should be painted even though Layout() or SetBounds() are
// not called.
label()->OnPaint(&canvas);
EXPECT_TRUE(label()->display_text_);
EXPECT_EQ(u"Altered", label()->display_text_->GetDisplayText());
}
TEST_F(LabelTest, AccessibleNameAndRole) {
label()->SetText(u"Text");
EXPECT_EQ(label()->GetAccessibleName(), u"Text");
EXPECT_EQ(label()->GetAccessibleRole(), ax::mojom::Role::kStaticText);
ui::AXNodeData data;
label()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Text");
EXPECT_EQ(data.role, ax::mojom::Role::kStaticText);
label()->SetTextContext(style::CONTEXT_DIALOG_TITLE);
EXPECT_EQ(label()->GetAccessibleName(), u"Text");
EXPECT_EQ(label()->GetAccessibleRole(), ax::mojom::Role::kTitleBar);
data = ui::AXNodeData();
label()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Text");
EXPECT_EQ(data.role, ax::mojom::Role::kTitleBar);
label()->SetText(u"New Text");
label()->SetAccessibleRole(ax::mojom::Role::kLink);
EXPECT_EQ(label()->GetAccessibleName(), u"New Text");
EXPECT_EQ(label()->GetAccessibleRole(), ax::mojom::Role::kLink);
data = ui::AXNodeData();
label()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"New Text");
EXPECT_EQ(data.role, ax::mojom::Role::kLink);
}
TEST_F(LabelTest, EmptyLabelSizing) {
const gfx::Size expected_size(0, label()->font_list().GetHeight());
EXPECT_EQ(expected_size, label()->GetPreferredSize());
label()->SetMultiLine(!label()->GetMultiLine());
EXPECT_EQ(expected_size, label()->GetPreferredSize());
}
TEST_F(LabelTest, SingleLineSizing) {
label()->SetText(u"A not so random string in one line.");
const gfx::Size size = label()->GetPreferredSize();
EXPECT_GT(size.height(), kMinTextDimension);
EXPECT_GT(size.width(), kMinTextDimension);
// Setting a size smaller than preferred should not change the preferred size.
label()->SetSize(gfx::Size(size.width() / 2, size.height() / 2));
EXPECT_EQ(size, label()->GetPreferredSize());
const auto border = gfx::Insets::TLBR(10, 20, 30, 40);
label()->SetBorder(CreateEmptyBorder(border));
const gfx::Size size_with_border = label()->GetPreferredSize();
EXPECT_EQ(size_with_border.height(), size.height() + border.height());
EXPECT_EQ(size_with_border.width(), size.width() + border.width());
EXPECT_EQ(size.height() + border.height(),
label()->GetHeightForWidth(size_with_border.width()));
}
TEST_F(LabelTest, MultilineSmallAvailableWidthSizing) {
label()->SetMultiLine(true);
label()->SetAllowCharacterBreak(true);
label()->SetText(u"Too Wide.");
// Check that Label can be laid out at a variety of small sizes,
// splitting the words into up to one character per line if necessary.
// Incorrect word splitting may cause infinite loops in text layout.
gfx::Size required_size = label()->GetPreferredSize();
for (int i = 1; i < required_size.width(); ++i)
EXPECT_GT(label()->GetHeightForWidth(i), 0);
}
// Verifies if SetAllowCharacterBreak(true) doesn't change the preferred size.
// See crbug.com/469559
TEST_F(LabelTest, PreferredSizeForAllowCharacterBreak) {
label()->SetText(u"Example");
gfx::Size preferred_size = label()->GetPreferredSize();
label()->SetMultiLine(true);
label()->SetAllowCharacterBreak(true);
EXPECT_EQ(preferred_size, label()->GetPreferredSize());
}
TEST_F(LabelTest, MultiLineSizing) {
label()->SetText(u"A random string\nwith multiple lines\nand returns!");
label()->SetMultiLine(true);
// GetPreferredSize
gfx::Size required_size = label()->GetPreferredSize();
EXPECT_GT(required_size.height(), kMinTextDimension);
EXPECT_GT(required_size.width(), kMinTextDimension);
// SizeToFit with unlimited width.
label()->SizeToFit(0);
int required_width = label()->GetLocalBounds().width();
EXPECT_GT(required_width, kMinTextDimension);
// SizeToFit with limited width.
label()->SizeToFit(required_width - 1);
int constrained_width = label()->GetLocalBounds().width();
#if BUILDFLAG(IS_WIN)
// Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc)
// has to be fixed to return the size that fits to given width/height.
EXPECT_LT(constrained_width, required_width);
#endif
EXPECT_GT(constrained_width, kMinTextDimension);
// Change the width back to the desire width.
label()->SizeToFit(required_width);
EXPECT_EQ(required_width, label()->GetLocalBounds().width());
// General tests for GetHeightForWidth.
int required_height = label()->GetHeightForWidth(required_width);
EXPECT_GT(required_height, kMinTextDimension);
int height_for_constrained_width =
label()->GetHeightForWidth(constrained_width);
#if BUILDFLAG(IS_WIN)
// Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc)
// has to be fixed to return the size that fits to given width/height.
EXPECT_GT(height_for_constrained_width, required_height);
#endif
// Using the constrained width or the required_width - 1 should give the
// same result for the height because the constrainted width is the tight
// width when given "required_width - 1" as the max width.
EXPECT_EQ(height_for_constrained_width,
label()->GetHeightForWidth(required_width - 1));
// Test everything with borders.
auto border = gfx::Insets::TLBR(10, 20, 30, 40);
label()->SetBorder(CreateEmptyBorder(border));
// SizeToFit and borders.
label()->SizeToFit(0);
int required_width_with_border = label()->GetLocalBounds().width();
EXPECT_EQ(required_width_with_border, required_width + border.width());
// GetHeightForWidth and borders.
int required_height_with_border =
label()->GetHeightForWidth(required_width_with_border);
EXPECT_EQ(required_height_with_border, required_height + border.height());
// Test that the border width is subtracted before doing the height
// calculation. If it is, then the height will grow when width
// is shrunk.
int height1 = label()->GetHeightForWidth(required_width_with_border - 1);
#if BUILDFLAG(IS_WIN)
// Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc)
// has to be fixed to return the size that fits to given width/height.
EXPECT_GT(height1, required_height_with_border);
#endif
EXPECT_EQ(height1, height_for_constrained_width + border.height());
// GetPreferredSize and borders.
label()->SetBounds(0, 0, 0, 0);
gfx::Size required_size_with_border = label()->GetPreferredSize();
EXPECT_EQ(required_size_with_border.height(),
required_size.height() + border.height());
EXPECT_EQ(required_size_with_border.width(),
required_size.width() + border.width());
}
#if !BUILDFLAG(IS_MAC)
// TODO(warx): Remove !BUILDFLAG(IS_MAC) once SetMaxLines() is applied to MAC
// (crbug.com/758720).
TEST_F(LabelTest, MultiLineSetMaxLines) {
// Ensure SetMaxLines clamps the line count of a string with returns.
label()->SetText(u"first line\nsecond line\nthird line");
label()->SetMultiLine(true);
gfx::Size string_size = label()->GetPreferredSize();
label()->SetMaxLines(2);
gfx::Size two_line_size = label()->GetPreferredSize();
EXPECT_EQ(string_size.width(), two_line_size.width());
EXPECT_GT(string_size.height(), two_line_size.height());
// Ensure GetHeightForWidth also respects SetMaxLines.
int height = label()->GetHeightForWidth(string_size.width() / 2);
EXPECT_EQ(height, two_line_size.height());
// Ensure SetMaxLines also works with line wrapping for SizeToFit.
label()->SetText(u"A long string that will be wrapped");
label()->SetMaxLines(0); // Used to get the uncapped height.
label()->SizeToFit(0); // Used to get the uncapped width.
label()->SizeToFit(label()->GetPreferredSize().width() / 4);
string_size = label()->GetPreferredSize();
label()->SetMaxLines(2);
two_line_size = label()->GetPreferredSize();
EXPECT_EQ(string_size.width(), two_line_size.width());
EXPECT_GT(string_size.height(), two_line_size.height());
// Ensure SetMaxLines also works with line wrapping for SetMaximumWidth.
label()->SetMaxLines(0); // Used to get the uncapped height.
label()->SizeToFit(0); // Used to get the uncapped width.
label()->SetMaximumWidth(label()->GetPreferredSize().width() / 4);
string_size = label()->GetPreferredSize();
label()->SetMaxLines(2);
two_line_size = label()->GetPreferredSize();
EXPECT_EQ(string_size.width(), two_line_size.width());
EXPECT_GT(string_size.height(), two_line_size.height());
// Ensure SetMaxLines respects the requested inset height.
const auto border = gfx::Insets::TLBR(1, 2, 3, 4);
label()->SetBorder(CreateEmptyBorder(border));
EXPECT_EQ(two_line_size.height() + border.height(),
label()->GetPreferredSize().height());
}
#endif
// Verifies if the combination of text eliding and multiline doesn't cause
// any side effects of size / layout calculation.
TEST_F(LabelTest, MultiLineSizingWithElide) {
const std::u16string text =
u"A random string\nwith multiple lines\nand returns!";
label()->SetText(text);
label()->SetMultiLine(true);
gfx::Size required_size = label()->GetPreferredSize();
EXPECT_GT(required_size.height(), kMinTextDimension);
EXPECT_GT(required_size.width(), kMinTextDimension);
label()->SetBoundsRect(gfx::Rect(required_size));
label()->SetElideBehavior(gfx::ELIDE_TAIL);
EXPECT_EQ(required_size, label()->GetPreferredSize());
EXPECT_EQ(text, label()->GetDisplayTextForTesting());
label()->SizeToFit(required_size.width() - 1);
gfx::Size narrow_size = label()->GetPreferredSize();
EXPECT_GT(required_size.width(), narrow_size.width());
EXPECT_LT(required_size.height(), narrow_size.height());
// SetBounds() doesn't change the preferred size.
label()->SetBounds(0, 0, narrow_size.width() - 1, narrow_size.height());
EXPECT_EQ(narrow_size, label()->GetPreferredSize());
// Paint() doesn't change the preferred size.
gfx::Canvas canvas;
label()->OnPaint(&canvas);
EXPECT_EQ(narrow_size, label()->GetPreferredSize());
}
// Check that labels support GetTooltipHandlerForPoint.
TEST_F(LabelTest, GetTooltipHandlerForPoint) {
label()->SetText(u"A string that's long enough to exceed the bounds");
label()->SetBounds(0, 0, 10, 10);
// By default, labels start out as tooltip handlers.
ASSERT_TRUE(label()->GetHandlesTooltips());
// There's a default tooltip if the text is too big to fit.
EXPECT_EQ(label(), label()->GetTooltipHandlerForPoint(gfx::Point(2, 2)));
// If tooltip handling is disabled, the label should not provide a tooltip
// handler.
label()->SetHandlesTooltips(false);
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(2, 2)));
label()->SetHandlesTooltips(true);
// If there's no default tooltip, this should return NULL.
label()->SetBounds(0, 0, 500, 50);
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(2, 2)));
label()->SetTooltipText(u"a tooltip");
// If the point hits the label, and tooltip is set, the label should be
// returned as its tooltip handler.
EXPECT_EQ(label(), label()->GetTooltipHandlerForPoint(gfx::Point(2, 2)));
// Additionally, GetTooltipHandlerForPoint should verify that the label
// actually contains the point.
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(2, 51)));
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(-1, 20)));
// Again, if tooltip handling is disabled, the label should not provide a
// tooltip handler.
label()->SetHandlesTooltips(false);
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(2, 2)));
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(2, 51)));
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(-1, 20)));
label()->SetHandlesTooltips(true);
// GetTooltipHandlerForPoint works should work in child bounds.
label()->SetBounds(2, 2, 10, 10);
EXPECT_EQ(label(), label()->GetTooltipHandlerForPoint(gfx::Point(1, 5)));
EXPECT_FALSE(label()->GetTooltipHandlerForPoint(gfx::Point(3, 11)));
}
// Check that label releases its internal layout data when it's unnecessary.
TEST_F(LabelTest, ResetRenderTextData) {
label()->SetText(u"Example");
label()->SizeToPreferredSize();
gfx::Size preferred_size = label()->GetPreferredSize();
EXPECT_NE(gfx::Size(), preferred_size);
EXPECT_FALSE(label()->display_text_);
gfx::Canvas canvas(preferred_size, 1.0f, true);
label()->OnPaint(&canvas);
EXPECT_TRUE(label()->display_text_);
// Label should recreate its RenderText object when it's invisible, to release
// the layout structures and data.
label()->SetVisible(false);
EXPECT_FALSE(label()->display_text_);
// Querying fields or size information should not recompute the layout
// unnecessarily.
EXPECT_EQ(u"Example", label()->GetText());
EXPECT_FALSE(label()->display_text_);
EXPECT_EQ(preferred_size, label()->GetPreferredSize());
EXPECT_FALSE(label()->display_text_);
// RenderText data should be back when it's necessary.
label()->SetVisible(true);
EXPECT_FALSE(label()->display_text_);
label()->OnPaint(&canvas);
EXPECT_TRUE(label()->display_text_);
// Changing layout just resets |display_text_|. It'll recover next time it's
// drawn.
label()->SetBounds(0, 0, 10, 10);
EXPECT_FALSE(label()->display_text_);
label()->OnPaint(&canvas);
EXPECT_TRUE(label()->display_text_);
}
TEST_F(LabelTest, MultilineSupportedRenderText) {
label()->SetText(u"Example of\nmultilined label");
label()->SetMultiLine(true);
label()->SizeToPreferredSize();
gfx::Canvas canvas(label()->GetPreferredSize(), 1.0f, true);
label()->OnPaint(&canvas);
// There's only RenderText instance, which should have multiple lines.
ASSERT_TRUE(label()->display_text_);
EXPECT_EQ(2u, label()->display_text_->GetNumLines());
}
// Ensures SchedulePaint() calls are not made in OnPaint().
TEST_F(LabelTest, NoSchedulePaintInOnPaint) {
TestLabel label;
int count = 0;
const auto expect_paint_count_increased = [&]() {
EXPECT_GT(label.schedule_paint_count(), count);
count = label.schedule_paint_count();
};
// Initialization should schedule at least one paint, but the precise number
// doesn't really matter.
expect_paint_count_increased();
// Painting should never schedule another paint.
label.SimulatePaint();
EXPECT_EQ(count, label.schedule_paint_count());
// Test a few things that should schedule paints. Multiple times is OK.
label.SetEnabled(false);
expect_paint_count_increased();
label.SetText(label.GetText() + u"Changed");
expect_paint_count_increased();
label.SizeToPreferredSize();
expect_paint_count_increased();
label.SetEnabledColor(SK_ColorBLUE);
expect_paint_count_increased();
label.SimulatePaint();
EXPECT_EQ(count, label.schedule_paint_count()); // Unchanged.
}
TEST_F(LabelTest, EmptyLabel) {
label()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
label()->RequestFocus();
label()->SizeToPreferredSize();
EXPECT_TRUE(label()->size().IsEmpty());
// With no text, neither links nor labels have a size in any dimension.
Link concrete_link;
EXPECT_TRUE(concrete_link.GetPreferredSize().IsEmpty());
}
TEST_F(LabelTest, CanForceDirectionality) {
Label bidi_text_force_url(ToRTL("0123456") + u".com", 0, style::STYLE_PRIMARY,
gfx::DirectionalityMode::DIRECTIONALITY_AS_URL);
EXPECT_EQ(base::i18n::TextDirection::LEFT_TO_RIGHT,
bidi_text_force_url.GetTextDirectionForTesting());
Label rtl_text_force_ltr(ToRTL("0123456"), 0, style::STYLE_PRIMARY,
gfx::DirectionalityMode::DIRECTIONALITY_FORCE_LTR);
EXPECT_EQ(base::i18n::TextDirection::LEFT_TO_RIGHT,
rtl_text_force_ltr.GetTextDirectionForTesting());
Label ltr_text_force_rtl(u"0123456", 0, style::STYLE_PRIMARY,
gfx::DirectionalityMode::DIRECTIONALITY_FORCE_RTL);
EXPECT_EQ(base::i18n::TextDirection::RIGHT_TO_LEFT,
ltr_text_force_rtl.GetTextDirectionForTesting());
SetRTL(true);
Label ltr_use_ui(u"0123456", 0, style::STYLE_PRIMARY,
gfx::DirectionalityMode::DIRECTIONALITY_FROM_UI);
EXPECT_EQ(base::i18n::TextDirection::RIGHT_TO_LEFT,
ltr_use_ui.GetTextDirectionForTesting());
SetRTL(false);
Label rtl_use_ui(ToRTL("0123456"), 0, style::STYLE_PRIMARY,
gfx::DirectionalityMode::DIRECTIONALITY_FROM_UI);
EXPECT_EQ(base::i18n::TextDirection::LEFT_TO_RIGHT,
rtl_use_ui.GetTextDirectionForTesting());
}
TEST_F(LabelTest, DefaultDirectionalityIsFromText) {
Label ltr(u"Foo");
EXPECT_EQ(base::i18n::TextDirection::LEFT_TO_RIGHT,
ltr.GetTextDirectionForTesting());
Label rtl(ToRTL("0123456"));
EXPECT_EQ(base::i18n::TextDirection::RIGHT_TO_LEFT,
rtl.GetTextDirectionForTesting());
}
TEST_F(LabelTest, IsDisplayTextTruncated) {
const std::u16string text = u"A random string";
label()->SetText(text);
gfx::Size zero_size;
label()->SetElideBehavior(gfx::ELIDE_TAIL);
label()->SetBoundsRect(gfx::Rect(zero_size));
EXPECT_TRUE(label()->IsDisplayTextTruncated());
label()->SetElideBehavior(gfx::NO_ELIDE);
EXPECT_TRUE(label()->IsDisplayTextTruncated());
gfx::Size minimum_size(1, 1);
label()->SetBoundsRect(gfx::Rect(minimum_size));
EXPECT_TRUE(label()->IsDisplayTextTruncated());
gfx::Size enough_size(100, 100);
label()->SetBoundsRect(gfx::Rect(enough_size));
EXPECT_FALSE(label()->IsDisplayTextTruncated());
const std::u16string empty_text;
label()->SetText(empty_text);
EXPECT_FALSE(label()->IsDisplayTextTruncated());
label()->SetBoundsRect(gfx::Rect(zero_size));
EXPECT_FALSE(label()->IsDisplayTextTruncated());
}
TEST_F(LabelTest, TextChangedCallback) {
bool text_changed = false;
auto subscription = label()->AddTextChangedCallback(base::BindRepeating(
[](bool* text_changed) { *text_changed = true; }, &text_changed));
label()->SetText(u"abc");
EXPECT_TRUE(text_changed);
}
// Verify that GetSubstringBounds returns the correct bounds, accounting for
// label insets.
TEST_F(LabelTest, GetSubstringBounds) {
label()->SetText(u"abc");
auto substring_bounds = label()->GetSubstringBounds(gfx::Range(0, 3));
EXPECT_EQ(1u, substring_bounds.size());
auto insets = gfx::Insets::TLBR(2, 3, 4, 5);
label()->SetBorder(CreateEmptyBorder(insets));
auto substring_bounds_with_inset =
label()->GetSubstringBounds(gfx::Range(0, 3));
EXPECT_EQ(1u, substring_bounds_with_inset.size());
EXPECT_EQ(substring_bounds[0].x() + 3, substring_bounds_with_inset[0].x());
EXPECT_EQ(substring_bounds[0].y() + 2, substring_bounds_with_inset[0].y());
EXPECT_EQ(substring_bounds[0].width(),
substring_bounds_with_inset[0].width());
EXPECT_EQ(substring_bounds[0].height(),
substring_bounds_with_inset[0].height());
}
// TODO(crbug.com/1139395): Enable on ChromeOS along with the DCHECK in Label.
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_ChecksSubpixelRenderingOntoOpaqueSurface \
DISABLED_ChecksSubpixelRenderingOntoOpaqueSurface
#else
#define MAYBE_ChecksSubpixelRenderingOntoOpaqueSurface \
ChecksSubpixelRenderingOntoOpaqueSurface
#endif
// Ensures DCHECK for subpixel rendering on transparent layer is working.
TEST_F(LabelTest, MAYBE_ChecksSubpixelRenderingOntoOpaqueSurface) {
View view;
Label* label = view.AddChildView(std::make_unique<TestLabel>());
EXPECT_TRUE(label->GetSubpixelRenderingEnabled());
gfx::Canvas canvas;
// Painting on a view not painted to a layer should be fine.
label->OnPaint(&canvas);
// Painting to an opaque layer should also be fine.
view.SetPaintToLayer();
label->OnPaint(&canvas);
// Set up a transparent layer for the parent view.
view.layer()->SetFillsBoundsOpaquely(false);
// Painting on a transparent layer should DCHECK.
EXPECT_DCHECK_DEATH(label->OnPaint(&canvas));
// We should not DCHECK if the check is skipped.
label->SetSkipSubpixelRenderingOpacityCheck(true);
label->OnPaint(&canvas);
label->SetSkipSubpixelRenderingOpacityCheck(false);
// Painting onto a transparent layer should not DCHECK if there's an opaque
// background in a parent of the Label.
view.SetBackground(CreateSolidBackground(SK_ColorWHITE));
label->OnPaint(&canvas);
}
TEST_F(LabelSelectionTest, Selectable) {
// By default, labels don't support text selection.
EXPECT_FALSE(label()->GetSelectable());
ASSERT_TRUE(label()->SetSelectable(true));
EXPECT_TRUE(label()->GetSelectable());
// Verify that making a label multiline still causes the label to support text
// selection.
label()->SetMultiLine(true);
EXPECT_TRUE(label()->GetSelectable());
// Verify that obscuring the label text causes the label to not support text
// selection.
label()->SetObscured(true);
EXPECT_FALSE(label()->GetSelectable());
}
// Verify that labels supporting text selection get focus on clicks.
TEST_F(LabelSelectionTest, FocusOnClick) {
label()->SetText(u"text");
label()->SizeToPreferredSize();
// By default, labels don't get focus on click.
PerformClick(gfx::Point());
EXPECT_NE(label(), GetFocusedView());
ASSERT_TRUE(label()->SetSelectable(true));
PerformClick(gfx::Point());
EXPECT_EQ(label(), GetFocusedView());
}
// Verify that labels supporting text selection do not get focus on tab
// traversal by default.
TEST_F(LabelSelectionTest, FocusTraversal) {
// Add another view before |label()|.
View* view = new View();
view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget()->GetContentsView()->AddChildViewAt(view, 0);
// By default, labels are not focusable.
view->RequestFocus();
EXPECT_EQ(view, GetFocusedView());
widget()->GetFocusManager()->AdvanceFocus(false);
EXPECT_NE(label(), GetFocusedView());
// On enabling text selection, labels can get focus on clicks but not via tab
// traversal.
view->RequestFocus();
EXPECT_EQ(view, GetFocusedView());
EXPECT_TRUE(label()->SetSelectable(true));
widget()->GetFocusManager()->AdvanceFocus(false);
EXPECT_NE(label(), GetFocusedView());
// A label with FocusBehavior::ALWAYS should get focus via tab traversal.
view->RequestFocus();
EXPECT_EQ(view, GetFocusedView());
EXPECT_TRUE(label()->SetSelectable(false));
label()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget()->GetFocusManager()->AdvanceFocus(false);
EXPECT_EQ(label(), GetFocusedView());
}
// Verify label text selection behavior on double and triple clicks.
TEST_F(LabelSelectionTest, DoubleTripleClick) {
label()->SetText(u"Label double click");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformClick(GetCursorPoint(0));
EXPECT_TRUE(GetSelectedText().empty());
// Double clicking should select the word under cursor.
PerformClick(GetCursorPoint(0));
EXPECT_EQ(u"Label", GetSelectedText());
// Triple clicking should select all the text.
PerformClick(GetCursorPoint(0));
EXPECT_EQ(label()->GetText(), GetSelectedText());
// Clicking again should alternate to double click.
PerformClick(GetCursorPoint(0));
EXPECT_EQ(u"Label", GetSelectedText());
// Clicking at another location should clear the selection.
PerformClick(GetCursorPoint(8));
EXPECT_TRUE(GetSelectedText().empty());
PerformClick(GetCursorPoint(8));
EXPECT_EQ(u"double", GetSelectedText());
}
// Verify label text selection behavior on mouse drag.
TEST_F(LabelSelectionTest, MouseDrag) {
label()->SetText(u"Label mouse drag");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformMousePress(GetCursorPoint(5));
PerformMouseDragTo(GetCursorPoint(0));
EXPECT_EQ(u"Label", GetSelectedText());
PerformMouseDragTo(GetCursorPoint(8));
EXPECT_EQ(u" mo", GetSelectedText());
PerformMouseDragTo(gfx::Point(200, GetCursorPoint(0).y()));
PerformMouseRelease(gfx::Point(200, GetCursorPoint(0).y()));
EXPECT_EQ(u" mouse drag", GetSelectedText());
event_generator()->PressKey(ui::VKEY_C, kControlCommandModifier);
EXPECT_EQ(u" mouse drag", GetClipboardText(ui::ClipboardBuffer::kCopyPaste));
}
TEST_F(LabelSelectionTest, MouseDragMultilineLTR) {
label()->SetMultiLine(true);
label()->SetText(u"abcd\nefgh");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
ASSERT_EQ(2u, GetLineCount());
PerformMousePress(GetCursorPoint(2));
PerformMouseDragTo(GetCursorPoint(0));
EXPECT_EQ(u"ab", GetSelectedText());
PerformMouseDragTo(GetCursorPoint(7));
EXPECT_EQ(u"cd\nef", GetSelectedText());
PerformMouseDragTo(gfx::Point(-5, GetCursorPoint(6).y()));
EXPECT_EQ(u"cd\n", GetSelectedText());
PerformMouseDragTo(gfx::Point(100, GetCursorPoint(6).y()));
EXPECT_EQ(u"cd\nefgh", GetSelectedText());
const gfx::Point points[] = {
{GetCursorPoint(1).x(), -5}, // NW.
{GetCursorPoint(2).x(), -5}, // NORTH.
{GetCursorPoint(3).x(), -5}, // NE.
{GetCursorPoint(8).x(), 100}, // SE.
{GetCursorPoint(7).x(), 100}, // SOUTH.
{GetCursorPoint(6).x(), 100}, // SW.
};
constexpr const char16_t* kExtendLeft = u"ab";
constexpr const char16_t* kExtendRight = u"cd\nefgh";
// For multiline, N* extends left, S* extends right.
PerformMouseDragTo(points[NW]);
EXPECT_EQ(kExtends ? kExtendLeft : u"b", GetSelectedText());
PerformMouseDragTo(points[NORTH]);
EXPECT_EQ(kExtends ? kExtendLeft : u"", GetSelectedText());
PerformMouseDragTo(points[NE]);
EXPECT_EQ(kExtends ? kExtendLeft : u"c", GetSelectedText());
PerformMouseDragTo(points[SE]);
EXPECT_EQ(kExtends ? kExtendRight : u"cd\nefg", GetSelectedText());
PerformMouseDragTo(points[SOUTH]);
EXPECT_EQ(kExtends ? kExtendRight : u"cd\nef", GetSelectedText());
PerformMouseDragTo(points[SW]);
EXPECT_EQ(kExtends ? kExtendRight : u"cd\ne", GetSelectedText());
}
// Single line fields consider the x offset as well. Ties go to the right.
TEST_F(LabelSelectionTest, MouseDragSingleLineLTR) {
label()->SetText(u"abcdef");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformMousePress(GetCursorPoint(2));
const gfx::Point points[] = {
{GetCursorPoint(1).x(), -5}, // NW.
{GetCursorPoint(2).x(), -5}, // NORTH.
{GetCursorPoint(3).x(), -5}, // NE.
{GetCursorPoint(3).x(), 100}, // SE.
{GetCursorPoint(2).x(), 100}, // SOUTH.
{GetCursorPoint(1).x(), 100}, // SW.
};
constexpr const char16_t* kExtendLeft = u"ab";
constexpr const char16_t* kExtendRight = u"cdef";
// For single line, western directions extend left, all others extend right.
PerformMouseDragTo(points[NW]);
EXPECT_EQ(kExtends ? kExtendLeft : u"b", GetSelectedText());
PerformMouseDragTo(points[NORTH]);
EXPECT_EQ(kExtends ? kExtendRight : u"", GetSelectedText());
PerformMouseDragTo(points[NE]);
EXPECT_EQ(kExtends ? kExtendRight : u"c", GetSelectedText());
PerformMouseDragTo(points[SE]);
EXPECT_EQ(kExtends ? kExtendRight : u"c", GetSelectedText());
PerformMouseDragTo(points[SOUTH]);
EXPECT_EQ(kExtends ? kExtendRight : u"", GetSelectedText());
PerformMouseDragTo(points[SW]);
EXPECT_EQ(kExtends ? kExtendLeft : u"b", GetSelectedText());
}
TEST_F(LabelSelectionTest, MouseDragMultilineRTL) {
label()->SetMultiLine(true);
label()->SetText(ToRTL("012\n345"));
// Sanity check.
EXPECT_EQ(u"\x5d0\x5d1\x5d2\n\x5d3\x5d4\x5d5", label()->GetText());
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
ASSERT_EQ(2u, GetLineCount());
PerformMousePress(GetCursorPoint(1)); // Note: RTL drag starts at 1, not 2.
PerformMouseDragTo(GetCursorPoint(0));
EXPECT_EQ(ToRTL("0"), GetSelectedText());
PerformMouseDragTo(GetCursorPoint(6));
EXPECT_EQ(ToRTL("12\n34"), GetSelectedText());
PerformMouseDragTo(gfx::Point(-5, GetCursorPoint(6).y()));
EXPECT_EQ(ToRTL("12\n345"), GetSelectedText());
PerformMouseDragTo(gfx::Point(100, GetCursorPoint(6).y()));
EXPECT_EQ(ToRTL("12\n"), GetSelectedText());
const gfx::Point points[] = {
{GetCursorPoint(2).x(), -5}, // NW: Now towards the end of the string.
{GetCursorPoint(1).x(), -5}, // NORTH,
{GetCursorPoint(0).x(), -5}, // NE: Towards the start.
{GetCursorPoint(4).x(), 100}, // SE.
{GetCursorPoint(5).x(), 100}, // SOUTH.
{GetCursorPoint(6).x(), 100}, // SW.
};
// Visual right, so to the beginning of the string for RTL.
const std::u16string extend_right = ToRTL("0");
const std::u16string extend_left = ToRTL("12\n345");
// For multiline, N* extends right, S* extends left.
PerformMouseDragTo(points[NW]);
EXPECT_EQ(kExtends ? extend_right : ToRTL("1"), GetSelectedText());
PerformMouseDragTo(points[NORTH]);
EXPECT_EQ(kExtends ? extend_right : ToRTL(""), GetSelectedText());
PerformMouseDragTo(points[NE]);
EXPECT_EQ(kExtends ? extend_right : ToRTL("0"), GetSelectedText());
PerformMouseDragTo(points[SE]);
EXPECT_EQ(kExtends ? extend_left : ToRTL("12\n"), GetSelectedText());
PerformMouseDragTo(points[SOUTH]);
EXPECT_EQ(kExtends ? extend_left : ToRTL("12\n3"), GetSelectedText());
PerformMouseDragTo(points[SW]);
EXPECT_EQ(kExtends ? extend_left : ToRTL("12\n34"), GetSelectedText());
}
TEST_F(LabelSelectionTest, MouseDragSingleLineRTL) {
label()->SetText(ToRTL("0123456"));
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformMousePress(GetCursorPoint(1));
const gfx::Point points[] = {
{GetCursorPoint(2).x(), -5}, // NW.
{GetCursorPoint(1).x(), -5}, // NORTH.
{GetCursorPoint(0).x(), -5}, // NE.
{GetCursorPoint(0).x(), 100}, // SE.
{GetCursorPoint(1).x(), 100}, // SOUTH.
{GetCursorPoint(2).x(), 100}, // SW.
};
// Visual right, so to the beginning of the string for RTL.
const std::u16string extend_right = ToRTL("0");
const std::u16string extend_left = ToRTL("123456");
// For single line, western directions extend left, all others extend right.
PerformMouseDragTo(points[NW]);
EXPECT_EQ(kExtends ? extend_left : ToRTL("1"), GetSelectedText());
PerformMouseDragTo(points[NORTH]);
EXPECT_EQ(kExtends ? extend_right : ToRTL(""), GetSelectedText());
PerformMouseDragTo(points[NE]);
EXPECT_EQ(kExtends ? extend_right : ToRTL("0"), GetSelectedText());
PerformMouseDragTo(points[SE]);
EXPECT_EQ(kExtends ? extend_right : ToRTL("0"), GetSelectedText());
PerformMouseDragTo(points[SOUTH]);
EXPECT_EQ(kExtends ? extend_right : ToRTL(""), GetSelectedText());
PerformMouseDragTo(points[SW]);
EXPECT_EQ(kExtends ? extend_left : ToRTL("1"), GetSelectedText());
}
// Verify the initially selected word on a double click, remains selected on
// mouse dragging.
TEST_F(LabelSelectionTest, MouseDragWord) {
label()->SetText(u"Label drag word");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformClick(GetCursorPoint(8));
PerformMousePress(GetCursorPoint(8));
EXPECT_EQ(u"drag", GetSelectedText());
PerformMouseDragTo(GetCursorPoint(0));
EXPECT_EQ(u"Label drag", GetSelectedText());
PerformMouseDragTo(gfx::Point(200, GetCursorPoint(0).y()));
PerformMouseRelease(gfx::Point(200, GetCursorPoint(0).y()));
EXPECT_EQ(u"drag word", GetSelectedText());
}
// TODO(crbug.com/1201128): LabelSelectionTest.SelectionClipboard is failing on
// linux-lacros.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_SelectionClipboard DISABLED_SelectionClipboard
#else
#define MAYBE_SelectionClipboard SelectionClipboard
#endif
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
// Verify selection clipboard behavior on text selection.
TEST_F(LabelSelectionTest, MAYBE_SelectionClipboard) {
label()->SetText(u"Label selection clipboard");
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
// Verify programmatic modification of selection, does not modify the
// selection clipboard.
label()->SelectRange(gfx::Range(2, 5));
EXPECT_EQ(u"bel", GetSelectedText());
EXPECT_TRUE(GetClipboardText(ui::ClipboardBuffer::kSelection).empty());
// Verify text selection using the mouse updates the selection clipboard.
PerformMousePress(GetCursorPoint(5));
PerformMouseDragTo(GetCursorPoint(0));
PerformMouseRelease(GetCursorPoint(0));
EXPECT_EQ(u"Label", GetSelectedText());
EXPECT_EQ(u"Label", GetClipboardText(ui::ClipboardBuffer::kSelection));
}
#endif
// Verify that keyboard shortcuts for Copy and Select All work when a selectable
// label is focused.
TEST_F(LabelSelectionTest, KeyboardActions) {
const std::u16string initial_text = u"Label keyboard actions";
label()->SetText(initial_text);
label()->SizeToPreferredSize();
ASSERT_TRUE(label()->SetSelectable(true));
PerformClick(gfx::Point());
EXPECT_EQ(label(), GetFocusedView());
event_generator()->PressKey(ui::VKEY_A, kControlCommandModifier);
EXPECT_EQ(initial_text, GetSelectedText());
event_generator()->PressKey(ui::VKEY_C, kControlCommandModifier);
EXPECT_EQ(initial_text, GetClipboardText(ui::ClipboardBuffer::kCopyPaste));
// The selection should get cleared on changing the text, but focus should not
// be affected.
const std::u16string new_text = u"Label obscured text";
label()->SetText(new_text);
EXPECT_FALSE(label()->HasSelection());
EXPECT_EQ(label(), GetFocusedView());
// Obscured labels do not support text selection.
label()->SetObscured(true);
EXPECT_FALSE(label()->GetSelectable());
event_generator()->PressKey(ui::VKEY_A, kControlCommandModifier);
EXPECT_EQ(std::u16string(), GetSelectedText());
}
// Verify the context menu options are enabled and disabled appropriately.
TEST_F(LabelSelectionTest, ContextMenuContents) {
label()->SetText(u"Label context menu");
label()->SizeToPreferredSize();
// A non-selectable label should not show a context menu and both copy and
// select-all context menu items should be disabled for it.
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kCopy));
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kSelectAll));
// For a selectable label with no selection, only kSelectAll should be
// enabled.
ASSERT_TRUE(label()->SetSelectable(true));
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kCopy));
EXPECT_TRUE(IsMenuCommandEnabled(Label::MenuCommands::kSelectAll));
// For a selectable label with a selection, both copy and select-all should
// be enabled.
label()->SelectRange(gfx::Range(0, 4));
EXPECT_TRUE(IsMenuCommandEnabled(Label::MenuCommands::kCopy));
EXPECT_TRUE(IsMenuCommandEnabled(Label::MenuCommands::kSelectAll));
// Ensure unsupported commands are not enabled.
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kLastCommandId + 1));
// An obscured label would not show a context menu and both copy and
// select-all should be disabled for it.
label()->SetObscured(true);
EXPECT_FALSE(label()->GetSelectable());
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kCopy));
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kSelectAll));
label()->SetObscured(false);
// For an empty label, both copy and select-all should be disabled.
label()->SetText(std::u16string());
ASSERT_TRUE(label()->SetSelectable(true));
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kCopy));
EXPECT_FALSE(IsMenuCommandEnabled(Label::MenuCommands::kSelectAll));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/label_unittest.cc | C++ | unknown | 64,005 |
// 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/link.h"
#include "build/build_config.h"
#include "base/check.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/event.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/font_list.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/style/platform_style.h"
namespace views {
Link::Link(const std::u16string& title, int text_context, int text_style)
: Label(title, text_context, text_style) {
RecalculateFont();
enabled_changed_subscription_ = AddEnabledChangedCallback(
base::BindRepeating(&Link::RecalculateFont, base::Unretained(this)));
SetAccessibilityProperties(ax::mojom::Role::kLink, title);
// Prevent invisible links from being announced by screen reader.
GetViewAccessibility().OverrideIsIgnored(title.empty());
// Label() indirectly calls SetText(), but at that point our virtual override
// will not be reached. Call it explicitly here to configure focus.
SetText(GetText());
views::FocusRing::Install(this);
}
Link::~Link() = default;
SkColor Link::GetColor() const {
// TODO(tapted): Use style::GetColor().
const ui::ColorProvider* color_provider = GetColorProvider();
DCHECK(color_provider);
if (!GetEnabled())
return color_provider->GetColor(ui::kColorLinkForegroundDisabled);
if (requested_enabled_color_.has_value())
return requested_enabled_color_.value();
return color_provider->GetColor(pressed_ ? ui::kColorLinkForegroundPressed
: ui::kColorLinkForeground);
}
void Link::SetForceUnderline(bool force_underline) {
if (force_underline_ == force_underline)
return;
force_underline_ = force_underline;
RecalculateFont();
}
bool Link::GetForceUnderline() const {
return force_underline_;
}
ui::Cursor Link::GetCursor(const ui::MouseEvent& event) {
if (!GetEnabled())
return ui::Cursor();
return ui::mojom::CursorType::kHand;
}
bool Link::GetCanProcessEventsWithinSubtree() const {
// Links need to be able to accept events (e.g., clicking) even though
// in general Labels do not.
return View::GetCanProcessEventsWithinSubtree();
}
void Link::OnMouseEntered(const ui::MouseEvent& event) {
RecalculateFont();
}
void Link::OnMouseExited(const ui::MouseEvent& event) {
RecalculateFont();
}
bool Link::OnMousePressed(const ui::MouseEvent& event) {
if (!GetEnabled() ||
(!event.IsLeftMouseButton() && !event.IsMiddleMouseButton()))
return false;
SetPressed(true);
return true;
}
bool Link::OnMouseDragged(const ui::MouseEvent& event) {
SetPressed(GetEnabled() &&
(event.IsLeftMouseButton() || event.IsMiddleMouseButton()) &&
HitTestPoint(event.location()));
return true;
}
void Link::OnMouseReleased(const ui::MouseEvent& event) {
// Change the highlight first just in case this instance is deleted
// while calling the controller
OnMouseCaptureLost();
if (GetEnabled() &&
(event.IsLeftMouseButton() || event.IsMiddleMouseButton()) &&
HitTestPoint(event.location()))
OnClick(event);
}
void Link::OnMouseCaptureLost() {
SetPressed(false);
}
bool Link::OnKeyPressed(const ui::KeyEvent& event) {
bool activate = (((event.key_code() == ui::VKEY_SPACE) &&
(event.flags() & ui::EF_ALT_DOWN) == 0) ||
(event.key_code() == ui::VKEY_RETURN &&
PlatformStyle::kReturnClicksFocusedControl));
if (!activate)
return false;
SetPressed(false);
OnClick(event);
return true;
}
void Link::OnGestureEvent(ui::GestureEvent* event) {
if (!GetEnabled())
return;
if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
SetPressed(true);
} else if (event->type() == ui::ET_GESTURE_TAP) {
OnClick(*event);
} else {
SetPressed(false);
return;
}
event->SetHandled();
}
bool Link::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
// Don't process Space and Return (depending on the platform) as an
// accelerator.
return event.key_code() == ui::VKEY_SPACE ||
(event.key_code() == ui::VKEY_RETURN &&
PlatformStyle::kReturnClicksFocusedControl);
}
void Link::OnFocus() {
Label::OnFocus();
RecalculateFont();
// We render differently focused.
SchedulePaint();
}
void Link::OnBlur() {
Label::OnBlur();
RecalculateFont();
// We render differently focused.
SchedulePaint();
}
void Link::SetFontList(const gfx::FontList& font_list) {
Label::SetFontList(font_list);
RecalculateFont();
}
void Link::SetText(const std::u16string& text) {
Label::SetText(text);
// Prevent invisible links from being announced by screen reader.
GetViewAccessibility().OverrideIsIgnored(text.empty());
ConfigureFocus();
}
void Link::OnThemeChanged() {
Label::OnThemeChanged();
Label::SetEnabledColor(GetColor());
}
void Link::SetEnabledColor(SkColor color) {
requested_enabled_color_ = color;
if (GetWidget())
Label::SetEnabledColor(GetColor());
}
bool Link::IsSelectionSupported() const {
return false;
}
void Link::SetPressed(bool pressed) {
if (pressed_ != pressed) {
pressed_ = pressed;
Label::SetEnabledColor(GetColor());
RecalculateFont();
SchedulePaint();
}
}
void Link::OnClick(const ui::Event& event) {
RequestFocus();
if (callback_)
callback_.Run(event);
}
void Link::RecalculateFont() {
const int style = font_list().GetFontStyle();
const int intended_style =
((GetEnabled() && (HasFocus() || IsMouseHovered())) || force_underline_)
? (style | gfx::Font::UNDERLINE)
: (style & ~gfx::Font::UNDERLINE);
if (style != intended_style)
Label::SetFontList(font_list().DeriveWithStyle(intended_style));
}
void Link::ConfigureFocus() {
// Disable focusability for empty links.
if (GetText().empty()) {
SetFocusBehavior(FocusBehavior::NEVER);
} else {
#if BUILDFLAG(IS_MAC)
SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY);
#else
SetFocusBehavior(FocusBehavior::ALWAYS);
#endif
}
}
BEGIN_METADATA(Link, Label)
ADD_READONLY_PROPERTY_METADATA(SkColor, Color, ui::metadata::SkColorConverter)
ADD_PROPERTY_METADATA(bool, ForceUnderline)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link.cc | C++ | unknown | 6,648 |
// 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.
#ifndef UI_VIEWS_CONTROLS_LINK_H_
#define UI_VIEWS_CONTROLS_LINK_H_
#include <memory>
#include <string>
#include <utility>
#include "base/functional/callback.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/color_palette.h"
#include "ui/views/controls/label.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/style/typography.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
//
// Link class
//
// A Link is a label subclass that looks like an HTML link. It has a
// controller which is notified when a click occurs.
//
////////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT Link : public Label {
public:
METADATA_HEADER(Link);
// A callback to be called when the link is clicked. Closures are also
// accepted; see below.
using ClickedCallback = base::RepeatingCallback<void(const ui::Event& event)>;
explicit Link(const std::u16string& title = std::u16string(),
int text_context = style::CONTEXT_LABEL,
int text_style = style::STYLE_LINK);
Link(const Link&) = delete;
Link& operator=(const Link&) = delete;
~Link() override;
// Allow providing callbacks that expect either zero or one args, since many
// callers don't care about the argument and can avoid adapter functions this
// way.
void SetCallback(base::RepeatingClosure callback) {
// Adapt this closure to a ClickedCallback by discarding the extra arg.
callback_ =
base::BindRepeating([](base::RepeatingClosure closure,
const ui::Event& event) { closure.Run(); },
std::move(callback));
}
void SetCallback(ClickedCallback callback) {
callback_ = std::move(callback);
}
SkColor GetColor() const;
void SetForceUnderline(bool force_underline);
bool GetForceUnderline() const;
// Label:
ui::Cursor GetCursor(const ui::MouseEvent& event) override;
bool GetCanProcessEventsWithinSubtree() const override;
void OnMouseEntered(const ui::MouseEvent& event) override;
void OnMouseExited(const ui::MouseEvent& event) override;
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnMouseCaptureLost() override;
bool OnKeyPressed(const ui::KeyEvent& event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override;
void OnFocus() override;
void OnBlur() override;
void SetFontList(const gfx::FontList& font_list) override;
void SetText(const std::u16string& text) override;
void OnThemeChanged() override;
void SetEnabledColor(SkColor color) override;
bool IsSelectionSupported() const override;
private:
virtual void RecalculateFont();
void SetPressed(bool pressed);
void OnClick(const ui::Event& event);
void ConfigureFocus();
ClickedCallback callback_;
// Whether the link is currently pressed.
bool pressed_ = false;
// The color when the link is neither pressed nor disabled.
absl::optional<SkColor> requested_enabled_color_;
base::CallbackListSubscription enabled_changed_subscription_;
// Whether the link text should use underline style regardless of enabled or
// focused state.
bool force_underline_ = true;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Link, Label)
VIEW_BUILDER_OVERLOAD_METHOD(SetCallback, base::RepeatingClosure)
VIEW_BUILDER_OVERLOAD_METHOD(SetCallback, Link::ClickedCallback)
VIEW_BUILDER_PROPERTY(bool, ForceUnderline)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Link)
#endif // UI_VIEWS_CONTROLS_LINK_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link.h | C++ | unknown | 3,989 |
// Copyright 2022 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/link_fragment.h"
#include <string>
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/link.h"
#include "ui/views/style/typography.h"
#include "ui/views/view_utils.h"
namespace views {
LinkFragment::LinkFragment(const std::u16string& title,
int text_context,
int text_style,
LinkFragment* other_fragment)
: Link(title, text_context, text_style),
prev_fragment_(this),
next_fragment_(this) {
// Connect to the previous fragment if it exists.
if (other_fragment)
Connect(other_fragment);
views::FocusRing::Install(this);
views::FocusRing::Get(this)->SetHasFocusPredicate([](View* view) -> bool {
auto* v = views::AsViewClass<LinkFragment>(view);
DCHECK(v);
if (v->HasFocus())
return true;
// Iterate through the loop of fragments until reaching the current fragment
// to see if any of them are focused. If so, this fragment will also be
// focused.
for (LinkFragment* current_fragment = v->next_fragment_;
current_fragment != v;
current_fragment = current_fragment->next_fragment_) {
if (current_fragment->HasFocus())
return true;
}
return false;
});
}
LinkFragment::~LinkFragment() {
Disconnect();
}
void LinkFragment::Connect(LinkFragment* other_fragment) {
DCHECK(prev_fragment_ == this);
DCHECK(next_fragment_ == this);
DCHECK(other_fragment);
next_fragment_ = other_fragment->next_fragment_;
other_fragment->next_fragment_->prev_fragment_ = this;
prev_fragment_ = other_fragment;
other_fragment->next_fragment_ = this;
}
void LinkFragment::Disconnect() {
DCHECK((prev_fragment_ != this) == (next_fragment_ != this));
if (prev_fragment_ != this) {
prev_fragment_->next_fragment_ = next_fragment_;
next_fragment_->prev_fragment_ = prev_fragment_;
}
}
bool LinkFragment::IsUnderlined() const {
return GetEnabled() &&
(HasFocus() || IsMouseHovered() || GetForceUnderline());
}
void LinkFragment::RecalculateFont() {
// Check whether any link fragment should be underlined.
bool should_be_underlined = IsUnderlined();
for (LinkFragment* current_fragment = next_fragment_;
!should_be_underlined && current_fragment != this;
current_fragment = current_fragment->next_fragment_) {
should_be_underlined = current_fragment->IsUnderlined();
}
// If the style differs from the current one, update.
if ((font_list().GetFontStyle() & gfx::Font::UNDERLINE) !=
should_be_underlined) {
auto MaybeUpdateStyle = [should_be_underlined](LinkFragment* fragment) {
const int style = fragment->font_list().GetFontStyle();
const int intended_style = should_be_underlined
? (style | gfx::Font::UNDERLINE)
: (style & ~gfx::Font::UNDERLINE);
fragment->Label::SetFontList(
fragment->font_list().DeriveWithStyle(intended_style));
fragment->SchedulePaint();
};
MaybeUpdateStyle(this);
views::FocusRing::Get(this)->SchedulePaint();
for (LinkFragment* current_fragment = next_fragment_;
current_fragment != this;
current_fragment = current_fragment->next_fragment_) {
MaybeUpdateStyle(current_fragment);
views::FocusRing::Get(current_fragment)->SchedulePaint();
}
}
}
BEGIN_METADATA(LinkFragment, Link)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link_fragment.cc | C++ | unknown | 3,691 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_LINK_FRAGMENT_H_
#define UI_VIEWS_CONTROLS_LINK_FRAGMENT_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/controls/link.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/style/typography.h"
namespace views {
// A `LinkFragment` can be used to represent a logical link that spans across
// multiple lines. Connected `LinkFragment`s adjust their style if any single
// one of them is hovered over of focused.
class VIEWS_EXPORT LinkFragment : public Link {
public:
METADATA_HEADER(LinkFragment);
explicit LinkFragment(const std::u16string& title = std::u16string(),
int text_context = style::CONTEXT_LABEL,
int text_style = style::STYLE_LINK,
LinkFragment* other_fragment = nullptr);
~LinkFragment() override;
LinkFragment(const LinkFragment&) = delete;
LinkFragment& operator=(const LinkFragment&) = delete;
private:
// Returns whether this fragment indicates that the entire link represented
// by it should be underlined.
bool IsUnderlined() const;
// Connects `this` to the `other_fragment`.
void Connect(LinkFragment* other_fragment);
// Disconnects `this` from any other fragments that it may be connected to.
void Disconnect();
// Recalculates the font style for this link fragment and, if it is changed,
// updates both this fragment and all other that are connected to it.
void RecalculateFont() override;
// Pointers to the previous and the next `LinkFragment` if the logical link
// represented by `this` consists of multiple such fragments (e.g. due to
// line breaks).
// If the logical link is just a single `LinkFragment` component, then these
// pointers point to `this`.
raw_ptr<LinkFragment> prev_fragment_;
raw_ptr<LinkFragment> next_fragment_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_LINK_FRAGMENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link_fragment.h | C++ | unknown | 2,055 |
// Copyright 2022 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/link_fragment.h"
#include <array>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/controls/base_control_test_widget.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
constexpr char16_t kLinkLabel[] = u"Test label";
class LinkFragmentTest : public test::BaseControlTestWidget {
public:
LinkFragmentTest() {
for (auto& fragment : fragments_) {
fragment = nullptr;
}
}
~LinkFragmentTest() override = default;
void SetUp() override {
test::BaseControlTestWidget::SetUp();
event_generator_ = std::make_unique<ui::test::EventGenerator>(
GetContext(), widget()->GetNativeWindow());
}
protected:
void CreateWidgetContent(View* container) override {
// Fragment 0 is stand-alone.
fragments_[0] =
container->AddChildView(std::make_unique<LinkFragment>(kLinkLabel));
gfx::Rect current_rect =
gfx::ScaleToEnclosedRect(container->GetLocalBounds(), 0.3f);
fragments_[0]->SetBoundsRect(current_rect);
int width = current_rect.width();
// Fragments 1 and 2 are connected.
current_rect.Offset(width, 0);
fragments_[1] =
container->AddChildView(std::make_unique<LinkFragment>(kLinkLabel));
fragments_[1]->SetBoundsRect(current_rect);
current_rect.Offset(width, 0);
fragments_[2] = container->AddChildView(std::make_unique<LinkFragment>(
kLinkLabel, style::CONTEXT_LABEL, style::STYLE_LINK, fragment(1)));
fragments_[2]->SetBoundsRect(current_rect);
}
LinkFragment* fragment(size_t index) {
DCHECK_LT(index, 3u);
return fragments_[index];
}
ui::test::EventGenerator* event_generator() { return event_generator_.get(); }
// Returns bounds of the fragment.
gfx::Rect GetBoundsForFragment(size_t index) {
return fragment(index)->GetBoundsInScreen();
}
private:
std::array<raw_ptr<LinkFragment>, 3> fragments_;
std::unique_ptr<ui::test::EventGenerator> event_generator_;
};
} // namespace
TEST_F(LinkFragmentTest, Metadata) {
for (size_t index = 0; index < 3; ++index) {
// Needed to avoid failing DCHECK when setting maximum width.
fragment(index)->SetMultiLine(true);
test::TestViewMetadata(fragment(index));
}
}
// Tests that hovering and unhovering a link adds and removes an underline
// under all connected fragments.
TEST_F(LinkFragmentTest, TestUnderlineOnHover) {
// A link fragment should be underlined.
const gfx::Point point_outside =
GetBoundsForFragment(2).bottom_right() + gfx::Vector2d(1, 1);
event_generator()->MoveMouseTo(point_outside);
EXPECT_FALSE(fragment(0)->IsMouseHovered());
const auto is_underlined = [this](size_t index) {
return !!(fragment(index)->font_list().GetFontStyle() &
gfx::Font::UNDERLINE);
};
EXPECT_TRUE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
// A non-hovered link fragment should not be underlined.
fragment(0)->SetForceUnderline(false);
fragment(1)->SetForceUnderline(false);
fragment(2)->SetForceUnderline(false);
EXPECT_FALSE(is_underlined(0));
EXPECT_FALSE(is_underlined(1));
EXPECT_FALSE(is_underlined(2));
// Hovering the first link fragment underlines it.
event_generator()->MoveMouseTo(GetBoundsForFragment(0).CenterPoint());
EXPECT_TRUE(fragment(0)->IsMouseHovered());
EXPECT_TRUE(is_underlined(0));
// The other link fragments stay non-hovered.
EXPECT_FALSE(is_underlined(1));
EXPECT_FALSE(is_underlined(2));
// Un-hovering the link removes the underline again.
event_generator()->MoveMouseTo(point_outside);
EXPECT_FALSE(fragment(0)->IsMouseHovered());
EXPECT_FALSE(is_underlined(0));
EXPECT_FALSE(is_underlined(1));
EXPECT_FALSE(is_underlined(2));
// Hovering the second link fragment underlines both the second and the
// third fragment.
event_generator()->MoveMouseTo(GetBoundsForFragment(1).CenterPoint());
EXPECT_TRUE(fragment(1)->IsMouseHovered());
EXPECT_FALSE(fragment(2)->IsMouseHovered());
EXPECT_FALSE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
// The same is true for hovering the third fragment.
event_generator()->MoveMouseTo(GetBoundsForFragment(2).CenterPoint());
EXPECT_TRUE(fragment(2)->IsMouseHovered());
EXPECT_FALSE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
// Moving outside removes the underline again.
event_generator()->MoveMouseTo(point_outside);
EXPECT_FALSE(is_underlined(0));
EXPECT_FALSE(is_underlined(1));
EXPECT_FALSE(is_underlined(2));
}
// Tests that focusing and unfocusing a link keeps the underline and adds a
// focus ring for all connected fragments.
TEST_F(LinkFragmentTest, TestUnderlineAndFocusRingOnFocus) {
const auto is_underlined = [this](size_t index) {
return !!(fragment(index)->font_list().GetFontStyle() &
gfx::Font::UNDERLINE);
};
// A non-focused link fragment should be underlined.
EXPECT_TRUE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
EXPECT_FALSE(views::FocusRing::Get(fragment(0))->ShouldPaintForTesting());
EXPECT_FALSE(views::FocusRing::Get(fragment(1))->ShouldPaintForTesting());
EXPECT_FALSE(views::FocusRing::Get(fragment(2))->ShouldPaintForTesting());
// Focusing on fragment 0, which is standalone, will only show focus ring for
// that fragment.
fragment(0)->RequestFocus();
EXPECT_TRUE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
EXPECT_TRUE(views::FocusRing::Get(fragment(0))->ShouldPaintForTesting());
EXPECT_FALSE(views::FocusRing::Get(fragment(1))->ShouldPaintForTesting());
EXPECT_FALSE(views::FocusRing::Get(fragment(2))->ShouldPaintForTesting());
// Focusing on fragment 1, which is connected to fragment 2, will focus both
// fragments 1 and 2.
fragment(1)->RequestFocus();
EXPECT_TRUE(is_underlined(0));
EXPECT_TRUE(is_underlined(1));
EXPECT_TRUE(is_underlined(2));
EXPECT_FALSE(views::FocusRing::Get(fragment(0))->ShouldPaintForTesting());
EXPECT_TRUE(views::FocusRing::Get(fragment(1))->ShouldPaintForTesting());
EXPECT_TRUE(views::FocusRing::Get(fragment(2))->ShouldPaintForTesting());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link_fragment_unittest.cc | C++ | unknown | 6,609 |
// 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 "ui/views/controls/link.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/ui_base_switches.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/border.h"
#include "ui/views/controls/base_control_test_widget.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
class LinkTest : public test::BaseControlTestWidget {
public:
LinkTest() = default;
LinkTest(const LinkTest&) = delete;
LinkTest& operator=(const LinkTest&) = delete;
~LinkTest() override = default;
void SetUp() override {
test::BaseControlTestWidget::SetUp();
event_generator_ = std::make_unique<ui::test::EventGenerator>(
GetContext(), widget()->GetNativeWindow());
}
protected:
void CreateWidgetContent(View* container) override {
// Create a widget containing a link which does not take the full size.
link_ = container->AddChildView(std::make_unique<Link>(u"TestLink"));
link_->SetBoundsRect(
gfx::ScaleToEnclosedRect(container->GetLocalBounds(), 0.5f));
}
Link* link() { return link_; }
ui::test::EventGenerator* event_generator() { return event_generator_.get(); }
public:
raw_ptr<Link> link_ = nullptr;
std::unique_ptr<ui::test::EventGenerator> event_generator_;
};
} // namespace
TEST_F(LinkTest, Metadata) {
link()->SetMultiLine(true);
test::TestViewMetadata(link());
}
TEST_F(LinkTest, TestLinkClick) {
bool link_clicked = false;
link()->SetCallback(base::BindRepeating(
[](bool* link_clicked) { *link_clicked = true; }, &link_clicked));
link()->SizeToPreferredSize();
gfx::Point point = link()->bounds().CenterPoint();
ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
link()->OnMouseReleased(release);
EXPECT_TRUE(link_clicked);
}
TEST_F(LinkTest, TestLinkTap) {
bool link_clicked = false;
link()->SetCallback(base::BindRepeating(
[](bool* link_clicked) { *link_clicked = true; }, &link_clicked));
link()->SizeToPreferredSize();
gfx::Point point = link()->bounds().CenterPoint();
ui::GestureEvent tap_event(point.x(), point.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP));
link()->OnGestureEvent(&tap_event);
EXPECT_TRUE(link_clicked);
}
// Tests that hovering and unhovering a link adds and removes an underline.
TEST_F(LinkTest, TestUnderlineOnHover) {
// A link should be underlined.
const gfx::Rect link_bounds = link()->GetBoundsInScreen();
const gfx::Point off_link = link_bounds.bottom_right() + gfx::Vector2d(1, 1);
event_generator()->MoveMouseTo(off_link);
EXPECT_FALSE(link()->IsMouseHovered());
const auto link_underlined = [link = link()]() {
return !!(link->font_list().GetFontStyle() & gfx::Font::UNDERLINE);
};
EXPECT_TRUE(link_underlined());
// A non-hovered link should should be underlined.
// For a11y, A link should be underlined by default. If forcefuly remove an
// underline, the underline appears according to hovering.
link()->SetForceUnderline(false);
EXPECT_FALSE(link_underlined());
// Hovering the link should underline it.
event_generator()->MoveMouseTo(link_bounds.CenterPoint());
EXPECT_TRUE(link()->IsMouseHovered());
EXPECT_TRUE(link_underlined());
// Un-hovering the link should remove the underline again.
event_generator()->MoveMouseTo(off_link);
EXPECT_FALSE(link()->IsMouseHovered());
EXPECT_FALSE(link_underlined());
}
// Tests that focusing and unfocusing a link keeps the underline and adds
// focus ring.
TEST_F(LinkTest, TestUnderlineAndFocusRingOnFocus) {
const auto link_underlined = [link = link()]() {
return !!(link->font_list().GetFontStyle() & gfx::Font::UNDERLINE);
};
// A non-focused link should be underlined and not have a focus ring.
EXPECT_TRUE(link_underlined());
EXPECT_FALSE(views::FocusRing::Get(link())->ShouldPaintForTesting());
// A focused link should be underlined and it should have a focus ring.
link()->RequestFocus();
EXPECT_TRUE(link_underlined());
EXPECT_TRUE(views::FocusRing::Get(link())->ShouldPaintForTesting());
}
TEST_F(LinkTest, AccessibleProperties) {
ui::AXNodeData data;
link()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"TestLink");
EXPECT_EQ(link()->GetAccessibleName(), u"TestLink");
EXPECT_EQ(data.role, ax::mojom::Role::kLink);
EXPECT_FALSE(link()->GetViewAccessibility().IsIgnored());
// Setting the accessible name to a non-empty string should replace the name
// from the link text.
data = ui::AXNodeData();
std::u16string accessible_name = u"Accessible Name";
link()->SetAccessibleName(accessible_name);
link()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
accessible_name);
EXPECT_EQ(link()->GetAccessibleName(), accessible_name);
EXPECT_EQ(data.role, ax::mojom::Role::kLink);
EXPECT_FALSE(link()->GetViewAccessibility().IsIgnored());
// Setting the accessible name to an empty string should cause the link text
// to be used as the name.
data = ui::AXNodeData();
link()->SetAccessibleName(std::u16string());
link()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"TestLink");
EXPECT_EQ(link()->GetAccessibleName(), u"TestLink");
EXPECT_EQ(data.role, ax::mojom::Role::kLink);
EXPECT_FALSE(link()->GetViewAccessibility().IsIgnored());
// Setting the link to an empty string without setting a new accessible
// name should cause the view to become "ignored" again.
data = ui::AXNodeData();
link()->SetText(std::u16string());
link()->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
std::u16string());
EXPECT_EQ(link()->GetAccessibleName(), std::u16string());
EXPECT_EQ(data.role, ax::mojom::Role::kLink);
EXPECT_TRUE(link()->GetViewAccessibility().IsIgnored());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/link_unittest.cc | C++ | unknown | 6,729 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CLOSURE_ANIMATION_MAC_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_CLOSURE_ANIMATION_MAC_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_delegate.h"
#include "ui/views/views_export.h"
namespace views {
class MenuItemView;
class SubmenuView;
// This class implements the Mac menu closure animation:
// 1) For 100ms, the selected item is drawn as unselected
// 2) Then, for another 100ms, the selected item is drawn as selected
// 3) Then, and the window fades over 250ms to transparency
// Note that this class is owned by the involved MenuController, so if the menu
// is destructed early for any reason, this class will be destructed also, which
// will stop the timer or animation (if they are running), so the callback will
// *not* be run - which is good, since the MenuController that would have
// received it is being deleted.
//
// This class also supports animating a menu away without animating the
// selection effect, which is achieved by passing nullptr for the item to
// animate. In this case, the animation skips straight to step 3 above.
class VIEWS_EXPORT MenuClosureAnimationMac
: public gfx::AnimationDelegate,
public base::SupportsWeakPtr<MenuClosureAnimationMac> {
public:
// After this closure animation is done, |callback| is run to finish
// dismissing the menu. If |item| is given, this will animate the item being
// accepted before animating the menu closing; if |item| is nullptr, only the
// menu closure will be animated.
MenuClosureAnimationMac(MenuItemView* item,
SubmenuView* menu,
base::OnceClosure callback);
MenuClosureAnimationMac(const MenuClosureAnimationMac&) = delete;
MenuClosureAnimationMac& operator=(const MenuClosureAnimationMac&) = delete;
~MenuClosureAnimationMac() override;
// Start the animation.
void Start();
// Returns the MenuItemView this animation targets.
MenuItemView* item() { return item_; }
// Returns the SubmenuView this animation targets.
SubmenuView* menu() { return menu_; }
// Causes animations to take no time for testing purposes. Note that this
// still causes the completion callback to be run asynchronously, so test
// situations have the same control flow as non-test situations.
static void DisableAnimationsForTesting();
private:
enum class AnimationStep {
kStart,
kUnselected,
kSelected,
kFading,
kFinish,
};
AnimationStep NextStepFor(AnimationStep step) const;
void AdvanceAnimation();
// gfx::AnimationDelegate:
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
base::OnceClosure callback_;
base::OneShotTimer timer_;
std::unique_ptr<gfx::Animation> fade_animation_;
raw_ptr<MenuItemView> item_;
raw_ptr<SubmenuView> menu_;
AnimationStep step_ = AnimationStep::kStart;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_CLOSURE_ANIMATION_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_closure_animation_mac.h | C++ | unknown | 3,382 |
// Copyright 2018 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/menu_closure_animation_mac.h"
#import <Cocoa/Cocoa.h>
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#import "base/task/single_thread_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/widget/widget.h"
namespace {
static bool g_disable_animations_for_testing = false;
}
namespace views {
MenuClosureAnimationMac::MenuClosureAnimationMac(MenuItemView* item,
SubmenuView* menu,
base::OnceClosure callback)
: callback_(std::move(callback)), item_(item), menu_(menu) {}
MenuClosureAnimationMac::~MenuClosureAnimationMac() = default;
void MenuClosureAnimationMac::Start() {
DCHECK_EQ(step_, AnimationStep::kStart);
if (g_disable_animations_for_testing) {
// Even when disabling animations, simulate the fact that the eventual
// accept callback will happen after a runloop cycle by skipping to the end
// of the animation.
step_ = AnimationStep::kFading;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&MenuClosureAnimationMac::AdvanceAnimation,
AsWeakPtr()));
return;
}
AdvanceAnimation();
}
// static
MenuClosureAnimationMac::AnimationStep MenuClosureAnimationMac::NextStepFor(
MenuClosureAnimationMac::AnimationStep step) const {
switch (step) {
case AnimationStep::kStart:
return item_ ? AnimationStep::kUnselected : AnimationStep::kFading;
case AnimationStep::kUnselected:
return AnimationStep::kSelected;
case AnimationStep::kSelected:
return AnimationStep::kFading;
case AnimationStep::kFading:
return AnimationStep::kFinish;
case AnimationStep::kFinish:
return AnimationStep::kFinish;
}
}
void MenuClosureAnimationMac::AdvanceAnimation() {
step_ = NextStepFor(step_);
if (step_ == AnimationStep::kUnselected ||
step_ == AnimationStep::kSelected) {
item_->SetForcedVisualSelection(step_ == AnimationStep::kSelected);
timer_.Start(FROM_HERE, base::Milliseconds(80),
base::BindRepeating(&MenuClosureAnimationMac::AdvanceAnimation,
base::Unretained(this)));
} else if (step_ == AnimationStep::kFading) {
auto fade = std::make_unique<gfx::LinearAnimation>(this);
fade->SetDuration(base::Milliseconds(200));
fade_animation_ = std::move(fade);
fade_animation_->Start();
} else if (step_ == AnimationStep::kFinish) {
std::move(callback_).Run();
}
}
// static
void MenuClosureAnimationMac::DisableAnimationsForTesting() {
g_disable_animations_for_testing = true;
}
void MenuClosureAnimationMac::AnimationProgressed(
const gfx::Animation* animation) {
// Walk up the menu from |menu_|, fading the NSWindows for all its ancestor
// menus in lockstep.
SubmenuView* submenu = menu_;
while (submenu) {
NSWindow* window =
submenu->GetWidget()->GetNativeWindow().GetNativeNSWindow();
[window setAlphaValue:animation->CurrentValueBetween(1.0, 0.0)];
MenuItemView* parent = submenu->GetMenuItem()->GetParentMenuItem();
submenu = parent ? parent->GetSubmenu() : nullptr;
}
}
void MenuClosureAnimationMac::AnimationEnded(const gfx::Animation* animation) {
AdvanceAnimation();
}
void MenuClosureAnimationMac::AnimationCanceled(
const gfx::Animation* animation) {
NOTREACHED_NORETURN();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_closure_animation_mac.mm | Objective-C++ | unknown | 3,826 |
// Copyright 2019 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/menu_closure_animation_mac.h"
#include <memory>
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/test/menu_test_utils.h"
TEST(MenuClosureAnimationMacTest, DestructCancelsCleanly) {
views::test::DisableMenuClosureAnimations();
base::test::TaskEnvironment environment;
bool called = false;
auto animation = std::make_unique<views::MenuClosureAnimationMac>(
nullptr, nullptr, base::BindLambdaForTesting([&]() { called = true; }));
animation->Start();
animation.reset();
// If the animation callback runs after the animation is destroyed, this line
// may crash; if not, |called| will get set to true and fail the test below.
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(called);
}
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_closure_animation_mac_unittest.cc | C++ | unknown | 985 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_COCOA_WATCHER_MAC_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_COCOA_WATCHER_MAC_H_
#include <memory>
#include "base/functional/callback.h"
#include "ui/views/views_export.h"
namespace views {
enum class MacNotificationFilter {
DontIgnoreNotifications,
IgnoreWorkspaceNotifications,
IgnoreAllNotifications
};
// This class executes a callback when a native menu begins tracking, or when a
// new window takes focus. With native menus, each one automatically closes when
// a new one begins tracking, and MenuPreTargetHandlerAura::OnWindowActivated()
// closes menus when new windows take focus. This allows Views menus to have the
// correct behavior.
class VIEWS_EXPORT MenuCocoaWatcherMac {
public:
// Forces all MenuCocoaWatcherMac instances to ignore certain NSNotifications.
static void SetNotificationFilterForTesting(MacNotificationFilter filter);
explicit MenuCocoaWatcherMac(base::OnceClosure callback);
MenuCocoaWatcherMac(const MenuCocoaWatcherMac&) = delete;
MenuCocoaWatcherMac& operator=(const MenuCocoaWatcherMac&) = delete;
~MenuCocoaWatcherMac();
private:
void ExecuteCallback();
// The closure to call when the notification comes in.
base::OnceClosure callback_;
struct ObjCStorage;
std::unique_ptr<ObjCStorage> objc_storage_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_COCOA_WATCHER_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_cocoa_watcher_mac.h | C++ | unknown | 1,547 |
// Copyright 2018 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/menu_cocoa_watcher_mac.h"
#import <Cocoa/Cocoa.h>
#include <dispatch/dispatch.h>
#include <memory>
#include <utility>
namespace views {
namespace {
// Returns the global notification filter.
MacNotificationFilter& NotificationFilterInternal() {
static MacNotificationFilter filter =
MacNotificationFilter::DontIgnoreNotifications;
return filter;
}
// Returns YES if `notification` should be ignored based on the current value of
// the notification filter.
BOOL ShouldIgnoreNotification(NSNotification* notification) {
switch (NotificationFilterInternal()) {
case MacNotificationFilter::DontIgnoreNotifications:
return NO;
case MacNotificationFilter::IgnoreWorkspaceNotifications:
return [[notification name]
isEqualToString:NSWorkspaceDidActivateApplicationNotification];
case MacNotificationFilter::IgnoreAllNotifications:
return YES;
}
return NO;
}
} // namespace
struct MenuCocoaWatcherMac::ObjCStorage {
// Tokens representing the notification observers.
id observer_token_other_menu_ = nil;
id observer_token_new_window_focus_ = nil;
id observer_token_app_change_ = nil;
};
MenuCocoaWatcherMac::MenuCocoaWatcherMac(base::OnceClosure callback)
: callback_(std::move(callback)),
objc_storage_(std::make_unique<ObjCStorage>()) {
objc_storage_->observer_token_other_menu_ =
[[NSNotificationCenter defaultCenter]
addObserverForName:NSMenuDidBeginTrackingNotification
object:nil
queue:nil
usingBlock:^(NSNotification* notification) {
if (ShouldIgnoreNotification(notification)) {
return;
}
ExecuteCallback();
}];
objc_storage_->observer_token_new_window_focus_ =
[[NSNotificationCenter defaultCenter]
addObserverForName:NSWindowDidBecomeKeyNotification
object:nil
queue:nil
usingBlock:^(NSNotification* notification) {
if (ShouldIgnoreNotification(notification)) {
return;
}
ExecuteCallback();
}];
objc_storage_->observer_token_app_change_ =
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserverForName:NSWorkspaceDidActivateApplicationNotification
object:nil
queue:nil
usingBlock:^(NSNotification* notification) {
if (ShouldIgnoreNotification(notification))
return;
// Only destroy menus if the browser is losing focus, not if
// it's gaining focus. This is to ensure that we can invoke
// a context menu while focused on another app, and still be
// able to click on menu items without dismissing the menu.
if (![[NSRunningApplication currentApplication] isActive]) {
ExecuteCallback();
}
}];
}
MenuCocoaWatcherMac::~MenuCocoaWatcherMac() {
[[NSNotificationCenter defaultCenter]
removeObserver:objc_storage_->observer_token_other_menu_];
[[NSNotificationCenter defaultCenter]
removeObserver:objc_storage_->observer_token_new_window_focus_];
[[[NSWorkspace sharedWorkspace] notificationCenter]
removeObserver:objc_storage_->observer_token_app_change_];
}
void MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter filter) {
NotificationFilterInternal() = filter;
}
void MenuCocoaWatcherMac::ExecuteCallback() {
__block base::OnceClosure callback = std::move(callback_);
dispatch_async(dispatch_get_main_queue(), ^{
if (callback) {
std::move(callback).Run();
}
});
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_cocoa_watcher_mac.mm | Objective-C++ | unknown | 4,083 |
// 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/menu_config.h"
#include "base/no_destructor.h"
#include "ui/base/ui_base_features.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_item_view.h"
namespace views {
MenuConfig::MenuConfig() {
Init();
InitCR2023();
}
MenuConfig::~MenuConfig() = default;
int MenuConfig::CornerRadiusForMenu(const MenuController* controller) const {
if (controller && controller->use_ash_system_ui_layout()) {
return controller->rounded_corners().has_value() ? 0
: touchable_corner_radius;
}
if (controller && (controller->IsCombobox() ||
(!use_bubble_border && controller->IsContextMenu()))) {
return auxiliary_corner_radius;
}
return corner_radius;
}
bool MenuConfig::ShouldShowAcceleratorText(const MenuItemView* item,
std::u16string* text) const {
if (!show_accelerators || !item->GetDelegate() || !item->GetCommand())
return false;
ui::Accelerator accelerator;
if (!item->GetDelegate()->GetAccelerator(item->GetCommand(), &accelerator))
return false;
if (item->GetMenuController() && item->GetMenuController()->IsContextMenu() &&
!show_context_menu_accelerators) {
return false;
}
*text = accelerator.GetShortcutText();
return true;
}
void MenuConfig::InitCR2023() {
if (!features::IsChromeRefresh2023()) {
return;
}
// CR2023 menu metrics
separator_height = 17;
separator_left_margin = 12;
separator_right_margin = 12;
item_top_margin = 6;
item_bottom_margin = 6;
}
// static
const MenuConfig& MenuConfig::instance() {
static base::NoDestructor<MenuConfig> instance;
return *instance;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config.cc | C++ | unknown | 1,919 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/font_list.h"
#include "ui/views/controls/menu/menu_image_util.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/round_rect_painter.h"
#include "ui/views/views_export.h"
namespace views {
class MenuController;
class MenuItemView;
// Layout type information for menu items. Use the instance() method to obtain
// the MenuConfig for the current platform.
struct VIEWS_EXPORT MenuConfig {
MenuConfig();
~MenuConfig();
// Menus are the only place using kGroupingPropertyKey, so any value (other
// than 0) is fine.
static constexpr int kMenuControllerGroupingId = 1001;
static const MenuConfig& instance();
// Helper methods to simplify access to MenuConfig:
// Returns the appropriate corner radius for the menu controlled by
// |controller|, or the default corner radius if |controller| is nullptr.
int CornerRadiusForMenu(const MenuController* controller) const;
// Returns whether |item_view| should show accelerator text. If so, returns
// the text to show.
bool ShouldShowAcceleratorText(const MenuItemView* item_view,
std::u16string* text) const;
// Initialize menu config for CR2023
void InitCR2023();
// Font list used by menus.
gfx::FontList font_list;
// Menu border sizes. The vertical border size does not apply to menus with
// rounded corners - those menus always use the corner radius as the vertical
// border size.
int menu_vertical_border_size = 4;
int menu_horizontal_border_size = views::RoundRectPainter::kBorderWidth;
// Submenu horizontal inset with parent menu. This is the horizontal overlap
// between the submenu and its parent menu, not including the borders of
// submenu and parent menu.
int submenu_horizontal_inset = 3;
// Margins between the top of the item and the label.
int item_top_margin = 4;
// Margins between the bottom of the item and the label.
int item_bottom_margin = 3;
// Margins used if the menu doesn't have icons.
int item_no_icon_top_margin = 4;
int item_no_icon_bottom_margin = 4;
// Minimum dimensions used for entire items. If these are nonzero, they
// override the vertical margin constants given above - the item's text and
// icon are vertically centered within these heights.
int minimum_text_item_height = 0;
int minimum_container_item_height = 0;
int minimum_menu_width = 0;
// TODO(ftirelo): Paddings should come from the layout provider, once Harmony
// is the default behavior.
// Horizontal padding between components in a menu item.
int item_horizontal_padding = 8;
// Horizontal padding between components in a touchable menu item.
int touchable_item_horizontal_padding = 16;
// Padding between the label and submenu arrow.
int label_to_arrow_padding = 8;
// Padding between the arrow and the edge.
int arrow_to_edge_padding = 5;
// The space reserved for the check. The actual size of the image may be
// different.
int check_width = kMenuCheckSize;
int check_height = kMenuCheckSize;
// The horizontal space reserved for submenu arrow. The actual width of the
// image may be different.
int arrow_width = kSubmenuArrowSize;
// Height of a normal separator (ui::NORMAL_SEPARATOR).
int separator_height = 11;
// Height of a double separator (ui::DOUBLE_SEPARATOR).
int double_separator_height = 18;
// Height of a ui::UPPER_SEPARATOR.
int separator_upper_height = 3;
// Height of a ui::LOWER_SEPARATOR.
int separator_lower_height = 4;
// Height of a ui::SPACING_SEPARATOR.
int separator_spacing_height = 3;
// Thickness of the drawn separator line in pixels.
int separator_thickness = 1;
// Thickness of the drawn separator line in pixels for double separator.
int double_separator_thickness = 2;
// Left & right separator padding
int separator_left_margin = 0;
int separator_right_margin = 0;
// Are mnemonics shown?
bool show_mnemonics = false;
// Are mnemonics used to activate items?
bool use_mnemonics = true;
// Height of the scroll arrow.
int scroll_arrow_height = 3;
// Minimum height of menu item.
int item_min_height = 0;
// Edge padding for an actionable submenu arrow.
int actionable_submenu_arrow_to_edge_padding = 14;
// Width of the submenu in an actionable submenu.
int actionable_submenu_width = 37;
// The height of the vertical separator used in an actionable submenu.
int actionable_submenu_vertical_separator_height = 18;
// The width of the vertical separator used in an actionable submenu.
int actionable_submenu_vertical_separator_width = 1;
// Whether the keyboard accelerators are visible.
bool show_accelerators = true;
// True if icon to label padding is always added with or without icon.
bool always_use_icon_to_label_padding = false;
// True if submenu arrow and shortcut right edge should be aligned.
bool align_arrow_and_shortcut = false;
// True if the context menu's should be offset from the cursor position.
bool offset_context_menus = false;
// True if the scroll container should add a border stroke around the menu.
bool use_outer_border = true;
// True if the icon is part of the label rather than in its own column.
bool icons_in_label = false;
// True if a combobox menu should put a checkmark next to the selected item.
bool check_selected_combobox_item = false;
// Delay, in ms, between when menus are selected or moused over and the menu
// appears.
int show_delay = 400;
// Radius of the rounded corners of the menu border. Must be >= 0.
int corner_radius = LayoutProvider::Get()->GetCornerRadiusMetric(
ShapeContextTokens::kMenuRadius);
// Radius of "auxiliary" rounded corners - comboboxes and context menus.
// Must be >= 0.
int auxiliary_corner_radius = LayoutProvider::Get()->GetCornerRadiusMetric(
ShapeContextTokens::kMenuAuxRadius);
// Radius of the rounded corners of the touchable menu border
int touchable_corner_radius = LayoutProvider::Get()->GetCornerRadiusMetric(
ShapeContextTokens::kMenuTouchRadius);
// Anchor offset for touchable menus created by a touch event.
int touchable_anchor_offset = 8;
// Height of child MenuItemViews for touchable menus.
int touchable_menu_height = 36;
// Minimum width of touchable menus.
int touchable_menu_min_width = 256;
// Maximum width of touchable menus.
int touchable_menu_max_width = 352;
// Shadow elevation of touchable menus.
int touchable_menu_shadow_elevation = 12;
// Shadow elevation of touchable submenus.
int touchable_submenu_shadow_elevation = 16;
// Vertical padding for touchable menus.
int vertical_touchable_menu_item_padding = 8;
// Left & right margin of padded separator (ui::PADDED_SEPARATOR).
int padded_separator_left_margin = 64;
int padded_separator_right_margin = 0;
// Whether arrow keys should wrap around the end of the menu when selecting.
bool arrow_key_selection_wraps = true;
// Whether to show accelerators in context menus.
bool show_context_menu_accelerators = true;
// Whether all types of menus use prefix selection for items.
bool all_menus_use_prefix_selection = false;
// Margins for footnotes (HIGHLIGHTED item at the end of a menu).
int footnote_vertical_margin = 11;
// Should use a bubble border for menus.
bool use_bubble_border = false;
private:
// Configures a MenuConfig as appropriate for the current platform.
void Init();
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config.h | C++ | unknown | 7,870 |
// Copyright 2014 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/menu_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/views/controls/menu/menu_image_util.h"
namespace views {
void MenuConfig::Init() {
submenu_horizontal_inset = 1;
arrow_to_edge_padding = 21;
gfx::ImageSkia check = GetMenuCheckImage(false);
check_height = check.height();
item_min_height = 29;
separator_spacing_height = 7;
separator_lower_height = 8;
separator_upper_height = 8;
always_use_icon_to_label_padding = true;
align_arrow_and_shortcut = true;
offset_context_menus = true;
corner_radius = 2;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(crbug/1129012): Change to false once pop-up menus have shadows.
use_outer_border = true;
#else
// In Ash, the border is provided by the shadow.
use_outer_border = false;
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config_chromeos.cc | C++ | unknown | 975 |
// Copyright 2017 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/menu_config.h"
namespace views {
void MenuConfig::Init() {}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config_fuchsia.cc | C++ | unknown | 262 |
// Copyright 2015 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/menu_config.h"
namespace views {
void MenuConfig::Init() {
arrow_to_edge_padding = 6;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config_linux.cc | C++ | unknown | 292 |
// Copyright 2014 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/menu_config.h"
#import <AppKit/AppKit.h>
#include "base/mac/mac_util.h"
#include "ui/gfx/platform_font_mac.h"
namespace {
void InitMaterialMenuConfig(views::MenuConfig* config) {
// These config parameters are from https://crbug.com/829347 and the spec
// images linked from that bug.
config->menu_horizontal_border_size = 0;
config->submenu_horizontal_inset = 0;
config->minimum_text_item_height = 28;
config->minimum_container_item_height = 40;
config->minimum_menu_width = 320;
config->label_to_arrow_padding = 0;
config->arrow_to_edge_padding = 16;
config->check_width = 16;
config->check_height = 16;
config->arrow_width = 8;
config->separator_height = 9;
config->separator_lower_height = 4;
config->separator_upper_height = 4;
config->separator_spacing_height = 5;
config->separator_thickness = 1;
config->align_arrow_and_shortcut = true;
config->use_outer_border = false;
config->icons_in_label = true;
config->corner_radius = 8;
config->auxiliary_corner_radius = 4;
config->item_top_margin = 4;
config->item_bottom_margin = 4;
}
} // namespace
namespace views {
void MenuConfig::Init() {
font_list = gfx::FontList(gfx::Font(
new gfx::PlatformFontMac(gfx::PlatformFontMac::SystemFontType::kMenu)));
check_selected_combobox_item = true;
arrow_key_selection_wraps = false;
use_mnemonics = false;
show_context_menu_accelerators = false;
all_menus_use_prefix_selection = true;
InitMaterialMenuConfig(this);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config_mac.mm | Objective-C++ | unknown | 1,688 |
// 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/menu_config.h"
#include <windows.h> // Must come before other Windows system headers.
#include <Vssym32.h>
#include "base/check.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/win/scoped_gdi_object.h"
#include "base/win/windows_version.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/system_fonts_win.h"
#include "ui/native_theme/native_theme_win.h"
using ui::NativeTheme;
namespace views {
void MenuConfig::Init() {
font_list =
gfx::FontList(gfx::win::GetSystemFont(gfx::win::SystemFont::kMenu));
NativeTheme::ExtraParams extra;
gfx::Size arrow_size = NativeTheme::GetInstanceForNativeUi()->GetPartSize(
NativeTheme::kMenuPopupArrow, NativeTheme::kNormal, extra);
if (!arrow_size.IsEmpty()) {
arrow_width = arrow_size.width();
} else {
// Sadly I didn't see a specify metrics for this.
arrow_width = GetSystemMetrics(SM_CXMENUCHECK);
}
BOOL show_cues;
show_mnemonics =
(SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &show_cues, 0) &&
show_cues == TRUE);
SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &show_delay, 0);
bool is_win11 = base::win::GetVersion() >= base::win::Version::WIN11;
bool is_refresh = features::IsChromeRefresh2023();
use_bubble_border = corner_radius > 0 || is_win11;
UMA_HISTOGRAM_BOOLEAN("Windows.Menu.Win11Style", is_win11 && !is_refresh);
separator_upper_height = 5;
separator_lower_height = 7;
// Under ChromeRefresh2023, the corner radius will not use the win11 style.
if (use_bubble_border && !is_refresh) {
corner_radius = 8;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_config_win.cc | C++ | unknown | 1,879 |
// 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/menu_controller.h"
#include <algorithm>
#include <set>
#include <utility>
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_controller_delegate.h"
#include "ui/views/controls/menu/menu_host_root_view.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_pre_target_handler.h"
#include "ui/views/controls/menu/menu_scroll_view_container.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/drag_utils.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/mouse_constants.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_constants.h"
#include "ui/views/view_tracker.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/win/internal_constants.h"
#include "ui/display/win/screen_win.h"
#include "ui/views/win/hwnd_util.h"
#endif
#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#endif
using ui::OSExchangeData;
DEFINE_UI_CLASS_PROPERTY_TYPE(std::vector<views::ViewTracker>*)
namespace views {
namespace {
// The menu controller manages the AX index attributes inside menu items. This
// property maintains a vector of menu children that were last assigned such
// attributes by MenuController::SetSelectionIndices() so that the controller
// can update them if children change via MenuController::MenuChildrenChanged().
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::vector<views::ViewTracker>,
kOrderedMenuChildren,
nullptr)
#if BUILDFLAG(IS_MAC)
bool AcceleratorShouldCancelMenu(const ui::Accelerator& accelerator) {
// Since AcceleratorShouldCancelMenu() is called quite early in key
// event handling, it is actually invoked for modifier keys themselves
// changing. In that case, the key code reflects that the modifier key is
// being pressed/released. We should never treat those presses as
// accelerators, so bail out here.
//
// Also, we have to check for VKEY_SHIFT here even though we don't check
// IsShiftDown() - otherwise this sequence of keypresses will dismiss the
// menu:
// Press Cmd
// Press Shift
// Which makes it impossible to use menus that have Cmd-Shift accelerators.
if (accelerator.key_code() == ui::VKEY_CONTROL ||
accelerator.key_code() == ui::VKEY_MENU || // aka Alt
accelerator.key_code() == ui::VKEY_COMMAND ||
accelerator.key_code() == ui::VKEY_SHIFT) {
return false;
}
// Using an accelerator on Mac closes any open menu. Note that Mac behavior is
// different between context menus (which block use of accelerators) and other
// types of menus, which close when an accelerator is sent and do repost the
// accelerator. In MacViews, this happens naturally because context menus are
// (modal) Cocoa menus and other menus are Views menus, which will go through
// this code path.
return accelerator.IsCtrlDown() || accelerator.IsAltDown() ||
accelerator.IsCmdDown();
}
#endif
bool ShouldIgnoreScreenBoundsForMenus() {
#if BUILDFLAG(IS_OZONE)
// Some platforms, such as Wayland, disallow client applications to manipulate
// global screen coordinates, requiring menus to be positioned relative to
// their parent windows. See comment in ozone_platform_wayland.cc.
return !ui::OzonePlatform::GetInstance()
->GetPlatformProperties()
.supports_global_screen_coordinates;
#else
return false;
#endif
}
// The amount of time the mouse should be down before a mouse release is
// considered intentional. This is to prevent spurious mouse releases from
// activating controls, especially when some UI element is revealed under the
// source of the activation (ex. menus showing underneath menu buttons).
base::TimeDelta menu_selection_hold_time = base::Milliseconds(200);
// Amount of time from when the drop exits the menu and the menu is hidden.
constexpr int kCloseOnExitTime = 1200;
// If a context menu is invoked by touch, we shift the menu by this offset so
// that the finger does not obscure the menu.
constexpr int kTouchYPadding = 15;
// The spacing offset for the bubble tip.
constexpr int kBubbleTipSizeLeftRight = 12;
constexpr int kBubbleTipSizeTopBottom = 11;
// The maximum distance (in DIPS) that the mouse can be moved before it should
// trigger a mouse menu item activation (regardless of how long the menu has
// been showing).
constexpr float kMaximumLengthMovedToActivate = 4.0f;
// Time to complete a cycle of the menu item alert animation.
constexpr base::TimeDelta kAlertAnimationThrobDuration =
base::Milliseconds(1000);
// Returns true if the mnemonic of |menu| matches key.
bool MatchesMnemonic(MenuItemView* menu, char16_t key) {
return key != 0 && menu->GetMnemonic() == key;
}
// Returns true if |menu| doesn't have a mnemonic and first character of the its
// title is |key|.
bool TitleMatchesMnemonic(MenuItemView* menu, char16_t key) {
if (menu->GetMnemonic())
return false;
std::u16string lower_title = base::i18n::ToLower(menu->title());
return !lower_title.empty() && lower_title[0] == key;
}
// Returns the first descendant of |view| that is hot tracked.
Button* GetFirstHotTrackedView(View* view) {
if (!view)
return nullptr;
Button* button = Button::AsButton(view);
if (button && button->IsHotTracked())
return button;
for (View* child : view->children()) {
Button* hot_view = GetFirstHotTrackedView(child);
if (hot_view)
return hot_view;
}
return nullptr;
}
// Recurses through the child views of |view| returning the first view starting
// at |pos| that is focusable. Children are considered first to last.
// TODO(https://crbug.com/942358): This can also return |view|, which seems
// incorrect.
View* GetFirstFocusableViewForward(View* view,
View::Views::const_iterator pos) {
for (auto i = pos; i != view->children().cend(); ++i) {
View* deepest = GetFirstFocusableViewForward(*i, (*i)->children().cbegin());
if (deepest)
return deepest;
}
return view->IsFocusable() ? view : nullptr;
}
// As GetFirstFocusableViewForward(), but children are considered last to first.
View* GetFirstFocusableViewBackward(View* view,
View::Views::const_reverse_iterator pos) {
for (auto i = pos; i != view->children().crend(); ++i) {
View* deepest =
GetFirstFocusableViewBackward(*i, (*i)->children().crbegin());
if (deepest)
return deepest;
}
return view->IsFocusable() ? view : nullptr;
}
// Returns the first child of |start| that is focusable.
View* GetInitialFocusableView(View* start, bool forward) {
const auto& children = start->children();
return forward ? GetFirstFocusableViewForward(start, children.cbegin())
: GetFirstFocusableViewBackward(start, children.crbegin());
}
// Returns the next view after |start_at| that is focusable. Returns null if
// there are no focusable children of |ancestor| after |start_at|.
View* GetNextFocusableView(View* ancestor, View* start_at, bool forward) {
DCHECK(ancestor->Contains(start_at));
View* parent = start_at;
do {
View* new_parent = parent->parent();
const auto pos = new_parent->FindChild(parent);
// Subtle: make_reverse_iterator() will result in an iterator that refers to
// the element before its argument, which is what we want.
View* next = forward
? GetFirstFocusableViewForward(new_parent, std::next(pos))
: GetFirstFocusableViewBackward(
new_parent, std::make_reverse_iterator(pos));
if (next)
return next;
parent = new_parent;
} while (parent != ancestor);
return nullptr;
}
#if BUILDFLAG(IS_WIN)
// Determines the correct coordinates and window to repost |event| to, if it is
// a mouse or touch event.
static void RepostEventImpl(const ui::LocatedEvent* event,
const gfx::Point& screen_loc,
gfx::NativeView native_view,
gfx::NativeWindow window) {
if (!event->IsMouseEvent() && !event->IsTouchEvent()) {
// TODO(rbyers): Gesture event repost is tricky to get right
// crbug.com/170987.
DCHECK(event->IsGestureEvent());
return;
}
if (!native_view)
return;
gfx::Point screen_loc_pixels =
display::win::ScreenWin::DIPToScreenPoint(screen_loc);
HWND target_window = ::WindowFromPoint(screen_loc_pixels.ToPOINT());
// If we don't find a native window for the HWND at the current location,
// then attempt to find a native window from its parent if one exists.
// There are HWNDs created outside views, which don't have associated
// native windows.
if (!window) {
HWND parent = ::GetParent(target_window);
if (parent) {
aura::WindowTreeHost* host =
aura::WindowTreeHost::GetForAcceleratedWidget(parent);
if (host) {
target_window = parent;
window = host->window();
}
}
}
// Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
// PostMessage/SendMessage to work correctly. These API's expect the
// coordinates to be in pixels.
if (event->IsMouseEvent()) {
HWND source_window = HWNDForNativeView(native_view);
if (!target_window || !source_window ||
GetWindowThreadProcessId(source_window, nullptr) !=
GetWindowThreadProcessId(target_window, nullptr)) {
// Even though we have mouse capture, windows generates a mouse event if
// the other window is in a separate thread. Only repost an event if
// |target_window| and |source_window| were created on the same thread,
// else double events can occur and lead to bad behavior.
return;
}
// Determine whether the click was in the client area or not.
// NOTE: WM_NCHITTEST coordinates are relative to the screen.
LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
const bool client_area = nc_hit_result == HTCLIENT;
int window_x = screen_loc_pixels.x();
int window_y = screen_loc_pixels.y();
if (client_area) {
POINT pt = {window_x, window_y};
ScreenToClient(target_window, &pt);
window_x = pt.x;
window_y = pt.y;
}
WPARAM target = client_area ? event->native_event().wParam
: static_cast<WPARAM>(nc_hit_result);
LPARAM window_coords = MAKELPARAM(window_x, window_y);
PostMessage(target_window, event->native_event().message, target,
window_coords);
return;
}
if (!window)
return;
aura::Window* root = window->GetRootWindow();
aura::client::ScreenPositionClient* spc =
aura::client::GetScreenPositionClient(root);
if (!spc)
return;
gfx::Point root_loc(screen_loc);
spc->ConvertPointFromScreen(root, &root_loc);
std::unique_ptr<ui::Event> clone = event->Clone();
std::unique_ptr<ui::LocatedEvent> located_event(
static_cast<ui::LocatedEvent*>(clone.release()));
located_event->set_location(root_loc);
located_event->set_root_location(root_loc);
root->GetHost()->dispatcher()->RepostEvent(located_event.get());
}
#endif // BUILDFLAG(IS_WIN)
} // namespace
// MenuScrollTask --------------------------------------------------------------
// MenuScrollTask is used when the SubmenuView does not all fit on screen and
// the mouse is over the scroll up/down buttons. MenuScrollTask schedules
// itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls
// appropriately.
class MenuController::MenuScrollTask {
public:
MenuScrollTask() {
pixels_per_second_ = MenuItemView::pref_menu_height() * 20;
}
MenuScrollTask(const MenuScrollTask&) = delete;
MenuScrollTask& operator=(const MenuScrollTask&) = delete;
void Update(const MenuController::MenuPart& part) {
if (!part.is_scroll()) {
StopScrolling();
return;
}
DCHECK(part.submenu);
SubmenuView* new_menu = part.submenu;
bool new_is_up = (part.type == MenuController::MenuPart::Type::kScrollUp);
if (new_menu == submenu_ && is_scrolling_up_ == new_is_up)
return;
start_scroll_time_ = base::Time::Now();
start_y_ = part.submenu->GetVisibleBounds().y();
submenu_ = new_menu;
is_scrolling_up_ = new_is_up;
if (!scrolling_timer_.IsRunning()) {
scrolling_timer_.Start(FROM_HERE, base::Milliseconds(30), this,
&MenuScrollTask::Run);
}
}
void StopScrolling() {
if (scrolling_timer_.IsRunning()) {
scrolling_timer_.Stop();
submenu_ = nullptr;
}
}
// The menu being scrolled. Returns null if not scrolling.
SubmenuView* submenu() const { return submenu_; }
private:
void Run() {
DCHECK(submenu_);
gfx::Rect vis_rect = submenu_->GetVisibleBounds();
const int delta_y = static_cast<int>(
(base::Time::Now() - start_scroll_time_).InMilliseconds() *
pixels_per_second_ / 1000);
vis_rect.set_y(is_scrolling_up_
? std::max(0, start_y_ - delta_y)
: std::min(submenu_->height() - vis_rect.height(),
start_y_ + delta_y));
submenu_->ScrollRectToVisible(vis_rect);
}
// SubmenuView being scrolled.
raw_ptr<SubmenuView> submenu_ = nullptr;
// Direction scrolling.
bool is_scrolling_up_ = false;
// Timer to periodically scroll.
base::RepeatingTimer scrolling_timer_;
// Time we started scrolling at.
base::Time start_scroll_time_;
// How many pixels to scroll per second.
int pixels_per_second_;
// Y-coordinate of submenu_view_ when scrolling started.
int start_y_ = 0;
};
// MenuController:SelectByCharDetails ----------------------------------------
struct MenuController::SelectByCharDetails {
SelectByCharDetails() = default;
// Index of the first menu with the specified mnemonic.
absl::optional<size_t> first_match;
// If true there are multiple menu items with the same mnemonic.
bool has_multiple = false;
// Index of the selected item; may remain nullopt.
absl::optional<size_t> index_of_item;
// If there are multiple matches this is the index of the item after the
// currently selected item whose mnemonic matches. This may remain nullopt
// even though there are matches.
absl::optional<size_t> next_match;
};
// MenuController:State ------------------------------------------------------
MenuController::State::State() = default;
MenuController::State::State(const State& other) = default;
MenuController::State::~State() = default;
// MenuController ------------------------------------------------------------
// static
MenuController* MenuController::active_instance_ = nullptr;
// static
MenuController* MenuController::GetActiveInstance() {
return active_instance_;
}
void MenuController::Run(Widget* parent,
MenuButtonController* button_controller,
MenuItemView* root,
const gfx::Rect& bounds,
MenuAnchorPosition position,
bool context_menu,
bool is_nested_drag,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget) {
exit_type_ = ExitType::kNone;
possible_drag_ = false;
drag_in_progress_ = false;
did_initiate_drag_ = false;
closing_event_time_ = base::TimeTicks();
menu_start_time_ = base::TimeTicks::Now();
menu_start_mouse_press_loc_ = gfx::Point();
ui::Event* event = nullptr;
if (parent) {
View* root_view = parent->GetRootView();
if (root_view) {
event = static_cast<internal::RootView*>(root_view)->current_event();
if (event && event->type() == ui::ET_MOUSE_PRESSED) {
gfx::Point screen_loc(
static_cast<const ui::MouseEvent*>(event)->location());
View::ConvertPointToScreen(static_cast<View*>(event->target()),
&screen_loc);
menu_start_mouse_press_loc_ = screen_loc;
}
}
}
// If we are already showing, this new menu is being nested. Such as context
// menus on top of normal menus.
if (showing_) {
// Nesting (context menus) is not used for drag and drop.
DCHECK(!for_drop_);
state_.hot_button = hot_button_;
hot_button_ = nullptr;
// We're already showing, push the current state.
menu_stack_.emplace_back(state_, std::move(pressed_lock_));
// The context menu should be owned by the same parent.
DCHECK_EQ(owner_, parent);
} else {
showing_ = true;
if (owner_)
owner_->RemoveObserver(this);
owner_ = parent;
if (owner_)
owner_->AddObserver(this);
native_view_for_gestures_ = native_view_for_gestures;
parent_widget_ = parent_widget;
// Only create a MenuPreTargetHandler for non-nested menus. Nested menus
// will use the existing one.
menu_pre_target_handler_ = MenuPreTargetHandler::Create(this, owner_);
}
#if BUILDFLAG(IS_MAC)
menu_cocoa_watcher_ = std::make_unique<MenuCocoaWatcherMac>(base::BindOnce(
&MenuController::Cancel, this->AsWeakPtr(), ExitType::kAll));
#endif
// Reset current state.
pending_state_ = State();
state_ = State();
UpdateInitialLocation(bounds, position, context_menu);
// Set the selection, which opens the initial menu.
SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
if (button_controller) {
pressed_lock_ = button_controller->TakeLock(
false, ui::LocatedEvent::FromIfValid(event));
}
if (for_drop_) {
if (!is_nested_drag) {
// Start the timer to hide the menu. This is needed as we get no
// notification when the drag has finished.
StartCancelAllTimer();
}
return;
}
// Make sure Chrome doesn't attempt to shut down while the menu is showing.
ViewsDelegate::GetInstance()->AddRef();
}
void MenuController::Cancel(ExitType type) {
#if BUILDFLAG(IS_MAC)
menu_closure_animation_.reset();
#endif
// If the menu has already been destroyed, no further cancellation is
// needed. We especially don't want to set the |exit_type_| to a lesser
// value.
if (exit_type_ == ExitType::kDestroyed || exit_type_ == type)
return;
if (!showing_) {
// This occurs if we're in the process of notifying the delegate for a drop
// and the delegate cancels us. Or if the releasing of ViewsDelegate causes
// an immediate shutdown.
return;
}
MenuItemView* selected = state_.item;
SetExitType(type);
SendMouseCaptureLostToActiveView();
// Hide windows immediately.
SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
if (for_drop_) {
// If we didn't block the caller we need to notify the menu, which
// triggers deleting us.
DCHECK(selected);
showing_ = false;
delegate_->OnMenuClosed(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
selected->GetRootMenuItem(), accept_event_flags_);
// WARNING: the call to MenuClosed deletes us.
return;
}
// If |type| is ExitType::kAll we update the state of the menu to not showing.
// For dragging this ensures that the correct visual state is reported until
// the drag operation completes. For non-dragging cases it is possible that
// the release of ViewsDelegate leads immediately to shutdown, which can
// trigger nested calls to Cancel. We want to reject these to prevent
// attempting a nested tear down of this and |delegate_|.
if (type == ExitType::kAll)
showing_ = false;
// On Windows and Linux the destruction of this menu's Widget leads to the
// teardown of the platform specific drag-and-drop Widget. Do not shutdown
// while dragging, leave the Widget hidden until drag-and-drop has completed,
// at which point all menus will be destroyed.
if (!drag_in_progress_)
ExitMenu();
}
void MenuController::AddNestedDelegate(
internal::MenuControllerDelegate* delegate) {
delegate_stack_.push_back(delegate);
delegate_ = delegate;
}
bool MenuController::IsCombobox() const {
return IsEditableCombobox() || IsReadonlyCombobox();
}
bool MenuController::IsEditableCombobox() const {
return combobox_type_ == ComboboxType::kEditable;
}
bool MenuController::IsReadonlyCombobox() const {
return combobox_type_ == ComboboxType::kReadonly;
}
bool MenuController::IsContextMenu() const {
return state_.context_menu;
}
void MenuController::SelectItemAndOpenSubmenu(MenuItemView* item) {
DCHECK(item);
SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
// If `item` has not a submenu, hot track `item`'s initial focusable button
// if any.
if (!item->HasSubmenu()) {
View* hot_view = GetInitialFocusableView(item, /*forward=*/true);
SetHotTrackedButton(Button::AsButton(hot_view));
}
}
bool MenuController::OnMousePressed(SubmenuView* source,
const ui::MouseEvent& event) {
// We should either have no current_mouse_event_target_, or should have a
// pressed state stored.
DCHECK(!current_mouse_event_target_ || current_mouse_pressed_state_);
// Find the root view to check. If any buttons were previously pressed, this
// is the same root view we've been forwarding to. Otherwise, it's the root
// view of the target.
MenuHostRootView* forward_to_root =
current_mouse_pressed_state_ ? current_mouse_event_target_.get()
: GetRootView(source, event.location());
current_mouse_pressed_state_ |= event.changed_button_flags();
if (forward_to_root) {
ui::MouseEvent event_for_root(event);
// Reset hot-tracking if a different view is getting a mouse press.
ConvertLocatedEventForRootView(source, forward_to_root, &event_for_root);
View* view =
forward_to_root->GetEventHandlerForPoint(event_for_root.location());
Button* button = Button::AsButton(view);
if (hot_button_ != button)
SetHotTrackedButton(button);
// Empty menu items are always handled by the menu controller.
if (!view || view->GetID() != MenuItemView::kEmptyMenuItemViewID) {
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
bool processed = forward_to_root->ProcessMousePressed(event_for_root);
// This object may be destroyed as a result of a mouse press event (some
// item may close the menu).
if (!this_ref)
return true;
// If the event was processed, the root view becomes our current mouse
// handler...
if (processed && !current_mouse_event_target_) {
current_mouse_event_target_ = forward_to_root;
}
// ...and we always return the result of the current handler.
if (current_mouse_event_target_)
return processed;
}
}
// Otherwise, the menu handles this click directly.
SetSelectionOnPointerDown(source, &event);
return true;
}
bool MenuController::OnMouseDragged(SubmenuView* source,
const ui::MouseEvent& event) {
if (current_mouse_event_target_) {
ui::MouseEvent event_for_root(event);
ConvertLocatedEventForRootView(source, current_mouse_event_target_,
&event_for_root);
return current_mouse_event_target_->ProcessMouseDragged(event_for_root);
}
MenuPart part = GetMenuPart(source, event.location());
UpdateScrolling(part);
if (for_drop_)
return false;
if (possible_drag_) {
if (View::ExceededDragThreshold(event.location() - press_pt_))
StartDrag(source, press_pt_);
return true;
}
MenuItemView* mouse_menu = nullptr;
if (part.type == MenuPart::Type::kMenuItem) {
// If there is no menu target, but a submenu target, then we are interacting
// with an empty menu item within a submenu. These cannot become selection
// targets for mouse interaction, so do not attempt to update selection.
if (part.menu || !part.submenu) {
if (!part.menu)
part.menu = source->GetMenuItem();
else
mouse_menu = part.menu;
SetSelection(part.menu ? part.menu.get() : state_.item.get(),
SELECTION_OPEN_SUBMENU);
}
} else if (part.type == MenuPart::Type::kNone) {
// If there is a sibling menu, show it. Otherwise, if the user has selected
// a menu item with no accompanying sibling menu or submenu, move selection
// back to the parent menu item.
if (!ShowSiblingMenu(source, event.location())) {
if (!part.is_scroll() && pending_state_.item &&
pending_state_.item->GetParentMenuItem() &&
!pending_state_.item->SubmenuIsShowing()) {
SetSelection(pending_state_.item->GetParentMenuItem(),
SELECTION_OPEN_SUBMENU);
}
}
}
UpdateActiveMouseView(source, event, mouse_menu);
return true;
}
void MenuController::OnMouseReleased(SubmenuView* source,
const ui::MouseEvent& event) {
current_mouse_pressed_state_ &= ~event.changed_button_flags();
if (current_mouse_event_target_) {
// If this was the final mouse button, then remove the forwarding target.
// We need to do this *before* dispatching the event to the root view
// because there's a chance that the event will open a nested (and blocking)
// menu, and we need to not have a forwarded root view.
MenuHostRootView* cached_event_target = current_mouse_event_target_;
if (!current_mouse_pressed_state_)
current_mouse_event_target_ = nullptr;
ui::MouseEvent event_for_root(event);
ConvertLocatedEventForRootView(source, cached_event_target,
&event_for_root);
cached_event_target->ProcessMouseReleased(event_for_root);
return;
}
if (for_drop_)
return;
DCHECK(state_.item);
possible_drag_ = false;
MenuPart part = GetMenuPart(source, event.location());
if (event.IsRightMouseButton() && part.type == MenuPart::Type::kMenuItem) {
MenuItemView* menu = part.menu;
// |menu| is null means this event is from an empty menu or a separator.
// If it is from an empty menu, use parent context menu instead of that.
if (!menu && part.submenu->children().size() == 1 &&
part.submenu->children().front()->GetID() ==
MenuItemView::kEmptyMenuItemViewID) {
menu = part.parent;
}
if (menu) {
gfx::Point screen_location(event.location());
View::ConvertPointToScreen(source->GetScrollViewContainer(),
&screen_location);
if (ShowContextMenu(menu, screen_location, ui::MENU_SOURCE_MOUSE))
return;
}
}
// A plain left click on a folder that has children serves to open that folder
// by setting the selection, rather than executing a command via the delegate
// or doing anything else.
// TODO(ellyjones): Why isn't a case needed here for EF_CONTROL_DOWN?
bool plain_left_click_with_children =
part.should_submenu_show && part.menu && part.menu->HasSubmenu() &&
(event.flags() & ui::EF_LEFT_MOUSE_BUTTON) &&
!(event.flags() & ui::EF_COMMAND_DOWN);
if (!part.is_scroll() && part.menu && !plain_left_click_with_children) {
if (active_mouse_view_tracker_->view()) {
SendMouseReleaseToActiveView(source, event);
return;
}
// If a mouse release was received quickly after showing.
base::TimeDelta time_shown = base::TimeTicks::Now() - menu_start_time_;
if (time_shown < menu_selection_hold_time) {
// And it wasn't far from the mouse press location.
gfx::Point screen_loc(event.location());
View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
gfx::Vector2d moved = screen_loc - menu_start_mouse_press_loc_;
if (moved.Length() < kMaximumLengthMovedToActivate) {
// Ignore the mouse release as it was likely this menu was shown under
// the mouse and the action was just a normal click.
return;
}
}
const int command = part.menu->GetCommand();
if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
command, event)) {
part.menu->GetDelegate()->ExecuteCommand(command, event.flags());
return;
}
if (!part.menu->NonIconChildViewsCount() &&
part.menu->GetDelegate()->IsTriggerableEvent(part.menu, event)) {
Accept(part.menu, event.flags());
return;
}
} else if (part.type == MenuPart::Type::kMenuItem) {
// User either clicked on empty space, or a menu that has children.
SetSelection(part.menu ? part.menu.get() : state_.item.get(),
SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
}
SendMouseCaptureLostToActiveView();
}
void MenuController::OnMouseMoved(SubmenuView* source,
const ui::MouseEvent& event) {
if (current_mouse_event_target_) {
ui::MouseEvent event_for_root(event);
ConvertLocatedEventForRootView(source, current_mouse_event_target_,
&event_for_root);
current_mouse_event_target_->ProcessMouseMoved(event_for_root);
return;
}
// Ignore mouse move events whose location is the same as where the mouse
// was when a menu was opened. This fixes the issue of opening a menu
// with the keyboard and having the menu item under the current mouse
// position incorrectly selected.
if (menu_open_mouse_loc_ && *menu_open_mouse_loc_ == event.location())
return;
menu_open_mouse_loc_.reset();
MenuHostRootView* root_view = GetRootView(source, event.location());
Button* new_hot_tracked_button = nullptr;
if (root_view) {
root_view->ProcessMouseMoved(event);
// Update hot-tracked button when a button state is changed with a mouse
// event. It is necessary to track it for accurate hot-tracking when both
// mouse and keyboard are used to navigate the menu.
ui::MouseEvent event_for_root(event);
ConvertLocatedEventForRootView(source, root_view, &event_for_root);
View* view = root_view->GetEventHandlerForPoint(event_for_root.location());
new_hot_tracked_button = Button::AsButton(view);
}
HandleMouseLocation(source, event.location());
// Updating the hot tracked button should be after `HandleMouseLocation()`
// which may reset the current hot tracked button.
if (new_hot_tracked_button)
SetHotTrackedButton(new_hot_tracked_button);
}
void MenuController::OnMouseEntered(SubmenuView* source,
const ui::MouseEvent& event) {
// MouseEntered is always followed by a mouse moved, so don't need to
// do anything here.
}
bool MenuController::OnMouseWheel(SubmenuView* source,
const ui::MouseWheelEvent& event) {
MenuPart part = GetMenuPart(source, event.location());
SetSelection(part.menu ? part.menu.get() : state_.item.get(),
SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
return part.submenu && part.submenu->OnMouseWheel(event);
}
void MenuController::OnGestureEvent(SubmenuView* source,
ui::GestureEvent* event) {
if (owner_ && send_gesture_events_to_owner()) {
#if defined(USE_AURA)
gfx::NativeView target = native_view_for_gestures_
? native_view_for_gestures_
: owner()->GetNativeWindow();
event->ConvertLocationToTarget(source->GetWidget()->GetNativeWindow(),
target);
target->delegate()->OnGestureEvent(event);
#else
owner()->OnGestureEvent(event);
#endif // defined(USE_AURA)
// Reset |send_gesture_events_to_owner_| when the first gesture ends.
if (event->type() == ui::ET_GESTURE_END)
send_gesture_events_to_owner_ = false;
return;
}
MenuHostRootView* root_view = GetRootView(source, event->location());
if (root_view) {
// Reset hot-tracking if a different view is getting a touch event.
ui::GestureEvent event_for_root(*event);
ConvertLocatedEventForRootView(source, root_view, &event_for_root);
View* view = root_view->GetEventHandlerForPoint(event_for_root.location());
Button* button = Button::AsButton(view);
if (hot_button_ && hot_button_ != button)
SetHotTrackedButton(nullptr);
}
MenuPart part = GetMenuPart(source, event->location());
if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
SetSelectionOnPointerDown(source, event);
event->StopPropagation();
} else if (event->type() == ui::ET_GESTURE_LONG_PRESS) {
if (part.type == MenuPart::Type::kMenuItem && part.menu) {
gfx::Point screen_location(event->location());
View::ConvertPointToScreen(source->GetScrollViewContainer(),
&screen_location);
if (ShowContextMenu(part.menu, screen_location, ui::MENU_SOURCE_TOUCH))
event->StopPropagation();
}
} else if (event->type() == ui::ET_GESTURE_TAP) {
if (!part.is_scroll() && part.menu &&
!(part.should_submenu_show && part.menu->HasSubmenu())) {
const int command = part.menu->GetCommand();
if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
command, *event)) {
item_selected_by_touch_ = true;
part.menu->GetDelegate()->ExecuteCommand(command, 0);
} else if (part.menu->GetDelegate()->IsTriggerableEvent(part.menu,
*event)) {
item_selected_by_touch_ = true;
Accept(part.menu, event->flags());
}
event->StopPropagation();
} else if (part.type == MenuPart::Type::kMenuItem) {
// User either tapped on empty space, or a menu that has children.
SetSelection(part.menu ? part.menu.get() : state_.item.get(),
SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
event->StopPropagation();
}
} else if (event->type() == ui::ET_GESTURE_TAP_CANCEL && part.menu &&
part.type == MenuPart::Type::kMenuItem) {
// Move the selection to the parent menu so that the selection in the
// current menu is unset. Make sure the submenu remains open by sending the
// appropriate SetSelectionTypes flags.
SetSelection(part.menu->GetParentMenuItem(),
SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
event->StopPropagation();
}
if (event->stopped_propagation())
return;
if (!part.submenu)
return;
part.submenu->OnGestureEvent(event);
}
void MenuController::OnTouchEvent(SubmenuView* source, ui::TouchEvent* event) {
// Bail if owner wants the current active gesture sequence.
if (owner_ && send_gesture_events_to_owner())
return;
if (event->type() == ui::ET_TOUCH_PRESSED) {
MenuPart part = GetMenuPart(source, event->location());
if (part.type == MenuPart::Type::kNone) {
RepostEventAndCancel(source, event);
event->SetHandled();
}
}
}
View* MenuController::GetTooltipHandlerForPoint(SubmenuView* source,
const gfx::Point& point) {
MenuHostRootView* root_view = GetRootView(source, point);
return root_view ? root_view->ProcessGetTooltipHandlerForPoint(point)
: nullptr;
}
void MenuController::ViewHierarchyChanged(
SubmenuView* source,
const ViewHierarchyChangedDetails& details) {
if (!details.is_add) {
// If the current mouse handler is removed, remove it as the handler.
if (details.child == current_mouse_event_target_) {
current_mouse_event_target_ = nullptr;
current_mouse_pressed_state_ = 0;
}
// Update |hot_button_| (both in |this| and in |menu_stack_| if it gets
// removed while a menu is up.
if (details.child == hot_button_) {
hot_button_ = nullptr;
for (auto& nested_state : menu_stack_) {
State& state = nested_state.first;
if (details.child == state.hot_button)
state.hot_button = nullptr;
}
}
}
}
bool MenuController::GetDropFormats(
SubmenuView* source,
int* formats,
std::set<ui::ClipboardFormatType>* format_types) {
return source->GetMenuItem()->GetDelegate()->GetDropFormats(
source->GetMenuItem(), formats, format_types);
}
bool MenuController::AreDropTypesRequired(SubmenuView* source) {
return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired(
source->GetMenuItem());
}
bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) {
return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(),
data);
}
void MenuController::OnDragEntered(SubmenuView* source,
const ui::DropTargetEvent& event) {
valid_drop_coordinates_ = false;
}
int MenuController::OnDragUpdated(SubmenuView* source,
const ui::DropTargetEvent& event) {
StopCancelAllTimer();
gfx::Point screen_loc(event.location());
View::ConvertPointToScreen(source, &screen_loc);
if (valid_drop_coordinates_ && screen_loc == drop_pt_)
return last_drop_operation_;
drop_pt_ = screen_loc;
valid_drop_coordinates_ = true;
MenuItemView* menu_item = GetMenuItemAt(source, event.x(), event.y());
bool over_empty_menu = false;
if (!menu_item) {
// See if we're over an empty menu.
menu_item = GetEmptyMenuItemAt(source, event.x(), event.y());
if (menu_item)
over_empty_menu = true;
}
MenuDelegate::DropPosition drop_position = MenuDelegate::DropPosition::kNone;
int drop_operation = ui::DragDropTypes::DRAG_NONE;
if (menu_item) {
gfx::Point menu_item_loc(event.location());
View::ConvertPointToTarget(source, menu_item, &menu_item_loc);
MenuItemView* query_menu_item;
if (!over_empty_menu) {
int menu_item_height = menu_item->height();
if (menu_item->HasSubmenu() &&
(menu_item_loc.y() > kDropBetweenPixels &&
menu_item_loc.y() < (menu_item_height - kDropBetweenPixels))) {
drop_position = MenuDelegate::DropPosition::kOn;
} else {
drop_position = (menu_item_loc.y() < menu_item_height / 2)
? MenuDelegate::DropPosition::kBefore
: MenuDelegate::DropPosition::kAfter;
}
query_menu_item = menu_item;
} else {
query_menu_item = menu_item->GetParentMenuItem();
drop_position = MenuDelegate::DropPosition::kOn;
}
drop_operation =
static_cast<int>(menu_item->GetDelegate()->GetDropOperation(
query_menu_item, event, &drop_position));
// If the menu has a submenu, schedule the submenu to open.
SetSelection(menu_item, menu_item->HasSubmenu() ? SELECTION_OPEN_SUBMENU
: SELECTION_DEFAULT);
if (drop_position == MenuDelegate::DropPosition::kNone ||
drop_operation == ui::DragDropTypes::DRAG_NONE)
menu_item = nullptr;
} else {
SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU);
}
SetDropMenuItem(menu_item, drop_position);
last_drop_operation_ = drop_operation;
return drop_operation;
}
void MenuController::OnDragExited(SubmenuView* source) {
StartCancelAllTimer();
if (drop_target_) {
StopShowTimer();
SetDropMenuItem(nullptr, MenuDelegate::DropPosition::kNone);
}
}
views::View::DropCallback MenuController::GetDropCallback(
SubmenuView* source,
const ui::DropTargetEvent& event) {
DCHECK(drop_target_);
// NOTE: the delegate may delete us after invoking GetDropCallback, as such
// we don't call cancel here.
MenuItemView* item = state_.item;
DCHECK(item);
MenuItemView* drop_target = drop_target_;
MenuDelegate::DropPosition drop_position = drop_position_;
// Close all menus, including any nested menus.
SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
CloseAllNestedMenus();
// Set state such that we exit.
showing_ = false;
SetExitType(ExitType::kAll);
// If over an empty menu item, drop occurs on the parent.
if (drop_target->GetID() == MenuItemView::kEmptyMenuItemViewID)
drop_target = drop_target->GetParentMenuItem();
if (for_drop_) {
delegate_->OnMenuClosed(
internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE,
item->GetRootMenuItem(), accept_event_flags_);
}
// WARNING: the call to MenuClosed deletes us.
return drop_target->GetDelegate()->GetDropCallback(drop_target, drop_position,
event);
}
void MenuController::OnDragEnteredScrollButton(SubmenuView* source,
bool is_up) {
MenuPart part;
part.type = is_up ? MenuPart::Type::kScrollUp : MenuPart::Type::kScrollDown;
part.submenu = source;
UpdateScrolling(part);
// Do this to force the selection to hide.
SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DropPosition::kNone);
StopCancelAllTimer();
}
void MenuController::OnDragExitedScrollButton(SubmenuView* source) {
StartCancelAllTimer();
SetDropMenuItem(nullptr, MenuDelegate::DropPosition::kNone);
StopScrolling();
}
void MenuController::OnDragWillStart() {
DCHECK(!drag_in_progress_);
drag_in_progress_ = true;
}
void MenuController::OnDragComplete(bool should_close) {
DCHECK(drag_in_progress_);
drag_in_progress_ = false;
// During a drag, mouse events are processed directly by the widget, and not
// sent to the MenuController. At drag completion, reset pressed state and
// the event target.
current_mouse_pressed_state_ = 0;
current_mouse_event_target_ = nullptr;
// Only attempt to close if the MenuHost said to.
if (should_close) {
if (showing_) {
// During a drag operation there are several ways in which this can be
// canceled and deleted. Verify that this is still active before closing
// the widgets.
if (GetActiveInstance() == this) {
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
CloseAllNestedMenus();
Cancel(ExitType::kAll);
// The above may have deleted us. If not perform a full shutdown.
if (!this_ref)
return;
ExitMenu();
}
} else if (exit_type_ == ExitType::kAll) {
// We may have been canceled during the drag. If so we still need to fully
// shutdown.
ExitMenu();
}
}
}
ui::PostDispatchAction MenuController::OnWillDispatchKeyEvent(
ui::KeyEvent* event) {
if (exit_type() == ExitType::kAll || exit_type() == ExitType::kDestroyed) {
// If the event has arrived after the menu's exit type has changed but
// before its Widgets have been destroyed, the event will continue its
// normal propagation for the following reason:
// If the user accepts a menu item in a nested menu, and the menu item
// action starts a base::RunLoop; IDC_BOOKMARK_BAR_OPEN_ALL sometimes opens
// a modal dialog. The modal dialog starts a base::RunLoop and keeps the
// base::RunLoop running for the duration of its lifetime.
return ui::POST_DISPATCH_PERFORM_DEFAULT;
}
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
if (event->type() == ui::ET_KEY_PRESSED) {
bool key_handled = false;
#if BUILDFLAG(IS_MAC)
// Special handling for Option-Up and Option-Down, which should behave like
// Home and End respectively in menus.
if ((event->flags() & ui::EF_ALT_DOWN)) {
ui::KeyEvent rewritten_event(*event);
if (event->key_code() == ui::VKEY_UP) {
rewritten_event.set_key_code(ui::VKEY_HOME);
} else if (event->key_code() == ui::VKEY_DOWN) {
rewritten_event.set_key_code(ui::VKEY_END);
}
key_handled = OnKeyPressed(rewritten_event);
} else {
key_handled = OnKeyPressed(*event);
}
#else
key_handled = OnKeyPressed(*event);
#endif
if (key_handled)
event->StopPropagation();
// Key events can lead to this being deleted.
if (!this_ref) {
event->StopPropagation();
return ui::POST_DISPATCH_NONE;
}
if (!IsEditableCombobox() && !event->stopped_propagation()) {
// Do not check mnemonics if the Alt or Ctrl modifiers are pressed. For
// example Ctrl+<T> is an accelerator, but <T> only is a mnemonic.
const int kKeyFlagsMask =
ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN;
const int flags = event->flags();
if (exit_type() == ExitType::kNone && (flags & kKeyFlagsMask) == 0) {
char16_t c = event->GetCharacter();
SelectByChar(c);
// SelectByChar can lead to this being deleted.
if (!this_ref) {
event->StopPropagation();
return ui::POST_DISPATCH_NONE;
}
}
}
}
ui::Accelerator accelerator(*event);
#if BUILDFLAG(IS_MAC)
if (AcceleratorShouldCancelMenu(accelerator)) {
Cancel(ExitType::kAll);
return ui::POST_DISPATCH_PERFORM_DEFAULT;
}
#endif
ViewsDelegate::ProcessMenuAcceleratorResult result =
ViewsDelegate::GetInstance()->ProcessAcceleratorWhileMenuShowing(
accelerator);
// Above can lead to |this| being deleted.
if (!this_ref) {
event->StopPropagation();
return ui::POST_DISPATCH_NONE;
}
if (result == ViewsDelegate::ProcessMenuAcceleratorResult::CLOSE_MENU) {
Cancel(ExitType::kAll);
event->StopPropagation();
return ui::POST_DISPATCH_NONE;
}
if (IsEditableCombobox()) {
const base::flat_set<ui::KeyboardCode> kKeysThatDontPropagate = {
ui::VKEY_DOWN, ui::VKEY_UP, ui::VKEY_ESCAPE, ui::VKEY_F4,
ui::VKEY_RETURN};
if (kKeysThatDontPropagate.find(event->key_code()) ==
kKeysThatDontPropagate.end())
return ui::POST_DISPATCH_PERFORM_DEFAULT;
}
event->StopPropagation();
return ui::POST_DISPATCH_NONE;
}
void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) {
if (submenu->IsShowing()) {
gfx::Point point = display::Screen::GetScreen()->GetCursorScreenPoint();
const SubmenuView* root_submenu =
submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu();
View::ConvertPointFromScreen(root_submenu->GetWidget()->GetRootView(),
&point);
HandleMouseLocation(submenu, point);
}
}
void MenuController::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(owner_, widget);
owner_->RemoveObserver(this);
owner_ = nullptr;
native_view_for_gestures_ = nullptr;
}
bool MenuController::IsCancelAllTimerRunningForTest() {
return cancel_all_timer_.IsRunning();
}
void MenuController::ClearStateForTest() {
state_ = State();
pending_state_ = State();
}
// static
void MenuController::TurnOffMenuSelectionHoldForTest() {
menu_selection_hold_time = base::TimeDelta();
}
void MenuController::OnMenuItemDestroying(MenuItemView* menu_item) {
#if BUILDFLAG(IS_MAC)
if (menu_closure_animation_ && menu_closure_animation_->item() == menu_item)
menu_closure_animation_.reset();
#endif
UnregisterAlertedItem(menu_item);
}
void MenuController::AnimationProgressed(const gfx::Animation* animation) {
DCHECK_EQ(animation, &alert_animation_);
// Schedule paints at each alerted menu item. The menu items pull the
// animation's current value in their OnPaint methods.
for (MenuItemView* item : alerted_items_) {
if (item->GetParentMenuItem()->SubmenuIsShowing())
item->SchedulePaint();
}
}
void MenuController::SetSelection(MenuItemView* menu_item,
int selection_types) {
size_t paths_differ_at = 0;
std::vector<MenuItemView*> current_path;
std::vector<MenuItemView*> new_path;
BuildPathsAndCalculateDiff(pending_state_.item, menu_item, ¤t_path,
&new_path, &paths_differ_at);
size_t current_size = current_path.size();
size_t new_size = new_path.size();
// ACTIONABLE_SUBMENUs can change without changing the pending item, this
// occurs when selection moves from the COMMAND area to the SUBMENU area of
// the ACTIONABLE_SUBMENU.
const bool pending_item_changed =
pending_state_.item != menu_item ||
pending_state_.submenu_open !=
!!(selection_types & SELECTION_OPEN_SUBMENU);
if (pending_item_changed && pending_state_.item)
SetHotTrackedButton(nullptr);
// Notify the old path it isn't selected.
MenuDelegate* current_delegate =
current_path.empty() ? nullptr : current_path.front()->GetDelegate();
for (size_t i = paths_differ_at; i < current_size; ++i) {
if (current_delegate &&
(current_path[i]->GetType() == MenuItemView::Type::kSubMenu ||
current_path[i]->GetType() ==
MenuItemView::Type::kActionableSubMenu)) {
current_delegate->WillHideMenu(current_path[i]);
}
current_path[i]->SetSelected(false);
}
// Notify the new path it is selected.
for (size_t i = paths_differ_at; i < new_size; ++i) {
new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds());
new_path[i]->SetSelected(true);
if (new_path[i]->GetType() == MenuItemView::Type::kActionableSubMenu) {
new_path[i]->SetSelectionOfActionableSubmenu(
(selection_types & SELECTION_OPEN_SUBMENU) != 0);
}
}
if (menu_item &&
menu_item->GetType() == MenuItemView::Type::kActionableSubMenu) {
menu_item->SetSelectionOfActionableSubmenu(
(selection_types & SELECTION_OPEN_SUBMENU) != 0);
}
DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);
pending_state_.item = menu_item;
pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;
// Stop timers.
StopCancelAllTimer();
// Resets show timer only when pending menu item is changed.
if (pending_item_changed)
StopShowTimer();
if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
CommitPendingSelection();
else if (pending_item_changed)
StartShowTimer();
// Notify an accessibility focus event on all menu items except for the root.
if (menu_item && pending_item_changed &&
(MenuDepth(menu_item) != 1 ||
menu_item->GetType() != MenuItemView::Type::kSubMenu ||
(menu_item->GetType() == MenuItemView::Type::kActionableSubMenu &&
(selection_types & SELECTION_OPEN_SUBMENU) == 0))) {
// Before firing the selection event, ensure that focus appears to be
// within the popup. This is helpful for ATs on some platforms,
// specifically on Windows, where selection events in a list are mapped
// to focus events. Without this call, the focus appears to be elsewhere.
menu_item->GetViewAccessibility().SetPopupFocusOverride();
menu_item->NotifyAccessibilityEvent(ax::mojom::Event::kSelection, true);
// Notify an accessibility selected children changed event on the parent
// submenu.
if (menu_item->GetParentMenuItem() &&
menu_item->GetParentMenuItem()->GetSubmenu()) {
menu_item->GetParentMenuItem()->GetSubmenu()->NotifyAccessibilityEvent(
ax::mojom::Event::kSelectedChildrenChanged,
true /* send_native_event */);
}
}
}
void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
const ui::LocatedEvent* event) {
if (for_drop_)
return;
DCHECK(!active_mouse_view_tracker_->view());
MenuPart part = GetMenuPart(source, event->location());
if (part.is_scroll())
return; // Ignore presses on scroll buttons.
// When this menu is opened through a touch event, a simulated right-click
// is sent before the menu appears. Ignore it.
if ((event->flags() & ui::EF_RIGHT_MOUSE_BUTTON) &&
(event->flags() & ui::EF_FROM_TOUCH))
return;
if (part.type == MenuPart::Type::kNone ||
(part.type == MenuPart::Type::kMenuItem && part.menu &&
part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) {
// Remember the time stamp of the current (press down) event. The owner can
// then use this to figure out if this menu was finished with the same click
// which is sent to it thereafter.
closing_event_time_ = event->time_stamp();
// Event wasn't pressed over any menu, or the active menu, cancel.
RepostEventAndCancel(source, event);
// Do not repost events for Linux Aura because this behavior is more
// consistent with the behavior of other Linux apps.
return;
}
// On a press we immediately commit the selection, that way a submenu
// pops up immediately rather than after a delay.
int selection_types = SELECTION_UPDATE_IMMEDIATELY;
if (!part.menu) {
part.menu = part.parent;
selection_types |= SELECTION_OPEN_SUBMENU;
} else {
if (part.menu->GetDelegate()->CanDrag(part.menu)) {
possible_drag_ = true;
press_pt_ = event->location();
}
if (part.menu->HasSubmenu() && part.should_submenu_show)
selection_types |= SELECTION_OPEN_SUBMENU;
}
SetSelection(part.menu, selection_types);
}
void MenuController::StartDrag(SubmenuView* source,
const gfx::Point& location) {
MenuItemView* item = state_.item;
DCHECK(item);
// Points are in the coordinates of the submenu, need to map to that of
// the selected item. Additionally source may not be the parent of
// the selected item, so need to map to screen first then to item.
gfx::Point press_loc(location);
View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
View::ConvertPointFromScreen(item, &press_loc);
gfx::Point widget_loc(press_loc);
View::ConvertPointToWidget(item, &widget_loc);
float raster_scale = ScaleFactorForDragFromWidget(source->GetWidget());
gfx::Canvas canvas(item->size(), raster_scale, false /* opaque */);
item->PaintForDrag(&canvas);
gfx::ImageSkia image =
gfx::ImageSkia::CreateFromBitmap(canvas.GetBitmap(), raster_scale);
std::unique_ptr<OSExchangeData> data(std::make_unique<OSExchangeData>());
item->GetDelegate()->WriteDragData(item, data.get());
data->provider().SetDragImage(image, press_loc.OffsetFromOrigin());
StopScrolling();
int drag_ops = item->GetDelegate()->GetDragOperations(item);
did_initiate_drag_ = true;
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
// TODO(varunjain): Properly determine and send DragEventSource below.
item->GetWidget()->RunShellDrag(nullptr, std::move(data), widget_loc,
drag_ops, ui::mojom::DragEventSource::kMouse);
// MenuController may have been deleted so check before accessing member
// variables.
if (this_ref)
did_initiate_drag_ = false;
}
bool MenuController::OnKeyPressed(const ui::KeyEvent& event) {
DCHECK_EQ(event.type(), ui::ET_KEY_PRESSED);
// Do not process while performing drag-and-drop.
if (for_drop_)
return false;
bool handled_key_code = false;
const ui::KeyboardCode key_code = event.key_code();
switch (key_code) {
case ui::VKEY_HOME:
if (IsEditableCombobox())
break;
MoveSelectionToFirstOrLastItem(INCREMENT_SELECTION_DOWN);
break;
case ui::VKEY_END:
if (IsEditableCombobox())
break;
MoveSelectionToFirstOrLastItem(INCREMENT_SELECTION_UP);
break;
case ui::VKEY_UP:
case ui::VKEY_PRIOR:
IncrementSelection(INCREMENT_SELECTION_UP);
break;
case ui::VKEY_DOWN:
case ui::VKEY_NEXT:
IncrementSelection(INCREMENT_SELECTION_DOWN);
break;
// Handling of VK_RIGHT and VK_LEFT is different depending on the UI
// layout.
case ui::VKEY_RIGHT:
if (IsEditableCombobox())
break;
if (base::i18n::IsRTL())
CloseSubmenu();
else
OpenSubmenuChangeSelectionIfCan();
break;
case ui::VKEY_LEFT:
if (IsEditableCombobox())
break;
if (base::i18n::IsRTL())
OpenSubmenuChangeSelectionIfCan();
else
CloseSubmenu();
break;
// On Mac, treat space the same as return.
#if !BUILDFLAG(IS_MAC)
case ui::VKEY_SPACE:
SendAcceleratorToHotTrackedView(event.flags());
break;
#endif
case ui::VKEY_F4:
if (!IsCombobox())
break;
// Fallthrough to accept or dismiss combobox menus on F4, like windows.
[[fallthrough]];
case ui::VKEY_RETURN:
#if BUILDFLAG(IS_MAC)
case ui::VKEY_SPACE:
#endif
// An odd special case: if a prefix selection is in flight, space should
// add to that selection rather than activating the menu. This is
// important for allowing the user to select between items that have the
// same first word.
if (key_code == ui::VKEY_SPACE &&
MenuConfig::instance().all_menus_use_prefix_selection &&
ShouldContinuePrefixSelection()) {
break;
}
if (pending_state_.item) {
if (pending_state_.item->HasSubmenu()) {
if ((key_code == ui::VKEY_F4 ||
(key_code == ui::VKEY_RETURN && IsEditableCombobox())) &&
pending_state_.item->GetSubmenu()->IsShowing())
Cancel(ExitType::kAll);
else
OpenSubmenuChangeSelectionIfCan();
} else {
handled_key_code = true;
if (!SendAcceleratorToHotTrackedView(event.flags()) &&
pending_state_.item->GetEnabled()) {
const int command = pending_state_.item->GetCommand();
if (pending_state_.item->GetDelegate()
->ShouldExecuteCommandWithoutClosingMenu(command, event)) {
pending_state_.item->GetDelegate()->ExecuteCommand(command, 0);
} else {
Accept(pending_state_.item, event.flags());
}
}
}
}
break;
case ui::VKEY_ESCAPE:
if (!state_.item->GetParentMenuItem() ||
(!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
(!state_.item->SubmenuIsShowing()))) {
// User pressed escape and current menu has no submenus. If we are
// nested, close the current menu on the stack. Otherwise fully exit the
// menu.
Cancel(delegate_stack_.size() > 1 ? ExitType::kOutermost
: ExitType::kAll);
break;
}
CloseSubmenu();
break;
#if !BUILDFLAG(IS_MAC)
case ui::VKEY_APPS: {
Button* hot_view = GetFirstHotTrackedView(pending_state_.item);
if (hot_view) {
hot_view->ShowContextMenu(hot_view->GetKeyboardContextMenuLocation(),
ui::MENU_SOURCE_KEYBOARD);
} else if (pending_state_.item->GetEnabled() &&
pending_state_.item->GetRootMenuItem() !=
pending_state_.item) {
// Show the context menu for the given menu item. We don't try to show
// the menu for the (boundless) root menu item. This can happen, e.g.,
// when the user hits the APPS key after opening the menu, when no item
// is selected, but showing a context menu for an implicitly-selected
// and invisible item doesn't make sense.
ShowContextMenu(pending_state_.item,
pending_state_.item->GetKeyboardContextMenuLocation(),
ui::MENU_SOURCE_KEYBOARD);
}
break;
}
#endif
#if BUILDFLAG(IS_WIN)
// On Windows, pressing Alt and F10 keys should hide the menu to match the
// OS behavior.
case ui::VKEY_MENU:
case ui::VKEY_F10:
Cancel(ExitType::kAll);
break;
#endif
default:
break;
}
return handled_key_code;
}
MenuController::MenuController(bool for_drop,
internal::MenuControllerDelegate* delegate)
: for_drop_(for_drop),
active_mouse_view_tracker_(std::make_unique<ViewTracker>()),
delegate_(delegate),
alert_animation_(this) {
delegate_stack_.push_back(delegate_);
active_instance_ = this;
}
MenuController::~MenuController() {
DCHECK(!showing_);
if (owner_)
owner_->RemoveObserver(this);
if (active_instance_ == this)
active_instance_ = nullptr;
StopShowTimer();
StopCancelAllTimer();
CHECK(!IsInObserverList());
}
bool MenuController::SendAcceleratorToHotTrackedView(int event_flags) {
Button* hot_view = GetFirstHotTrackedView(pending_state_.item);
if (!hot_view)
return false;
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
ui::Accelerator accelerator(ui::VKEY_RETURN, event_flags);
hot_view->AcceleratorPressed(accelerator);
// An accelerator may have canceled the menu after activation.
if (this_ref) {
Button* button = static_cast<Button*>(hot_view);
SetHotTrackedButton(button);
}
return true;
}
void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
MenuAnchorPosition position,
bool context_menu) {
pending_state_.context_menu = context_menu;
pending_state_.initial_bounds = bounds;
pending_state_.anchor = AdjustAnchorPositionForRtl(position);
// Calculate the bounds of the monitor we'll show menus on. Do this once to
// avoid repeated system queries for the info.
pending_state_.monitor_bounds = display::Screen::GetScreen()
->GetDisplayNearestPoint(bounds.origin())
.work_area();
if (!pending_state_.monitor_bounds.Contains(bounds)) {
// Use the monitor area if the work area doesn't contain the bounds. This
// handles showing a menu from the launcher.
gfx::Rect monitor_area = display::Screen::GetScreen()
->GetDisplayNearestPoint(bounds.origin())
.bounds();
if (monitor_area.Contains(bounds))
pending_state_.monitor_bounds = monitor_area;
}
}
// static
MenuAnchorPosition MenuController::AdjustAnchorPositionForRtl(
MenuAnchorPosition position) {
if (!base::i18n::IsRTL())
return position;
// Reverse anchor position for RTL languages.
switch (position) {
case MenuAnchorPosition::kTopLeft:
return MenuAnchorPosition::kTopRight;
case MenuAnchorPosition::kTopRight:
return MenuAnchorPosition::kTopLeft;
case MenuAnchorPosition::kBubbleTopLeft:
return MenuAnchorPosition::kBubbleTopRight;
case MenuAnchorPosition::kBubbleTopRight:
return MenuAnchorPosition::kBubbleTopLeft;
case MenuAnchorPosition::kBubbleLeft:
return MenuAnchorPosition::kBubbleRight;
case MenuAnchorPosition::kBubbleRight:
return MenuAnchorPosition::kBubbleLeft;
case MenuAnchorPosition::kBubbleBottomLeft:
return MenuAnchorPosition::kBubbleBottomRight;
case MenuAnchorPosition::kBubbleBottomRight:
return MenuAnchorPosition::kBubbleBottomLeft;
case MenuAnchorPosition::kBottomCenter:
return position;
}
}
void MenuController::Accept(MenuItemView* item, int event_flags) {
// This counts as activation of a menu item. We don't put this logic in
// ReallyAccept() because we expect activation to happen while the element is
// visible to the user, but ReallyAccept() is called on Mac *after* the menu
// is closed.
if (item) {
const ui::ElementIdentifier id = item->GetProperty(kElementIdentifierKey);
if (id)
views::ElementTrackerViews::GetInstance()->NotifyViewActivated(id, item);
}
// EndPopupFocusOverride before closing the menu, the focus should move on
// after closing the menu.
item->GetViewAccessibility().EndPopupFocusOverride();
// Setting `result_` now means that a future Cancel() call will include that
// `result_` in its delegate notification, and thus the clicked command will
// still be executed even if the menu is canceled during the close animation.
// See crbug.com/1251450. Note that we don't set the exit type at this point,
// because we want the Cancel's exit type to take precedence.
result_ = item;
accept_event_flags_ = event_flags;
#if BUILDFLAG(IS_MAC)
menu_closure_animation_ = std::make_unique<MenuClosureAnimationMac>(
item, item->GetParentMenuItem()->GetSubmenu(),
base::BindOnce(&MenuController::ReallyAccept, base::Unretained(this)));
menu_closure_animation_->Start();
#else
ReallyAccept();
#endif
}
void MenuController::ReallyAccept() {
DCHECK(!for_drop_);
#if BUILDFLAG(IS_MAC)
// Reset the closure animation since it's now finished - this also unblocks
// input events for the menu.
menu_closure_animation_.reset();
#endif
if (result_ && !menu_stack_.empty() &&
!result_->GetDelegate()->ShouldCloseAllMenusOnExecute(
result_->GetCommand())) {
SetExitType(ExitType::kOutermost);
} else {
SetExitType(ExitType::kAll);
}
ExitMenu();
}
bool MenuController::ShowSiblingMenu(SubmenuView* source,
const gfx::Point& mouse_location) {
if (!menu_stack_.empty() || !pressed_lock_.get())
return false;
View* source_view = source->GetScrollViewContainer();
if (mouse_location.x() >= 0 && mouse_location.x() < source_view->width() &&
mouse_location.y() >= 0 && mouse_location.y() < source_view->height()) {
// The mouse is over the menu, no need to continue.
return false;
}
// TODO(oshima): Replace with views only API.
if (!owner_ || !display::Screen::GetScreen()->IsWindowUnderCursor(
owner_->GetNativeWindow())) {
return false;
}
// The user moved the mouse outside the menu and over the owning window. See
// if there is a sibling menu we should show.
gfx::Point screen_point(mouse_location);
View::ConvertPointToScreen(source_view, &screen_point);
MenuAnchorPosition anchor;
bool has_mnemonics;
MenuButton* button = nullptr;
MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->GetSiblingMenu(
source->GetMenuItem()->GetRootMenuItem(), screen_point, &anchor,
&has_mnemonics, &button);
if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
return false;
delegate_->SiblingMenuCreated(alt_menu);
// If the delegate returns a menu, they must also return a button.
CHECK(button);
// There is a sibling menu, update the button state, hide the current menu
// and show the new one.
pressed_lock_ = button->button_controller()->TakeLock(true, nullptr);
// Need to reset capture when we show the menu again, otherwise we aren't
// going to get any events.
did_capture_ = false;
gfx::Point screen_menu_loc;
View::ConvertPointToScreen(button, &screen_menu_loc);
// It is currently not possible to show a submenu recursively in a bubble.
DCHECK(!MenuItemView::IsBubble(anchor));
UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
button->width(), button->height()),
anchor, state_.context_menu);
alt_menu->PrepareForRun(
false, has_mnemonics,
source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
alt_menu->controller_ = AsWeakPtr();
SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
return true;
}
bool MenuController::ShowContextMenu(MenuItemView* menu_item,
const gfx::Point& screen_location,
ui::MenuSourceType source_type) {
// Set the selection immediately, making sure the submenu is only open
// if it already was.
int selection_types = SELECTION_UPDATE_IMMEDIATELY;
if (state_.item == pending_state_.item && state_.submenu_open)
selection_types |= SELECTION_OPEN_SUBMENU;
SetSelection(pending_state_.item, selection_types);
if (menu_item->GetDelegate()->ShowContextMenu(
menu_item, menu_item->GetCommand(), screen_location, source_type)) {
SendMouseCaptureLostToActiveView();
return true;
}
return false;
}
void MenuController::CloseAllNestedMenus() {
for (auto& nested_menu : menu_stack_) {
State& state = nested_menu.first;
MenuItemView* last_item = state.item;
for (MenuItemView* item = last_item; item;
item = item->GetParentMenuItem()) {
CloseMenu(item);
last_item = item;
}
state.submenu_open = false;
state.item = last_item;
}
}
MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
// Walk the view hierarchy until we find a menu item (or the root).
View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
while (child_under_mouse &&
child_under_mouse->GetID() != MenuItemView::kMenuItemViewID) {
child_under_mouse = child_under_mouse->parent();
}
if (child_under_mouse && child_under_mouse->GetEnabled() &&
child_under_mouse->GetID() == MenuItemView::kMenuItemViewID) {
return static_cast<MenuItemView*>(child_under_mouse);
}
return nullptr;
}
MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
if (child_under_mouse &&
child_under_mouse->GetID() == MenuItemView::kEmptyMenuItemViewID) {
return static_cast<MenuItemView*>(child_under_mouse);
}
return nullptr;
}
bool MenuController::IsScrollButtonAt(SubmenuView* source,
int x,
int y,
MenuPart::Type* part) {
MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
View* child_under_mouse =
scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
if (child_under_mouse && child_under_mouse->GetEnabled()) {
if (child_under_mouse == scroll_view->scroll_up_button()) {
*part = MenuPart::Type::kScrollUp;
return true;
}
if (child_under_mouse == scroll_view->scroll_down_button()) {
*part = MenuPart::Type::kScrollDown;
return true;
}
}
return false;
}
MenuController::MenuPart MenuController::GetMenuPart(
SubmenuView* source,
const gfx::Point& source_loc) {
gfx::Point screen_loc(source_loc);
View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
}
MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
MenuItemView* item,
const gfx::Point& screen_loc) {
MenuPart part;
for (; item; item = item->GetParentMenuItem()) {
if (item->SubmenuIsShowing() &&
GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
&part)) {
return part;
}
}
return part;
}
bool MenuController::GetMenuPartByScreenCoordinateImpl(
SubmenuView* menu,
const gfx::Point& screen_loc,
MenuPart* part) {
// Is the mouse over the scroll buttons?
gfx::Point scroll_view_loc = screen_loc;
View* scroll_view_container = menu->GetScrollViewContainer();
View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
if (scroll_view_loc.x() < 0 ||
scroll_view_loc.x() >= scroll_view_container->width() ||
scroll_view_loc.y() < 0 ||
scroll_view_loc.y() >= scroll_view_container->height()) {
// Point isn't contained in menu.
return false;
}
if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
&(part->type))) {
part->submenu = menu;
return true;
}
// Not over the scroll button. Check the actual menu.
if (DoesSubmenuContainLocation(menu, screen_loc)) {
gfx::Point menu_loc = screen_loc;
View::ConvertPointFromScreen(menu, &menu_loc);
part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
part->type = MenuPart::Type::kMenuItem;
part->submenu = menu;
part->should_submenu_show =
part->submenu && part->menu &&
(part->menu->GetType() == MenuItemView::Type::kSubMenu ||
IsLocationOverSubmenuAreaOfActionableSubmenu(part->menu, screen_loc));
if (!part->menu)
part->parent = menu->GetMenuItem();
return true;
}
// Return false for points on ash system UI menu shadows, to search parent
// menus.
if (use_ash_system_ui_layout_)
return false;
// While the mouse isn't over a menu item or the scroll buttons of menu, it
// is contained by menu and so we return true. If we didn't return true other
// menus would be searched, even though they are likely obscured by us.
return true;
}
MenuHostRootView* MenuController::GetRootView(SubmenuView* submenu,
const gfx::Point& source_loc) {
MenuPart part = GetMenuPart(submenu, source_loc);
SubmenuView* view = part.submenu;
return view && view->GetWidget()
? static_cast<MenuHostRootView*>(view->GetWidget()->GetRootView())
: nullptr;
}
void MenuController::ConvertLocatedEventForRootView(View* source,
View* dst,
ui::LocatedEvent* event) {
if (source->GetWidget()->GetRootView() == dst)
return;
gfx::Point new_location(event->location());
View::ConvertPointToScreen(source, &new_location);
View::ConvertPointFromScreen(dst, &new_location);
event->set_location(new_location);
}
bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
const gfx::Point& screen_loc) {
gfx::Point view_loc = screen_loc;
View::ConvertPointFromScreen(submenu, &view_loc);
gfx::Rect vis_rect = submenu->GetVisibleBounds();
return vis_rect.Contains(view_loc);
}
bool MenuController::IsLocationOverSubmenuAreaOfActionableSubmenu(
MenuItemView* item,
const gfx::Point& screen_loc) const {
if (!item || item->GetType() != MenuItemView::Type::kActionableSubMenu)
return false;
gfx::Point view_loc = screen_loc;
View::ConvertPointFromScreen(item, &view_loc);
if (base::i18n::IsRTL())
view_loc.set_x(item->GetMirroredXInView(view_loc.x()));
return item->GetSubmenuAreaOfActionableSubmenu().Contains(view_loc);
}
void MenuController::CommitPendingSelection() {
StopShowTimer();
size_t paths_differ_at = 0;
std::vector<MenuItemView*> current_path;
std::vector<MenuItemView*> new_path;
BuildPathsAndCalculateDiff(state_.item, pending_state_.item, ¤t_path,
&new_path, &paths_differ_at);
// Hide the old menu.
for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
CloseMenu(current_path[i]);
}
// Copy pending to state_, making sure to preserve the direction menus were
// opened.
std::list<bool> pending_open_direction;
state_.open_leading.swap(pending_open_direction);
state_ = pending_state_;
state_.open_leading.swap(pending_open_direction);
size_t menu_depth = MenuDepth(state_.item);
if (menu_depth == 0) {
state_.open_leading.clear();
} else {
for (size_t cached_size = state_.open_leading.size();
cached_size >= menu_depth; --cached_size) {
state_.open_leading.pop_back();
}
}
if (!state_.item) {
// Nothing to select.
StopScrolling();
return;
}
// Open all the submenus preceeding the last menu item (last menu item is
// handled next).
if (new_path.size() > 1) {
for (auto i = new_path.begin(); i != new_path.end() - 1; ++i)
OpenMenu(*i);
}
if (state_.submenu_open) {
// The submenu should be open, open the submenu if the item has a submenu.
if (state_.item->HasSubmenu()) {
OpenMenu(state_.item);
} else {
state_.submenu_open = false;
}
} else if (state_.item->SubmenuIsShowing()) {
state_.item->GetSubmenu()->Hide();
}
if (scroll_task_.get() && scroll_task_->submenu()) {
// Stop the scrolling if none of the elements of the selection contain
// the menu being scrolled.
bool found = false;
for (MenuItemView* item = state_.item; item && !found;
item = item->GetParentMenuItem()) {
found = (item->SubmenuIsShowing() &&
item->GetSubmenu() == scroll_task_->submenu());
}
if (!found)
StopScrolling();
}
}
void MenuController::CloseMenu(MenuItemView* item) {
DCHECK(item);
if (!item->HasSubmenu())
return;
for (MenuItemView* subitem : item->GetSubmenu()->GetMenuItems())
UnregisterAlertedItem(subitem);
item->GetSubmenu()->Hide();
}
void MenuController::OpenMenu(MenuItemView* item) {
DCHECK(item);
if (item->GetSubmenu()->IsShowing()) {
return;
}
OpenMenuImpl(item, true);
did_capture_ = true;
}
void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
// TODO(oshima|sky): Don't show the menu if drag is in progress and
// this menu doesn't support drag drop. See crbug.com/110495.
if (show) {
size_t old_num_children = item->GetSubmenu()->children().size();
item->GetDelegate()->WillShowMenu(item);
if (old_num_children != item->GetSubmenu()->children().size()) {
// If the number of children changed then we may need to add empty items.
item->RemoveEmptyMenus();
item->AddEmptyMenus();
}
}
const MenuConfig& menu_config = MenuConfig::instance();
bool prefer_leading =
state_.open_leading.empty() ? true : state_.open_leading.back();
bool resulting_direction;
// Anchor for calculated bounds. Can be alternatively used by a system
// compositor for better positioning.
ui::OwnedWindowAnchor anchor;
// While the Windows 11 style menus uses the same bubble border as "touch-
// style" menus, some positioning calculations are different. Testing for that
// condition separately will allow those subtle positioning differences to be
// taken into account within CalculateBubbleMenuBounds() and elsewhere.
gfx::Rect bounds =
MenuItemView::IsBubble(state_.anchor) ||
(!IsCombobox() && menu_config.use_bubble_border &&
menu_config.CornerRadiusForMenu(this))
? CalculateBubbleMenuBounds(item, prefer_leading,
&resulting_direction, &anchor)
: CalculateMenuBounds(item, prefer_leading, &resulting_direction,
&anchor);
state_.open_leading.push_back(resulting_direction);
bool do_capture = (!did_capture_ && !for_drop_ && !IsEditableCombobox());
showing_submenu_ = true;
// Register alerted MenuItemViews so we can animate them. We do this here to
// handle both newly-opened submenus and submenus that have changed.
for (MenuItemView* subitem : item->GetSubmenu()->GetMenuItems()) {
if (subitem->is_alerted())
RegisterAlertedItem(subitem);
}
if (show) {
MenuHost::InitParams params;
params.parent = owner_;
params.bounds = bounds;
params.do_capture = do_capture;
params.native_view_for_gestures = native_view_for_gestures_;
params.owned_window_anchor = anchor;
params.parent_widget = parent_widget_;
if (item->GetParentMenuItem()) {
params.context = item->GetWidget();
// (crbug.com/1414232) The item to be open is a submenu. Make sure
// params.context is set.
DCHECK(params.context);
params.menu_type = ui::MenuType::kChildMenu;
} else if (state_.context_menu) {
if (!menu_stack_.empty()) {
auto* last_menu_item = menu_stack_.back().first.item.get();
if (last_menu_item->SubmenuIsShowing())
params.context = last_menu_item->GetSubmenu()->GetWidget();
else
params.context = last_menu_item->GetWidget();
} else {
params.context = owner_;
}
params.menu_type = ui::MenuType::kRootContextMenu;
} else {
params.context = owner_;
params.menu_type = ui::MenuType::kRootMenu;
}
item->GetSubmenu()->ShowAt(params);
// Figure out if the mouse is under the menu; if so, remember the mouse
// location so we can ignore the first mouse move event(s) with that
// location. We do this after ShowAt because ConvertPointFromScreen
// doesn't work correctly if the widget isn't shown.
if (item->GetSubmenu()->GetWidget() != nullptr) {
gfx::Point mouse_pos =
display::Screen::GetScreen()->GetCursorScreenPoint();
View::ConvertPointFromScreen(item->submenu_->GetWidget()->GetRootView(),
&mouse_pos);
MenuPart part_under_mouse = GetMenuPart(item->submenu_, mouse_pos);
if (part_under_mouse.type != MenuPart::Type::kNone)
menu_open_mouse_loc_ = mouse_pos;
}
item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
TooltipManager::kGroupingPropertyKey,
reinterpret_cast<void*>(MenuConfig::kMenuControllerGroupingId));
// Set the selection indices for this menu level based on traversal order.
SetSelectionIndices(item);
} else {
item->GetSubmenu()->Reposition(bounds, anchor);
}
showing_submenu_ = false;
}
void MenuController::MenuChildrenChanged(MenuItemView* item) {
DCHECK(item);
// Menu shouldn't be updated during drag operation.
DCHECK(!active_mouse_view_tracker_->view());
// If needed, refresh the AX index assignments.
if (item->GetProperty(kOrderedMenuChildren))
SetSelectionIndices(item);
// If the current item or pending item is a descendant of the item
// that changed, move the selection back to the changed item.
const MenuItemView* ancestor = state_.item;
while (ancestor && ancestor != item)
ancestor = ancestor->GetParentMenuItem();
if (!ancestor) {
ancestor = pending_state_.item;
while (ancestor && ancestor != item)
ancestor = ancestor->GetParentMenuItem();
if (!ancestor)
return;
}
SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
if (item->HasSubmenu())
OpenMenuImpl(item, false);
}
void MenuController::BuildPathsAndCalculateDiff(
MenuItemView* old_item,
MenuItemView* new_item,
std::vector<MenuItemView*>* old_path,
std::vector<MenuItemView*>* new_path,
size_t* first_diff_at) {
DCHECK(old_path && new_path && first_diff_at);
BuildMenuItemPath(old_item, old_path);
BuildMenuItemPath(new_item, new_path);
*first_diff_at = static_cast<size_t>(std::distance(
old_path->begin(), base::ranges::mismatch(*old_path, *new_path).first));
}
void MenuController::BuildMenuItemPath(MenuItemView* item,
std::vector<MenuItemView*>* path) {
if (!item)
return;
BuildMenuItemPath(item->GetParentMenuItem(), path);
path->push_back(item);
}
void MenuController::StartShowTimer() {
show_timer_.Start(FROM_HERE,
base::Milliseconds(MenuConfig::instance().show_delay), this,
&MenuController::CommitPendingSelection);
}
void MenuController::StopShowTimer() {
show_timer_.Stop();
}
void MenuController::StartCancelAllTimer() {
cancel_all_timer_.Start(
FROM_HERE, base::Milliseconds(kCloseOnExitTime),
base::BindOnce(&MenuController::Cancel, base::Unretained(this),
ExitType::kAll));
}
void MenuController::StopCancelAllTimer() {
cancel_all_timer_.Stop();
}
gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
bool prefer_leading,
bool* is_leading,
ui::OwnedWindowAnchor* anchor) {
DCHECK(item);
DCHECK(anchor);
SubmenuView* submenu = item->GetSubmenu();
DCHECK(submenu);
// For the first menu, anchor_rect is initial bounds. If |item| is a child
// menu, anchor_rect will be recalculated.
anchor->anchor_rect = state_.initial_bounds;
gfx::Point item_loc;
View::ConvertPointToScreen(item, &item_loc);
// Sets additional anchor parameters.
SetAnchorParametersForItem(item, item_loc, anchor);
gfx::Rect menu_bounds =
gfx::Rect(submenu->GetScrollViewContainer()->GetPreferredSize());
const gfx::Rect& monitor_bounds = state_.monitor_bounds;
const gfx::Rect& anchor_bounds = state_.initial_bounds;
// For comboboxes, ensure the menu is at least as wide as the anchor.
if (IsCombobox())
menu_bounds.set_width(std::max(menu_bounds.width(), anchor_bounds.width()));
// Don't let the menu go too wide or too tall.
menu_bounds.set_width(std::min(
menu_bounds.width(), item->GetDelegate()->GetMaxWidthForMenu(item)));
if (!monitor_bounds.IsEmpty()) {
menu_bounds.set_width(
std::min(menu_bounds.width(), monitor_bounds.width()));
menu_bounds.set_height(
std::min(menu_bounds.height(), monitor_bounds.height()));
}
// Assume we can honor prefer_leading.
*is_leading = prefer_leading;
const MenuConfig& menu_config = MenuConfig::instance();
// Not the first menu; position it relative to the bounds of its parent menu
// item.
if (item->GetParentMenuItem()) {
// We must make sure we take into account the UI layout. If the layout is
// RTL, then a 'leading' menu is positioned to the left of the parent menu
// item and not to the right.
const bool layout_is_rtl = base::i18n::IsRTL();
const bool create_on_right = prefer_leading != layout_is_rtl;
const int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
const int left_of_parent =
item_loc.x() - menu_bounds.width() + submenu_horizontal_inset;
const int right_of_parent =
item_loc.x() + item->width() - submenu_horizontal_inset;
MenuScrollViewContainer* container =
item->GetParentMenuItem()->GetSubmenu()->GetScrollViewContainer();
menu_bounds.set_y(item_loc.y() - container->GetInsets().top());
// Assume the menu can be placed in the preferred location.
menu_bounds.set_x(create_on_right ? right_of_parent : left_of_parent);
// Calculate anchor for |menu_bounds|. Screen bounds must be ignored here
// as system compositors that do not provide global screen coordinates will
// use this anchor (instead of bounds) and check if the window fits the
// screen area (if it's constrained, etc).
anchor->anchor_rect = menu_bounds;
anchor->anchor_rect.set_size({1, 1});
// TODO(1163646): handle RTL layout.
anchor->anchor_rect.set_x(left_of_parent + menu_bounds.width());
anchor->anchor_rect.set_width(menu_bounds.x() - anchor->anchor_rect.x());
// Everything after this check requires monitor bounds to be non-empty.
if (ShouldIgnoreScreenBoundsForMenus() || monitor_bounds.IsEmpty())
return menu_bounds;
// Menu does not actually fit where it was placed, move it to the other side
// and update |is_leading|.
if (menu_bounds.x() < monitor_bounds.x()) {
*is_leading = !layout_is_rtl;
menu_bounds.set_x(right_of_parent);
} else if (menu_bounds.right() > monitor_bounds.right()) {
*is_leading = layout_is_rtl;
menu_bounds.set_x(left_of_parent);
}
} else {
using MenuPosition = MenuItemView::MenuPosition;
// First item, align top left corner of menu with bottom left corner of
// anchor bounds.
menu_bounds.set_x(anchor_bounds.x());
menu_bounds.set_y(anchor_bounds.bottom());
const int above_anchor = anchor_bounds.y() - menu_bounds.height();
if (state_.anchor == MenuAnchorPosition::kTopRight) {
// Move the menu so that its right edge is aligned with the anchor
// bounds right edge.
menu_bounds.set_x(anchor_bounds.right() - menu_bounds.width());
} else if (state_.anchor == MenuAnchorPosition::kBottomCenter) {
// Try to fit the menu above the anchor bounds. If it doesn't fit, place
// it below.
const int horizontally_centered =
anchor_bounds.x() + (anchor_bounds.width() - menu_bounds.width()) / 2;
menu_bounds.set_x(horizontally_centered);
menu_bounds.set_y(above_anchor - kTouchYPadding);
if (!ShouldIgnoreScreenBoundsForMenus() &&
menu_bounds.y() < monitor_bounds.y())
menu_bounds.set_y(anchor_bounds.y() + kTouchYPadding);
}
if (item->actual_menu_position() == MenuPosition::kAboveBounds) {
// Menu has already been drawn above, put it above the anchor bounds.
menu_bounds.set_y(above_anchor);
}
// Everything beyond this point requires monitor bounds to be non-empty.
if (ShouldIgnoreScreenBoundsForMenus() || monitor_bounds.IsEmpty())
return menu_bounds;
// If the menu position is below or above the anchor bounds, force it to fit
// on the screen. Otherwise, try to fit the menu in the following locations:
// 1.) Below the anchor bounds
// 2.) Above the anchor bounds
// 3.) At the bottom of the monitor and off the side of the anchor bounds
if (item->actual_menu_position() == MenuPosition::kBelowBounds ||
item->actual_menu_position() == MenuPosition::kAboveBounds) {
// Menu has been drawn below/above the anchor bounds, make sure it fits
// on the screen in its current location.
const int drawn_width = menu_bounds.width();
menu_bounds.Intersect(monitor_bounds);
// Do not allow the menu to get narrower. This handles the case where the
// menu would have drawn off-screen, but the effective anchor was shifted
// at the end of this function. Preserve the width, so it is shifted
// again.
menu_bounds.set_width(drawn_width);
} else if (menu_bounds.bottom() <= monitor_bounds.bottom()) {
// Menu fits below anchor bounds.
item->set_actual_menu_position(MenuPosition::kBelowBounds);
} else if (above_anchor >= monitor_bounds.y()) {
// Menu fits above anchor bounds.
menu_bounds.set_y(above_anchor);
item->set_actual_menu_position(MenuPosition::kAboveBounds);
} else if (item->GetDelegate()->ShouldTryPositioningBesideAnchor()) {
const int left_of_anchor = anchor_bounds.x() - menu_bounds.width();
const int right_of_anchor = anchor_bounds.right();
menu_bounds.set_y(monitor_bounds.bottom() - menu_bounds.height());
if (state_.anchor == MenuAnchorPosition::kTopLeft) {
// Prefer menu to right of anchor bounds but move it to left if it
// doesn't fit.
menu_bounds.set_x(right_of_anchor);
if (menu_bounds.right() > monitor_bounds.right())
menu_bounds.set_x(left_of_anchor);
} else {
// Prefer menu to left of anchor bounds but move it to right if it
// doesn't fit.
menu_bounds.set_x(left_of_anchor);
if (menu_bounds.x() < monitor_bounds.x())
menu_bounds.set_x(right_of_anchor);
}
} else {
// The delegate doesn't want the menu repositioned to the side, and it
// doesn't fit on the screen in any orientation - just clip the menu to
// the screen and let the scrolling arrows appear.
menu_bounds.Intersect(monitor_bounds);
}
}
// Ensure the menu is not displayed off screen.
menu_bounds.set_x(std::clamp(menu_bounds.x(), monitor_bounds.x(),
monitor_bounds.right() - menu_bounds.width()));
menu_bounds.set_y(std::clamp(menu_bounds.y(), monitor_bounds.y(),
monitor_bounds.bottom() - menu_bounds.height()));
return menu_bounds;
}
gfx::Rect MenuController::CalculateBubbleMenuBounds(
MenuItemView* item,
bool prefer_leading,
bool* is_leading,
ui::OwnedWindowAnchor* anchor) {
DCHECK(item);
DCHECK(anchor);
const bool is_anchored_bubble = MenuItemView::IsBubble(state_.anchor);
// TODO(msisov): Shall we also calculate anchor for bubble menus, which are
// used by ash? If there is a need. Fix that.
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kTopLeft;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomRight;
anchor->constraint_adjustment =
ui::OwnedWindowConstraintAdjustment::kAdjustmentNone;
// Assume we can honor `prefer_leading`.
*is_leading = prefer_leading;
SubmenuView* submenu = item->GetSubmenu();
DCHECK(submenu);
gfx::Size menu_size = submenu->GetScrollViewContainer()->GetPreferredSize();
int x = 0;
int y = 0;
const MenuConfig& menu_config = MenuConfig::instance();
// Shadow insets are built into MenuScrollView's preferred size so it must be
// compensated for when determining the bounds of touchable menus.
BubbleBorder::Shadow shadow_type = BubbleBorder::STANDARD_SHADOW;
int elevation = menu_config.touchable_menu_shadow_elevation;
#if BUILDFLAG(IS_CHROMEOS_ASH)
if (use_ash_system_ui_layout_) {
shadow_type = BubbleBorder::CHROMEOS_SYSTEM_UI_SHADOW;
elevation = item->GetParentMenuItem()
? menu_config.touchable_submenu_shadow_elevation
: menu_config.touchable_menu_shadow_elevation;
}
#endif
const gfx::Insets border_and_shadow_insets =
BubbleBorder::GetBorderAndShadowInsets(elevation, shadow_type);
const gfx::Rect& monitor_bounds = state_.monitor_bounds;
const bool is_bubble_menu =
menu_config.use_bubble_border && menu_config.CornerRadiusForMenu(this);
if (!item->GetParentMenuItem()) {
// This is a top-level menu, position it relative to the anchor bounds.
const gfx::Rect& anchor_bounds = state_.initial_bounds;
using MenuPosition = MenuItemView::MenuPosition;
// First the size gets reduced to the possible space.
if (!monitor_bounds.IsEmpty()) {
int max_width = monitor_bounds.width();
int max_height = monitor_bounds.height();
// In case of bubbles, the maximum width is limited by the space
// between the display corner and the target area + the tip size.
if (is_anchored_bubble || is_bubble_menu ||
item->actual_menu_position() == MenuPosition::kAboveBounds) {
// Don't consider |border_and_shadow_insets| because when the max size
// is enforced, the scroll view is shown and the md shadows are not
// applied.
max_height =
std::max(anchor_bounds.y() - monitor_bounds.y(),
monitor_bounds.bottom() - anchor_bounds.bottom()) -
(is_bubble_menu ? 0 : menu_config.touchable_anchor_offset);
}
// The menu should always have a non-empty available area.
DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
menu_size.SetToMin(gfx::Size(max_width, max_height));
}
// Respect the delegate's maximum width.
menu_size.set_width(std::min(
menu_size.width(), item->GetDelegate()->GetMaxWidthForMenu(item)));
// Calculate possible coordinates. Do not clamp values; that happens later.
int x_menu_on_left = 0;
int x_menu_on_right = 0;
int y_menu_above = 0;
int y_menu_below = 0;
switch (state_.anchor) {
case MenuAnchorPosition::kBubbleTopLeft:
case MenuAnchorPosition::kBubbleTopRight:
case MenuAnchorPosition::kBubbleBottomLeft:
case MenuAnchorPosition::kBubbleBottomRight:
case MenuAnchorPosition::kTopLeft:
case MenuAnchorPosition::kTopRight:
case MenuAnchorPosition::kBottomCenter:
// Align the right edges of the menu and anchor.
x_menu_on_left = anchor_bounds.right() -
(state_.anchor == MenuAnchorPosition::kBottomCenter
? menu_size.width() / 2
: menu_size.width()) +
border_and_shadow_insets.right();
// Align the left edges of the menu and anchor.
x_menu_on_right = anchor_bounds.x() - border_and_shadow_insets.left();
// Align the bottom of the menu with the top of the anchor.
y_menu_above =
anchor_bounds.y() - menu_size.height() +
border_and_shadow_insets.bottom() -
(is_anchored_bubble ? menu_config.touchable_anchor_offset : 0);
// Align the top of the menu with the bottom of the anchor.
y_menu_below =
anchor_bounds.bottom() - border_and_shadow_insets.top() +
(is_anchored_bubble ? menu_config.touchable_anchor_offset : 0);
break;
case MenuAnchorPosition::kBubbleLeft:
case MenuAnchorPosition::kBubbleRight:
// Align the right edge of the menu with the left edge of the anchor.
x_menu_on_left = anchor_bounds.x() - menu_size.width() +
border_and_shadow_insets.right() -
menu_config.touchable_anchor_offset;
// Align the left edge of the menu with the right edge of the anchor.
x_menu_on_right = anchor_bounds.right() -
border_and_shadow_insets.left() +
menu_config.touchable_anchor_offset;
// Align the bottom of the menu with the bottom of the anchor.
y_menu_above = anchor_bounds.bottom() - menu_size.height() +
border_and_shadow_insets.bottom();
// Align the top of the menu with the top of the anchor.
y_menu_below = anchor_bounds.y() - border_and_shadow_insets.top();
break;
}
// Choose the most appropriate x coordinate.
switch (state_.anchor) {
case MenuAnchorPosition::kBubbleTopLeft:
case MenuAnchorPosition::kBubbleLeft:
case MenuAnchorPosition::kBubbleBottomLeft:
case MenuAnchorPosition::kTopRight:
case MenuAnchorPosition::kBottomCenter:
x = x_menu_on_left >= monitor_bounds.x() ? x_menu_on_left
: x_menu_on_right;
break;
case MenuAnchorPosition::kBubbleTopRight:
case MenuAnchorPosition::kBubbleRight:
case MenuAnchorPosition::kBubbleBottomRight:
case MenuAnchorPosition::kTopLeft:
x = x_menu_on_right + menu_size.width() <= monitor_bounds.right()
? x_menu_on_right
: x_menu_on_left;
break;
}
// Choose the most appropriate y coordinate.
const bool able_to_show_menu_below =
y_menu_below + menu_size.height() <= monitor_bounds.bottom();
const bool able_to_show_menu_above = y_menu_above >= monitor_bounds.y();
switch (state_.anchor) {
case MenuAnchorPosition::kBubbleLeft:
case MenuAnchorPosition::kBubbleRight:
case MenuAnchorPosition::kBubbleBottomLeft:
case MenuAnchorPosition::kBubbleBottomRight:
case MenuAnchorPosition::kTopLeft:
case MenuAnchorPosition::kTopRight:
case MenuAnchorPosition::kBottomCenter:
// Respect the actual menu position calculated earlier if possible, to
// prevent changing positions during menu size updates.
if (able_to_show_menu_below &&
(item->actual_menu_position() != MenuPosition::kAboveBounds ||
!able_to_show_menu_above)) {
y = y_menu_below;
item->set_actual_menu_position(MenuPosition::kBelowBounds);
} else if (able_to_show_menu_above) {
y = y_menu_above;
item->set_actual_menu_position(MenuPosition::kAboveBounds);
} else {
// No room above or below. Show the menu as low as possible.
y = monitor_bounds.bottom() - menu_size.height();
item->set_actual_menu_position(MenuPosition::kBestFit);
}
break;
case MenuAnchorPosition::kBubbleTopLeft:
case MenuAnchorPosition::kBubbleTopRight:
// Respect the actual menu position calculated earlier if possible, to
// prevent changing positions during menu size updates.
if (able_to_show_menu_above &&
(item->actual_menu_position() != MenuPosition::kBelowBounds ||
!able_to_show_menu_below)) {
y = y_menu_above;
item->set_actual_menu_position(MenuPosition::kAboveBounds);
} else if (able_to_show_menu_below) {
y = y_menu_below;
item->set_actual_menu_position(MenuPosition::kBelowBounds);
} else {
// No room above or below. Show the menu as high as possible.
y = monitor_bounds.y();
item->set_actual_menu_position(MenuPosition::kBestFit);
}
break;
}
// The above adjustments may have shifted a large menu off the screen.
// Clamp the menu origin to the valid range.
const int x_min = monitor_bounds.x() - border_and_shadow_insets.left();
const int x_max = monitor_bounds.right() - menu_size.width() +
border_and_shadow_insets.right();
const int y_min = monitor_bounds.y() - border_and_shadow_insets.top();
const int y_max = monitor_bounds.bottom() - menu_size.height() +
border_and_shadow_insets.bottom();
DCHECK_LE(x_min, x_max);
DCHECK_LE(y_min, y_max);
x = std::clamp(x, x_min, x_max);
y = std::clamp(y, y_min, y_max);
} else {
// This is a sub-menu, position it relative to the parent menu.
const gfx::Rect item_bounds = item->GetBoundsInScreen();
// If the layout is RTL, then a 'leading' menu is positioned to the left of
// the parent menu item and not to the right.
const bool layout_is_rtl = base::i18n::IsRTL();
const bool create_on_right = prefer_leading != layout_is_rtl;
// Don't let the menu get too wide if bubble menus are on.
if (is_bubble_menu) {
menu_size.set_width(std::min(
menu_size.width(), item->GetDelegate()->GetMaxWidthForMenu(item)));
}
const int width_with_right_inset =
is_bubble_menu ? (menu_size.width() - border_and_shadow_insets.right())
: (menu_config.touchable_menu_min_width +
border_and_shadow_insets.right());
const int x_max = monitor_bounds.right() - width_with_right_inset;
const int x_left = item_bounds.x() - width_with_right_inset;
const int x_right = item_bounds.right() - border_and_shadow_insets.left();
if (create_on_right) {
x = x_right;
if (monitor_bounds.width() == 0 || x_right <= x_max) {
// Enough room on the right, show normally.
x = x_right;
} else if (x_left >= monitor_bounds.x()) {
// Enough room on the left, show there.
*is_leading = prefer_leading;
x = x_left;
} else {
// No room on either side. Flush the menu to the right edge.
x = x_max;
}
} else {
if (monitor_bounds.width() == 0 || x_left >= monitor_bounds.x()) {
// Enough room on the left, show normally.
x = x_left;
} else if (x_right <= x_max) {
// Enough room on the right, show there.
*is_leading = !prefer_leading;
x = x_right;
} else {
// No room on either side. Flush the menu to the left edge.
x = monitor_bounds.x();
}
}
// Make sure the menu doesn't exceed the monitor bounds while cancelling
// out the border and shadow at the top and bottom.
menu_size.set_height(
std::min(menu_size.height(),
monitor_bounds.height() + border_and_shadow_insets.height()));
y = item_bounds.y() - border_and_shadow_insets.top() -
(is_bubble_menu ? 0 : menu_config.vertical_touchable_menu_item_padding);
auto y_min = monitor_bounds.y() - border_and_shadow_insets.top();
auto y_max = is_bubble_menu ? monitor_bounds.bottom() +
border_and_shadow_insets.bottom() -
menu_size.height()
: monitor_bounds.bottom() - menu_size.height() +
border_and_shadow_insets.top();
y = std::clamp(y, y_min, y_max);
}
auto menu_bounds = gfx::Rect(x, y, menu_size.width(), menu_size.height());
// TODO(msisov): Shall we also calculate anchor for bubble menus, which are
// used by ash? If there is a need. Fix that.
anchor->anchor_rect = menu_bounds;
anchor->anchor_rect.set_size({1, 1});
return menu_bounds;
}
// static
size_t MenuController::MenuDepth(MenuItemView* item) {
return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : size_t{0};
}
void MenuController::IncrementSelection(
SelectionIncrementDirectionType direction) {
MenuItemView* item = pending_state_.item;
DCHECK(item);
if (pending_state_.submenu_open && item->SubmenuIsShowing()) {
// A menu is selected and open, but none of its children are selected,
// select the first menu item that is visible and enabled.
if (!item->GetSubmenu()->GetMenuItems().empty()) {
MenuItemView* to_select = FindInitialSelectableMenuItem(item, direction);
SetInitialHotTrackedView(to_select, direction);
return;
}
}
if (!item->children().empty()) {
Button* button = GetFirstHotTrackedView(item);
if (button) {
DCHECK_EQ(hot_button_, button);
SetHotTrackedButton(nullptr);
}
bool direction_is_down = direction == INCREMENT_SELECTION_DOWN;
View* to_make_hot =
button ? GetNextFocusableView(item, button, direction_is_down)
: GetInitialFocusableView(item, direction_is_down);
Button* hot_button = Button::AsButton(to_make_hot);
if (hot_button) {
SetHotTrackedButton(hot_button);
return;
}
}
SetNextHotTrackedView(item, direction);
}
void MenuController::SetSelectionIndices(MenuItemView* parent) {
if (parent->GetProperty(kOrderedMenuChildren)) {
// Clear any old AX index assignments.
for (ViewTracker& item : *(parent->GetProperty(kOrderedMenuChildren))) {
if (item.view())
item.view()->GetViewAccessibility().ClearPosInSetOverride();
}
}
std::vector<View*> ordering;
SubmenuView* const submenu = parent->GetSubmenu();
for (MenuItemView* item : submenu->GetMenuItems()) {
if (!item->IsTraversableByKeyboard())
continue;
bool found_focusable = false;
if (!item->children().empty()) {
for (View* child = GetInitialFocusableView(item, true); child;
child = GetNextFocusableView(item, child, true)) {
ordering.push_back(child);
found_focusable = true;
}
}
if (!found_focusable)
ordering.push_back(item);
}
parent->SetProperty(kOrderedMenuChildren,
std::make_unique<std::vector<ViewTracker>>(
ordering.begin(), ordering.end()));
if (ordering.empty())
return;
const size_t set_size = ordering.size();
for (size_t i = 0; i < set_size; ++i) {
ordering[i]->GetViewAccessibility().OverridePosInSet(
static_cast<int>(i + 1), static_cast<int>(set_size));
}
}
void MenuController::MoveSelectionToFirstOrLastItem(
SelectionIncrementDirectionType direction) {
MenuItemView* item = pending_state_.item;
DCHECK(item);
MenuItemView* submenu = nullptr;
if (pending_state_.submenu_open && item->SubmenuIsShowing()) {
if (item->GetSubmenu()->GetMenuItems().empty())
return;
// A menu is selected and open, but none of its children are selected,
// select the first or last menu item that is visible and enabled.
submenu = item;
} else {
submenu = item->GetParentMenuItem();
}
MenuItemView* to_select = FindInitialSelectableMenuItem(submenu, direction);
SetInitialHotTrackedView(to_select, direction);
}
MenuItemView* MenuController::FindInitialSelectableMenuItem(
MenuItemView* parent,
SelectionIncrementDirectionType direction) {
const size_t parent_count = parent->GetSubmenu()->GetMenuItems().size();
if (direction == INCREMENT_SELECTION_DOWN) {
for (size_t index = 0; index < parent_count; ++index) {
MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
if (child->IsTraversableByKeyboard())
return child;
}
} else {
for (size_t index = parent_count; index > 0; --index) {
MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index - 1);
if (child->IsTraversableByKeyboard())
return child;
}
}
return nullptr;
}
void MenuController::OpenSubmenuChangeSelectionIfCan() {
MenuItemView* item = pending_state_.item;
if (!item->HasSubmenu() || !item->GetEnabled() || !item->GetParentMenuItem()) {
MenuItemView* submenu_item =
item->GetParentMenuItem() ? item->GetParentMenuItem() : item;
submenu_item->GetDelegate()->OnUnhandledOpenSubmenu(submenu_item,
base::i18n::IsRTL());
return;
}
// Show the sub-menu.
SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
MenuItemView* to_select = nullptr;
if (!item->GetSubmenu()->GetMenuItems().empty())
to_select = FindInitialSelectableMenuItem(item, INCREMENT_SELECTION_DOWN);
if (to_select) {
// Selection is going from the ACTIONABLE to the SUBMENU region of the
// ACTIONABLE_SUBMENU, so highlight the SUBMENU area.
if (item->type_ == MenuItemView::Type::kActionableSubMenu)
item->SetSelectionOfActionableSubmenu(true);
SetSelection(to_select, SELECTION_UPDATE_IMMEDIATELY);
}
}
void MenuController::CloseSubmenu() {
MenuItemView* item = state_.item;
DCHECK(item);
if (!item->GetParentMenuItem()) {
item->GetDelegate()->OnUnhandledCloseSubmenu(item, base::i18n::IsRTL());
return;
}
if (item->SubmenuIsShowing())
SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
else if (item->GetParentMenuItem()->GetParentMenuItem())
SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
}
MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
MenuItemView* parent,
char16_t key,
bool (*match_function)(MenuItemView* menu, char16_t mnemonic)) {
SubmenuView* submenu = parent->GetSubmenu();
DCHECK(submenu);
SelectByCharDetails details;
const auto menu_items = submenu->GetMenuItems();
for (size_t i = 0; i < menu_items.size(); ++i) {
MenuItemView* child = menu_items[i];
if (child->GetEnabled() && child->GetVisible()) {
if (child == pending_state_.item)
details.index_of_item = i;
if (match_function(child, key)) {
if (!details.first_match.has_value()) {
details.first_match = i;
} else {
details.has_multiple = true;
}
if (!details.next_match.has_value() &&
details.index_of_item.has_value() && i > details.index_of_item)
details.next_match = i;
}
}
}
return details;
}
void MenuController::AcceptOrSelect(MenuItemView* parent,
const SelectByCharDetails& details) {
// This should only be invoked if there is a match.
DCHECK(details.first_match.has_value());
DCHECK(parent->HasSubmenu());
SubmenuView* submenu = parent->GetSubmenu();
DCHECK(submenu);
if (!details.has_multiple) {
// There's only one match, activate it (or open if it has a submenu).
if (submenu->GetMenuItemAt(details.first_match.value())->HasSubmenu()) {
SetSelection(submenu->GetMenuItemAt(details.first_match.value()),
SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
} else {
Accept(submenu->GetMenuItemAt(details.first_match.value()), 0);
}
} else if (!details.index_of_item.has_value() ||
!details.next_match.has_value()) {
SetSelection(submenu->GetMenuItemAt(details.first_match.value()),
SELECTION_DEFAULT);
} else {
SetSelection(submenu->GetMenuItemAt(details.next_match.value()),
SELECTION_DEFAULT);
}
}
void MenuController::SelectByChar(char16_t character) {
// Do not process while performing drag-and-drop.
if (for_drop_)
return;
if (!character)
return;
char16_t char_array[] = {character, 0};
char16_t key = base::i18n::ToLower(char_array)[0];
MenuItemView* item = pending_state_.item;
if (!item->SubmenuIsShowing())
item = item->GetParentMenuItem();
DCHECK(item);
DCHECK(item->HasSubmenu());
DCHECK(item->GetSubmenu());
if (item->GetSubmenu()->GetMenuItems().empty())
return;
// Look for matches based on mnemonic first.
SelectByCharDetails details =
FindChildForMnemonic(item, key, &MatchesMnemonic);
if (details.first_match.has_value()) {
AcceptOrSelect(item, details);
return;
}
if (IsReadonlyCombobox() ||
MenuConfig::instance().all_menus_use_prefix_selection) {
item->GetSubmenu()->GetPrefixSelector()->InsertText(
char_array,
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
} else {
// If no mnemonics found, look at first character of titles.
details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
if (details.first_match.has_value())
AcceptOrSelect(item, details);
}
}
void MenuController::RepostEventAndCancel(SubmenuView* source,
const ui::LocatedEvent* event) {
gfx::Point screen_loc(event->location());
View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
#if BUILDFLAG(IS_WIN)
if (event->IsMouseEvent() || event->IsTouchEvent()) {
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
if (state_.item) {
// This must be done before we ReleaseCapture() below, which can lead to
// deleting the `source`.
gfx::NativeView native_view = source->GetWidget()->GetNativeView();
gfx::NativeWindow window =
native_view
? display::Screen::GetScreen()->GetWindowAtScreenPoint(screen_loc)
: nullptr;
state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
// We're going to close and we own the event capture. We need to repost
// the event, otherwise the window the user clicked on won't get the
// event.
RepostEventImpl(event, screen_loc, native_view, window);
} else {
// We some times get an event after closing all the menus. Ignore it. Make
// sure the menu is in fact not visible. If the menu is visible, then
// we're in a bad state where we think the menu isn't visible but it is.
DCHECK(!source->GetWidget()->IsVisible());
}
// Reposting the event may have deleted this, if so exit.
if (!this_ref)
return;
}
#endif
// Determine target to see if a complete or partial close of the menu should
// occur.
ExitType exit_type = ExitType::kAll;
if (!menu_stack_.empty()) {
// We're running nested menus. Only exit all if the mouse wasn't over one
// of the menus from the last run.
MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
menu_stack_.back().first.item, screen_loc);
if (last_part.type != MenuPart::Type::kNone)
exit_type = ExitType::kOutermost;
}
#if BUILDFLAG(IS_MAC)
// When doing a menu closure animation, target the deepest submenu - that way
// MenuClosureAnimationMac will fade out all the menus in sync, rather than
// the shallowest menu only.
menu_closure_animation_ = std::make_unique<MenuClosureAnimationMac>(
nullptr, state_.item->GetSubmenu(),
base::BindOnce(&MenuController::Cancel, base::Unretained(this),
exit_type));
menu_closure_animation_->Start();
#else
Cancel(exit_type);
#endif
}
void MenuController::SetDropMenuItem(MenuItemView* new_target,
MenuDelegate::DropPosition new_position) {
if (new_target == drop_target_ && new_position == drop_position_)
return;
if (drop_target_) {
drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
nullptr, MenuDelegate::DropPosition::kNone);
}
drop_target_ = new_target;
drop_position_ = new_position;
if (drop_target_) {
drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
drop_target_, drop_position_);
}
}
void MenuController::UpdateScrolling(const MenuPart& part) {
if (!part.is_scroll() && !scroll_task_.get()) {
return;
}
if (!scroll_task_.get())
scroll_task_ = std::make_unique<MenuScrollTask>();
scroll_task_->Update(part);
}
void MenuController::StopScrolling() {
scroll_task_.reset(nullptr);
}
void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
const ui::MouseEvent& event,
View* target_menu) {
View* target = nullptr;
gfx::Point target_menu_loc(event.location());
if (target_menu && !target_menu->children().empty()) {
// Locate the deepest child view to send events to. This code assumes we
// don't have to walk up the tree to find a view interested in events. This
// is currently true for the cases we are embedding views, but if we embed
// more complex hierarchies it'll need to change.
View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
&target_menu_loc);
View::ConvertPointFromScreen(target_menu, &target_menu_loc);
target = target_menu->GetEventHandlerForPoint(target_menu_loc);
if (target == target_menu || !target->GetEnabled())
target = nullptr;
}
View* active_mouse_view = active_mouse_view_tracker_->view();
if (target != active_mouse_view) {
SendMouseCaptureLostToActiveView();
active_mouse_view = target;
active_mouse_view_tracker_->SetView(active_mouse_view);
if (active_mouse_view) {
gfx::Point target_point(target_menu_loc);
View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED, target_point,
target_point, ui::EventTimeForNow(), 0,
0);
active_mouse_view->OnMouseEntered(mouse_entered_event);
ui::MouseEvent mouse_pressed_event(
ui::ET_MOUSE_PRESSED, target_point, target_point,
ui::EventTimeForNow(), event.flags(), event.changed_button_flags());
active_mouse_view->OnMousePressed(mouse_pressed_event);
}
}
if (active_mouse_view) {
gfx::Point target_point(target_menu_loc);
View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
ui::MouseEvent mouse_dragged_event(
ui::ET_MOUSE_DRAGGED, target_point, target_point, ui::EventTimeForNow(),
event.flags(), event.changed_button_flags());
active_mouse_view->OnMouseDragged(mouse_dragged_event);
}
}
void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
const ui::MouseEvent& event) {
View* active_mouse_view = active_mouse_view_tracker_->view();
if (!active_mouse_view)
return;
gfx::Point target_loc(event.location());
View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
&target_loc);
View::ConvertPointFromScreen(active_mouse_view, &target_loc);
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
ui::EventTimeForNow(), event.flags(),
event.changed_button_flags());
// Reset the active mouse view before sending mouse released. That way if it
// calls back to us, we aren't in a weird state.
active_mouse_view_tracker_->SetView(nullptr);
active_mouse_view->OnMouseReleased(release_event);
}
void MenuController::SendMouseCaptureLostToActiveView() {
View* active_mouse_view = active_mouse_view_tracker_->view();
if (!active_mouse_view)
return;
// Reset the active mouse view before sending mouse capture lost. That way if
// it calls back to us, we aren't in a weird state.
active_mouse_view_tracker_->SetView(nullptr);
active_mouse_view->OnMouseCaptureLost();
}
void MenuController::SetExitType(ExitType type) {
exit_type_ = type;
}
void MenuController::ExitMenu() {
bool nested = delegate_stack_.size() > 1;
// ExitTopMostMenu unwinds nested delegates
internal::MenuControllerDelegate* delegate = delegate_;
int accept_event_flags = accept_event_flags_;
base::WeakPtr<MenuController> this_ref = AsWeakPtr();
MenuItemView* result = ExitTopMostMenu();
delegate->OnMenuClosed(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
result, accept_event_flags);
// |delegate| may have deleted this.
if (this_ref && nested && exit_type_ == ExitType::kAll)
ExitMenu();
}
MenuItemView* MenuController::ExitTopMostMenu() {
// Release the lock which prevents Chrome from shutting down while the menu is
// showing.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&ViewsDelegate::ReleaseRef,
base::Unretained(ViewsDelegate::GetInstance())));
// Close any open menus.
SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
#if BUILDFLAG(IS_WIN)
// On Windows, if we select the menu item by touch and if the window at the
// location is another window on the same thread, that window gets a
// WM_MOUSEACTIVATE message and ends up activating itself, which is not
// correct. We workaround this by setting a property on the window at the
// current cursor location. We check for this property in our
// WM_MOUSEACTIVATE handler and don't activate the window if the property is
// set.
if (item_selected_by_touch_) {
item_selected_by_touch_ = false;
POINT cursor_pos;
::GetCursorPos(&cursor_pos);
HWND window = ::WindowFromPoint(cursor_pos);
if (::GetWindowThreadProcessId(window, nullptr) == ::GetCurrentThreadId()) {
::SetProp(window, ui::kIgnoreTouchMouseActivateForWindow,
reinterpret_cast<HANDLE>(true));
}
}
#endif
std::unique_ptr<MenuButtonController::PressedLock> nested_pressed_lock;
bool nested_menu = !menu_stack_.empty();
if (nested_menu) {
DCHECK(!menu_stack_.empty());
// We're running from within a menu, restore the previous state.
// The menus are already showing, so we don't have to show them.
state_ = menu_stack_.back().first;
pending_state_ = menu_stack_.back().first;
hot_button_ = state_.hot_button;
nested_pressed_lock = std::move(menu_stack_.back().second);
menu_stack_.pop_back();
// Even though the menus are nested, there may not be nested delegates.
if (delegate_stack_.size() > 1) {
delegate_stack_.pop_back();
delegate_ = delegate_stack_.back();
}
} else {
#if defined(USE_AURA)
menu_pre_target_handler_.reset();
#endif
showing_ = false;
did_capture_ = false;
}
MenuItemView* result = result_;
// In case we're nested, reset |result_|.
result_ = nullptr;
if (exit_type_ == ExitType::kOutermost) {
SetExitType(ExitType::kNone);
} else if (nested_menu && result) {
// We're nested and about to return a value. The caller might enter
// another blocking loop. We need to make sure all menus are hidden
// before that happens otherwise the menus will stay on screen.
CloseAllNestedMenus();
SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
// Set exit_all_, which makes sure all nested loops exit immediately.
if (exit_type_ != ExitType::kDestroyed)
SetExitType(ExitType::kAll);
}
// Reset our pressed lock and hot-tracked state to the previous state's, if
// they were active. The lock handles the case if the button was destroyed.
pressed_lock_ = std::move(nested_pressed_lock);
if (hot_button_)
hot_button_->SetHotTracked(true);
return result;
}
void MenuController::HandleMouseLocation(SubmenuView* source,
const gfx::Point& mouse_location) {
if (showing_submenu_)
return;
// Ignore mouse events if we're closing the menu.
if (exit_type_ != ExitType::kNone)
return;
MenuPart part = GetMenuPart(source, mouse_location);
UpdateScrolling(part);
if (for_drop_)
return;
if (part.type == MenuPart::Type::kNone &&
ShowSiblingMenu(source, mouse_location))
return;
if (part.type == MenuPart::Type::kMenuItem && part.menu) {
SetSelection(part.menu, part.should_submenu_show ? SELECTION_OPEN_SUBMENU
: SELECTION_DEFAULT);
} else if (!part.is_scroll() && pending_state_.item &&
pending_state_.item->GetParentMenuItem() &&
!pending_state_.item->SubmenuIsShowing()) {
// On exit if the user hasn't selected an item with a submenu, move the
// selection back to the parent menu item.
SetSelection(pending_state_.item->GetParentMenuItem(),
SELECTION_OPEN_SUBMENU);
}
}
void MenuController::SetInitialHotTrackedView(
MenuItemView* item,
SelectionIncrementDirectionType direction) {
if (!item)
return;
SetSelection(item, SELECTION_DEFAULT);
View* hot_view =
GetInitialFocusableView(item, direction == INCREMENT_SELECTION_DOWN);
SetHotTrackedButton(Button::AsButton(hot_view));
}
void MenuController::SetNextHotTrackedView(
MenuItemView* item,
SelectionIncrementDirectionType direction) {
MenuItemView* parent = item->GetParentMenuItem();
if (!parent)
return;
const auto menu_items = parent->GetSubmenu()->GetMenuItems();
const size_t num_menu_items = menu_items.size();
if (num_menu_items <= 1)
return;
const auto i = base::ranges::find(menu_items, item);
DCHECK(i != menu_items.cend());
auto index = static_cast<size_t>(std::distance(menu_items.cbegin(), i));
// Loop through the menu items in the desired direction. Assume we can wrap
// all the way back to this item.
size_t stop_index = index;
if (!MenuConfig::instance().arrow_key_selection_wraps) {
// Don't want to allow wrapping, so stop as soon as it happens.
stop_index = direction == INCREMENT_SELECTION_UP ? (num_menu_items - 1) : 0;
}
const size_t delta =
direction == INCREMENT_SELECTION_UP ? (num_menu_items - 1) : 1;
while (true) {
index = (index + delta) % num_menu_items;
if (index == stop_index)
return;
// Stop on the next keyboard-traversable item.
MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
if (child->IsTraversableByKeyboard()) {
SetInitialHotTrackedView(child, direction);
return;
}
}
}
void MenuController::SetHotTrackedButton(Button* new_hot_button) {
// Set hot tracked state and fire a11y events for the hot tracked button.
// This must be done whether or not it was the previous hot tracked button.
// For example, when a zoom button is pressed, the menu remains open and the
// same zoom button should have its hot tracked state set again.
// If we're providing a new hot-tracked button, first remove the existing one.
if (hot_button_ && hot_button_ != new_hot_button) {
hot_button_->SetHotTracked(false);
hot_button_->GetViewAccessibility().EndPopupFocusOverride();
}
// Then set the new one.
hot_button_ = new_hot_button;
if (hot_button_) {
hot_button_->GetViewAccessibility().SetPopupFocusOverride();
hot_button_->SetHotTracked(true);
hot_button_->NotifyAccessibilityEvent(ax::mojom::Event::kSelection, true);
}
}
bool MenuController::ShouldContinuePrefixSelection() const {
MenuItemView* item = pending_state_.item;
if (!item->SubmenuIsShowing())
item = item->GetParentMenuItem();
return item->GetSubmenu()->GetPrefixSelector()->ShouldContinueSelection();
}
void MenuController::RegisterAlertedItem(MenuItemView* item) {
alerted_items_.insert(item);
// Start animation if necessary. We stop the animation once no alerted
// items are showing.
if (!alert_animation_.is_animating()) {
alert_animation_.SetThrobDuration(kAlertAnimationThrobDuration);
alert_animation_.StartThrobbing(-1);
}
}
void MenuController::UnregisterAlertedItem(MenuItemView* item) {
alerted_items_.erase(item);
// Stop animation if necessary.
if (alerted_items_.empty())
alert_animation_.Stop();
}
void MenuController::SetAnchorParametersForItem(MenuItemView* item,
const gfx::Point& item_loc,
ui::OwnedWindowAnchor* anchor) {
if (item->GetParentMenuItem()) {
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kTopRight;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomRight;
// If the parent item has been repositioned to the left of its parent
// item. The next items must also be positioned on the left of its parent.
// Otherwise, there will be a chain of menus that will be positioned as to
// the right, to the left, to the right, to the left, etc. The direction
// must be maintained.
if (item->GetParentMenuItem()->GetParentMenuItem()) {
gfx::Point parent_of_parent_item_loc;
View::ConvertPointToScreen(item->GetParentMenuItem(),
&parent_of_parent_item_loc);
if (parent_of_parent_item_loc.x() > item_loc.x()) {
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kTopLeft;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomLeft;
}
}
anchor->constraint_adjustment =
ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY;
} else {
if (state_.context_menu) {
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kBottomLeft;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomRight;
anchor->constraint_adjustment =
ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY;
} else {
anchor->constraint_adjustment =
ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY;
if (state_.anchor == MenuAnchorPosition::kTopRight) {
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kBottomRight;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomLeft;
} else {
anchor->anchor_position = ui::OwnedWindowAnchorPosition::kBottomLeft;
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomRight;
}
}
}
}
bool MenuController::CanProcessInputEvents() const {
#if BUILDFLAG(IS_MAC)
return !menu_closure_animation_;
#else
return true;
#endif
}
void MenuController::SetMenuRoundedCorners(
absl::optional<gfx::RoundedCornersF> corners) {
rounded_corners_ = corners;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller.cc | C++ | unknown | 132,288 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_
#include <stddef.h>
#include <list>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/containers/flat_set.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/platform/platform_event_dispatcher.h"
#include "ui/gfx/animation/throb_animation.h"
#include "ui/views/controls/button/menu_button_controller.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/widget/widget_observer.h"
#if BUILDFLAG(IS_MAC)
#include "ui/views/controls/menu/menu_closure_animation_mac.h"
#include "ui/views/controls/menu/menu_cocoa_watcher_mac.h"
#endif
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace ui {
class OSExchangeData;
struct OwnedWindowAnchor;
} // namespace ui
namespace views {
class Button;
class MenuHostRootView;
class MenuItemView;
class MenuPreTargetHandler;
class MouseEvent;
class SubmenuView;
class View;
class ViewTracker;
namespace internal {
class MenuControllerDelegate;
class MenuRunnerImpl;
} // namespace internal
namespace test {
class MenuControllerTest;
class MenuControllerTestApi;
class MenuControllerUITest;
} // namespace test
// MenuController -------------------------------------------------------------
// MenuController is used internally by the various menu classes to manage
// showing, selecting and drag/drop for menus. All relevant events are
// forwarded to the MenuController from SubmenuView and MenuHost.
class VIEWS_EXPORT MenuController
: public base::SupportsWeakPtr<MenuController>,
public gfx::AnimationDelegate,
public WidgetObserver {
public:
// Enumeration of how the menu should exit.
enum class ExitType {
// Don't exit.
kNone,
// All menus, including nested, should be exited.
kAll,
// Only the outermost menu should be exited.
kOutermost,
// the menu is being closed as the result of one of the menus being
// destroyed.
kDestroyed
};
// Types of comboboxes.
enum class ComboboxType {
kNone,
kEditable,
kReadonly,
};
// If a menu is currently active, this returns the controller for it.
static MenuController* GetActiveInstance();
MenuController(const MenuController&) = delete;
MenuController& operator=(const MenuController&) = delete;
// Runs the menu at the specified location.
void Run(Widget* parent,
MenuButtonController* button_controller,
MenuItemView* root,
const gfx::Rect& bounds,
MenuAnchorPosition position,
bool context_menu,
bool is_nested_drag,
gfx::NativeView native_view_for_gestures = nullptr,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget);
bool for_drop() const { return for_drop_; }
bool in_nested_run() const { return !menu_stack_.empty(); }
// Whether or not drag operation is in progress.
bool drag_in_progress() const { return drag_in_progress_; }
// Whether the MenuController initiated the drag in progress. False if there
// is no drag in progress.
bool did_initiate_drag() const { return did_initiate_drag_; }
bool send_gesture_events_to_owner() const {
return send_gesture_events_to_owner_;
}
void set_send_gesture_events_to_owner(bool send_gesture_events_to_owner) {
send_gesture_events_to_owner_ = send_gesture_events_to_owner;
}
// Returns the owner of child windows.
// WARNING: this may be NULL.
Widget* owner() { return owner_; }
// Gets the most-current selected menu item, if any, including if the
// selection has not been committed yet.
views::MenuItemView* GetSelectedMenuItem() { return pending_state_.item; }
// Selects a menu-item and opens its sub-menu (if one exists) if not already
// so. Clears any selections within the submenu if it is already open.
void SelectItemAndOpenSubmenu(MenuItemView* item);
// Gets the anchor position which is used to show this menu.
MenuAnchorPosition GetAnchorPosition() { return state_.anchor; }
// Cancels the current Run. See ExitType for a description of what happens
// with the various parameters.
void Cancel(ExitType type);
// When is_nested_run() this will add a delegate to the stack. The most recent
// delegate will be notified. It will be removed upon the exiting of the
// nested menu. Ownership is not taken.
void AddNestedDelegate(internal::MenuControllerDelegate* delegate);
// Returns the current exit type. This returns a value other than
// ExitType::kNone if the menu is being canceled.
ExitType exit_type() const { return exit_type_; }
// Returns the time from the event which closed the menu - or 0.
base::TimeTicks closing_event_time() const { return closing_event_time_; }
// Set/Get combobox type.
void set_combobox_type(ComboboxType combobox_type) {
combobox_type_ = combobox_type;
}
bool IsCombobox() const;
bool IsEditableCombobox() const;
bool IsReadonlyCombobox() const;
bool IsContextMenu() const;
// Various events, forwarded from the submenu.
//
// NOTE: the coordinates of the events are in that of the
// MenuScrollViewContainer.
bool OnMousePressed(SubmenuView* source, const ui::MouseEvent& event);
bool OnMouseDragged(SubmenuView* source, const ui::MouseEvent& event);
void OnMouseReleased(SubmenuView* source, const ui::MouseEvent& event);
void OnMouseMoved(SubmenuView* source, const ui::MouseEvent& event);
void OnMouseEntered(SubmenuView* source, const ui::MouseEvent& event);
bool OnMouseWheel(SubmenuView* source, const ui::MouseWheelEvent& event);
void OnGestureEvent(SubmenuView* source, ui::GestureEvent* event);
void OnTouchEvent(SubmenuView* source, ui::TouchEvent* event);
View* GetTooltipHandlerForPoint(SubmenuView* source, const gfx::Point& point);
void ViewHierarchyChanged(SubmenuView* source,
const ViewHierarchyChangedDetails& details);
bool GetDropFormats(SubmenuView* source,
int* formats,
std::set<ui::ClipboardFormatType>* format_types);
bool AreDropTypesRequired(SubmenuView* source);
bool CanDrop(SubmenuView* source, const ui::OSExchangeData& data);
void OnDragEntered(SubmenuView* source, const ui::DropTargetEvent& event);
int OnDragUpdated(SubmenuView* source, const ui::DropTargetEvent& event);
void OnDragExited(SubmenuView* source);
views::View::DropCallback GetDropCallback(SubmenuView* source,
const ui::DropTargetEvent& event);
// Invoked from the scroll buttons of the MenuScrollViewContainer.
void OnDragEnteredScrollButton(SubmenuView* source, bool is_up);
void OnDragExitedScrollButton(SubmenuView* source);
// Called by the MenuHost when a drag is about to start on a child view.
// This could be initiated by one of our MenuItemViews, or could be through
// another child View.
void OnDragWillStart();
// Called by the MenuHost when the drag has completed. |should_close|
// corresponds to whether or not the menu should close.
void OnDragComplete(bool should_close);
// Called while dispatching messages to intercept key events.
// Returns ui::POST_DISPATCH_NONE if the event was swallowed by the menu.
ui::PostDispatchAction OnWillDispatchKeyEvent(ui::KeyEvent* event);
// Update the submenu's selection based on the current mouse location
void UpdateSubmenuSelection(SubmenuView* source);
// WidgetObserver overrides:
void OnWidgetDestroying(Widget* widget) override;
// Only used for testing.
bool IsCancelAllTimerRunningForTest();
// Only used for testing. Clears |state_| and |pending_state_| without
// notifying any menu items.
void ClearStateForTest();
// Only used for testing.
static void TurnOffMenuSelectionHoldForTest();
void set_use_ash_system_ui_layout(bool value) {
use_ash_system_ui_layout_ = value;
}
bool use_ash_system_ui_layout() const { return use_ash_system_ui_layout_; }
// The rounded corners of the context menu.
absl::optional<gfx::RoundedCornersF> rounded_corners() const {
return rounded_corners_;
}
// Notifies |this| that |menu_item| is being destroyed.
void OnMenuItemDestroying(MenuItemView* menu_item);
// Returns whether this menu can handle input events right now. This method
// can return false while running animations.
bool CanProcessInputEvents() const;
// Gets the animation used for menu item alerts. The returned pointer lives as
// long as the MenuController.
const gfx::Animation* GetAlertAnimation() const { return &alert_animation_; }
// gfx::AnimationDelegate:
void AnimationProgressed(const gfx::Animation* animation) override;
// Sets the customized rounded corners of the context menu.
void SetMenuRoundedCorners(absl::optional<gfx::RoundedCornersF> corners);
private:
friend class internal::MenuRunnerImpl;
friend class test::MenuControllerTest;
friend class test::MenuControllerTestApi;
friend class test::MenuControllerUITest;
friend class MenuHostRootView;
friend class MenuItemView;
friend class SubmenuView;
class MenuScrollTask;
struct SelectByCharDetails;
// Values supplied to SetSelection.
enum SetSelectionTypes {
SELECTION_DEFAULT = 0,
// If set submenus are opened immediately, otherwise submenus are only
// opened after a timer fires.
SELECTION_UPDATE_IMMEDIATELY = 1 << 0,
// If set and the menu_item has a submenu, the submenu is shown.
SELECTION_OPEN_SUBMENU = 1 << 1,
// SetSelection is being invoked as the result exiting or cancelling the
// menu. This is used for debugging.
SELECTION_EXIT = 1 << 2,
};
// Direction for IncrementSelection and FindInitialSelectableMenuItem.
enum SelectionIncrementDirectionType {
// Navigate the menu up.
INCREMENT_SELECTION_UP,
// Navigate the menu down.
INCREMENT_SELECTION_DOWN,
};
// Tracks selection information.
struct State {
State();
State(const State& other);
~State();
// The selected menu item.
raw_ptr<MenuItemView> item = nullptr;
// Used to capture a hot tracked child button when a nested menu is opened
// and to restore the hot tracked state when exiting a nested menu.
raw_ptr<Button> hot_button = nullptr;
// If item has a submenu this indicates if the submenu is showing.
bool submenu_open = false;
// Bounds passed to the run menu. Used for positioning the first menu.
gfx::Rect initial_bounds;
// Position of the initial menu.
MenuAnchorPosition anchor = MenuAnchorPosition::kTopLeft;
// The direction child menus have opened in.
std::list<bool> open_leading;
// Bounds for the monitor we're showing on.
gfx::Rect monitor_bounds;
// Is the current menu a context menu.
bool context_menu = false;
};
// Used by GetMenuPart to indicate the menu part at a particular location.
struct MenuPart {
// Type of part.
enum class Type { kNone, kMenuItem, kScrollUp, kScrollDown };
// Convenience for testing type == kScrollDown or type == kScrollUp.
bool is_scroll() const {
return type == Type::kScrollDown || type == Type::kScrollUp;
}
// Type of part.
Type type = Type::kNone;
// If type is kMenuItem, this is the menu item the mouse is over, otherwise
// this is null.
// NOTE: if type is kMenuItem and the mouse is not over a valid menu item
// but is over a menu (for example, the mouse is over a separator or
// empty menu), this is null and parent is the menu the mouse was
// clicked on.
raw_ptr<MenuItemView, DanglingUntriaged> menu = nullptr;
// If type is kMenuItem but the mouse is not over a menu item this is the
// parent of the menu item the user clicked on. Otherwise this is null.
raw_ptr<MenuItemView, DanglingUntriaged> parent = nullptr;
// This is the submenu the mouse is over.
raw_ptr<SubmenuView, DanglingUntriaged> submenu = nullptr;
// Whether the controller should apply SELECTION_OPEN_SUBMENU to this item.
bool should_submenu_show = false;
};
// Sets the selection to |menu_item|. A value of NULL unselects
// everything. |types| is a bitmask of |SetSelectionTypes|.
//
// Internally this updates pending_state_ immediately. state_ is only updated
// immediately if SELECTION_UPDATE_IMMEDIATELY is set. If
// SELECTION_UPDATE_IMMEDIATELY is not set CommitPendingSelection is invoked
// to show/hide submenus and update state_.
void SetSelection(MenuItemView* menu_item, int types);
void SetSelectionOnPointerDown(SubmenuView* source,
const ui::LocatedEvent* event);
void StartDrag(SubmenuView* source, const gfx::Point& location);
// Returns true if OnKeyPressed handled the key |event|.
bool OnKeyPressed(const ui::KeyEvent& event);
// Creates a MenuController. See |for_drop_| member for details on |for_drop|.
MenuController(bool for_drop, internal::MenuControllerDelegate* delegate);
~MenuController() override;
// Invokes AcceleratorPressed() on the hot tracked view if there is one.
// Returns true if AcceleratorPressed() was invoked. |event_flags| is the
// flags of the received key event.
bool SendAcceleratorToHotTrackedView(int event_flags);
void UpdateInitialLocation(const gfx::Rect& bounds,
MenuAnchorPosition position,
bool context_menu);
// Returns the anchor position adjusted for RTL languages. For example,
// in RTL MenuAnchorPosition::kBubbleLeft is mapped to kBubbleRight.
static MenuAnchorPosition AdjustAnchorPositionForRtl(
MenuAnchorPosition position);
// Invoked when the user accepts the selected item. This is only used
// when blocking. This schedules the loop to quit.
void Accept(MenuItemView* item, int event_flags);
void ReallyAccept();
bool ShowSiblingMenu(SubmenuView* source, const gfx::Point& mouse_location);
// Shows a context menu for |menu_item| as a result of an event if
// appropriate, using the given |screen_location|. This is invoked on long
// press, releasing the right mouse button, and pressing the "app" key.
// Returns whether a context menu was shown.
bool ShowContextMenu(MenuItemView* menu_item,
const gfx::Point& screen_location,
ui::MenuSourceType source_type);
// Closes all menus, including any menus of nested invocations of Run.
void CloseAllNestedMenus();
// Gets the enabled menu item at the specified location.
// If over_any_menu is non-null it is set to indicate whether the location
// is over any menu. It is possible for this to return NULL, but
// over_any_menu to be true. For example, the user clicked on a separator.
MenuItemView* GetMenuItemAt(View* menu, int x, int y);
// If there is an empty menu item at the specified location, it is returned.
MenuItemView* GetEmptyMenuItemAt(View* source, int x, int y);
// Returns true if the coordinate is over the scroll buttons of the
// SubmenuView's MenuScrollViewContainer. If true is returned, part is set to
// indicate which scroll button the coordinate is.
bool IsScrollButtonAt(SubmenuView* source,
int x,
int y,
MenuPart::Type* part);
// Returns the target for the mouse event. The coordinates are in terms of
// source's scroll view container.
MenuPart GetMenuPart(SubmenuView* source, const gfx::Point& source_loc);
// Returns the target for mouse events. The search is done through |item| and
// all its parents.
MenuPart GetMenuPartByScreenCoordinateUsingMenu(MenuItemView* item,
const gfx::Point& screen_loc);
// Implementation of GetMenuPartByScreenCoordinate for a single menu. Returns
// true if the supplied SubmenuView contains the location in terms of the
// screen. If it does, part is set appropriately and true is returned.
bool GetMenuPartByScreenCoordinateImpl(SubmenuView* menu,
const gfx::Point& screen_loc,
MenuPart* part);
// Returns the RootView of the target for the mouse event, if there is a
// target at |source_loc|.
MenuHostRootView* GetRootView(SubmenuView* source,
const gfx::Point& source_loc);
// Converts the located event from |source|'s geometry to |dst|'s geometry,
// iff the root view of source and dst differ.
void ConvertLocatedEventForRootView(View* source,
View* dst,
ui::LocatedEvent* event);
// Returns true if the SubmenuView contains the specified location. This does
// NOT included the scroll buttons, only the submenu view.
bool DoesSubmenuContainLocation(SubmenuView* submenu,
const gfx::Point& screen_loc);
// Returns whether the location is over the ACTIONABLE_SUBMENU's submenu area.
bool IsLocationOverSubmenuAreaOfActionableSubmenu(
MenuItemView* item,
const gfx::Point& screen_loc) const;
// Opens/Closes the necessary menus such that state_ matches that of
// pending_state_. This is invoked if submenus are not opened immediately,
// but after a delay.
void CommitPendingSelection();
// If item has a submenu, it is closed. This does NOT update the selection
// in anyway.
void CloseMenu(MenuItemView* item);
// If item has a submenu, it is opened. This does NOT update the selection
// in anyway.
void OpenMenu(MenuItemView* item);
// Implementation of OpenMenu. If |show| is true, this invokes show on the
// menu, otherwise Reposition is invoked.
void OpenMenuImpl(MenuItemView* item, bool show);
// Invoked when the children of a menu change and the menu is showing.
// This closes any submenus and resizes the submenu.
void MenuChildrenChanged(MenuItemView* item);
// Builds the paths of the two menu items into the two paths, and
// sets first_diff_at to the location of the first difference between the
// two paths.
void BuildPathsAndCalculateDiff(MenuItemView* old_item,
MenuItemView* new_item,
std::vector<MenuItemView*>* old_path,
std::vector<MenuItemView*>* new_path,
size_t* first_diff_at);
// Builds the path for the specified item.
void BuildMenuItemPath(MenuItemView* item, std::vector<MenuItemView*>* path);
// Starts/stops the timer that commits the pending state to state
// (opens/closes submenus).
void StartShowTimer();
void StopShowTimer();
// Starts/stops the timer cancel the menu. This is used during drag and
// drop when the drop enters/exits the menu.
void StartCancelAllTimer();
void StopCancelAllTimer();
// Calculates the bounds of the menu to show. is_leading is set to match the
// direction the menu opened in. Also calculates anchor that system compositor
// can use to position the menu.
gfx::Rect CalculateMenuBounds(MenuItemView* item,
bool prefer_leading,
bool* is_leading,
ui::OwnedWindowAnchor* anchor);
// Calculates the bubble bounds of the menu to show. is_leading is set to
// match the direction the menu opened in. Also calculates anchor that system
// compositor can use to position the menu.
// TODO(msisov): anchor.anchor_rect equals to returned rect at the moment as
// bubble menu bounds are used only by ash, as its backend uses menu bounds
// instead of anchor for positioning.
gfx::Rect CalculateBubbleMenuBounds(MenuItemView* item,
bool prefer_leading,
bool* is_leading,
ui::OwnedWindowAnchor* anchor);
// Returns the depth of the menu.
static size_t MenuDepth(MenuItemView* item);
// Selects the next or previous (depending on |direction|) menu item.
void IncrementSelection(SelectionIncrementDirectionType direction);
// Sets up accessible indices for menu items based on up/down arrow selection
// logic, to be used by screen readers to give accurate "item X of Y"
// information (and to be consistent with accessible keyboard use).
//
// This only sets one level of menu, so it must be called when submenus are
// opened as well.
void SetSelectionIndices(MenuItemView* parent);
// Selects the first or last (depending on |direction|) menu item.
void MoveSelectionToFirstOrLastItem(
SelectionIncrementDirectionType direction);
// Returns the first (|direction| == NAVIGATE_SELECTION_DOWN) or the last
// (|direction| == INCREMENT_SELECTION_UP) selectable child menu item of
// |parent|. If there are no selectable items returns NULL.
MenuItemView* FindInitialSelectableMenuItem(
MenuItemView* parent,
SelectionIncrementDirectionType direction);
// If the selected item has a submenu and it isn't currently open, the
// the selection is changed such that the menu opens immediately.
void OpenSubmenuChangeSelectionIfCan();
// If possible, closes the submenu.
void CloseSubmenu();
// Returns details about which menu items match the mnemonic |key|.
// |match_function| is used to determine which menus match.
SelectByCharDetails FindChildForMnemonic(
MenuItemView* parent,
char16_t key,
bool (*match_function)(MenuItemView* menu, char16_t mnemonic));
// Selects or accepts the appropriate menu item based on |details|.
void AcceptOrSelect(MenuItemView* parent, const SelectByCharDetails& details);
// Selects by mnemonic, and if that doesn't work tries the first character of
// the title.
void SelectByChar(char16_t key);
// For Windows and Aura we repost an event which dismisses the |source| menu.
// The menu may also be canceled depending on the target of the event. |event|
// is then processed without the menu present. On non-aura Windows, a new
// mouse event is generated and posted to the window (if there is one) at the
// location of the event. On aura, the event is reposted on the RootWindow.
void RepostEventAndCancel(SubmenuView* source, const ui::LocatedEvent* event);
// Sets the drop target to new_item.
void SetDropMenuItem(MenuItemView* new_item,
MenuDelegate::DropPosition position);
// Starts/stops scrolling as appropriate. part gives the part the mouse is
// over.
void UpdateScrolling(const MenuPart& part);
// Stops scrolling.
void StopScrolling();
// Updates active mouse view from the location of the event and sends it
// the appropriate events. This is used to send mouse events to child views so
// that they react to click-drag-release as if the user clicked on the view
// itself.
void UpdateActiveMouseView(SubmenuView* event_source,
const ui::MouseEvent& event,
View* target_menu);
// Sends a mouse release event to the current active mouse view and sets
// it to null.
void SendMouseReleaseToActiveView(SubmenuView* event_source,
const ui::MouseEvent& event);
// Sends a mouse capture lost event to the current active mouse view and sets
// it to null.
void SendMouseCaptureLostToActiveView();
// Sets exit type. Calling this can terminate the active nested message-loop.
void SetExitType(ExitType type);
// Performs the teardown of menus. This will notify the |delegate_|. If
// |exit_type_| is ExitType::kAll all nested runs will be exited.
void ExitMenu();
// Performs the teardown of the menu launched by Run(). The selected item is
// returned.
MenuItemView* ExitTopMostMenu();
// Handles the mouse location event on the submenu |source|.
void HandleMouseLocation(SubmenuView* source,
const gfx::Point& mouse_location);
// Sets hot-tracked state to the first focusable descendant view of |item|.
void SetInitialHotTrackedView(MenuItemView* item,
SelectionIncrementDirectionType direction);
// Sets hot-tracked state to the next focusable element after |item| in
// |direction|.
void SetNextHotTrackedView(MenuItemView* item,
SelectionIncrementDirectionType direction);
// Updates the current |hot_button_| and its hot tracked state.
void SetHotTrackedButton(Button* new_hot_button);
// Returns whether typing a new character will continue the existing prefix
// selection. If this returns false, typing a new character will start a new
// prefix selection, and some characters (such as Space) will be treated as
// commands instead of parts of the prefix.
bool ShouldContinuePrefixSelection() const;
// Manage alerted MenuItemViews that we are animating.
void RegisterAlertedItem(MenuItemView* item);
void UnregisterAlertedItem(MenuItemView* item);
// Sets anchor position, gravity and constraints for the |item|.
void SetAnchorParametersForItem(MenuItemView* item,
const gfx::Point& item_loc,
ui::OwnedWindowAnchor* anchor);
// The active instance.
static MenuController* active_instance_;
// If true the menu is shown for a drag and drop. Note that the semantics for
// drag and drop are slightly different: cancel timer is kicked off any time
// the drag moves outside the menu, mouse events do nothing...
const bool for_drop_;
// If true, we're showing.
bool showing_ = false;
// Indicates what to exit.
ExitType exit_type_ = ExitType::kNone;
// Whether we did a capture. We do a capture only if we're blocking and
// the mouse was down when Run.
bool did_capture_ = false;
// As the user drags the mouse around pending_state_ changes immediately.
// When the user stops moving/dragging the mouse (or clicks the mouse)
// pending_state_ is committed to state_, potentially resulting in
// opening or closing submenus. This gives a slight delayed effect to
// submenus as the user moves the mouse around. This is done so that as the
// user moves the mouse all submenus don't immediately pop.
State pending_state_;
State state_;
// If the user accepted the selection, this is the result.
raw_ptr<MenuItemView> result_ = nullptr;
// The event flags when the user selected the menu.
int accept_event_flags_ = 0;
// If not empty, it means we're nested. When Run is invoked from within
// Run, the current state (state_) is pushed onto menu_stack_. This allows
// MenuController to restore the state when the nested run returns.
using NestedState =
std::pair<State, std::unique_ptr<MenuButtonController::PressedLock>>;
std::list<NestedState> menu_stack_;
// When Run is invoked during an active Run, it may be called from a separate
// MenuControllerDelegate. If not empty it means we are nested, and the
// stacked delegates should be notified instead of |delegate_|.
std::list<internal::MenuControllerDelegate*> delegate_stack_;
// As the mouse moves around submenus are not opened immediately. Instead
// they open after this timer fires.
base::OneShotTimer show_timer_;
// Used to invoke CancelAll(). This is used during drag and drop to hide the
// menu after the mouse moves out of the of the menu. This is necessitated by
// the lack of an ability to detect when the drag has completed from the drop
// side.
base::OneShotTimer cancel_all_timer_;
// Drop target.
raw_ptr<MenuItemView> drop_target_ = nullptr;
MenuDelegate::DropPosition drop_position_ =
MenuDelegate::DropPosition::kUnknow;
// Owner of child windows.
// WARNING: this may be NULL.
raw_ptr<Widget> owner_ = nullptr;
// An optional NativeView to which gestures will be forwarded to if
// RunType::SEND_GESTURE_EVENTS_TO_OWNER is set.
gfx::NativeView native_view_for_gestures_ = nullptr;
gfx::AcceleratedWidget parent_widget_ = gfx::kNullAcceleratedWidget;
// Indicates a possible drag operation.
bool possible_drag_ = false;
// True when drag operation is in progress.
bool drag_in_progress_ = false;
// True when the drag operation in progress was initiated by the
// MenuController for a child MenuItemView (as opposed to initiated separately
// by a child View).
bool did_initiate_drag_ = false;
// Location the mouse was pressed at. Used to detect d&d.
gfx::Point press_pt_;
// We get a slew of drag updated messages as the mouse is over us. To avoid
// continually processing whether we can drop, we cache the coordinates.
bool valid_drop_coordinates_ = false;
gfx::Point drop_pt_;
int last_drop_operation_ = ui::DragDropTypes::DRAG_NONE;
// If true, we're in the middle of invoking ShowAt on a submenu.
bool showing_submenu_ = false;
// Task for scrolling the menu. If non-null indicates a scroll is currently
// underway.
std::unique_ptr<MenuScrollTask> scroll_task_;
// The lock to keep the menu button pressed while a menu is visible.
std::unique_ptr<MenuButtonController::PressedLock> pressed_lock_;
// ViewTracker used to store the View mouse drag events are forwarded to. See
// UpdateActiveMouseView() for details.
std::unique_ptr<ViewTracker> active_mouse_view_tracker_;
// Current hot tracked child button if any.
raw_ptr<Button> hot_button_ = nullptr;
raw_ptr<internal::MenuControllerDelegate> delegate_;
// The timestamp of the event which closed the menu - or 0 otherwise.
base::TimeTicks closing_event_time_;
// Time when the menu is first shown.
base::TimeTicks menu_start_time_;
// If a mouse press triggered this menu, this will have its location (in
// screen coordinates). Otherwise this will be (0, 0).
gfx::Point menu_start_mouse_press_loc_;
// If the mouse was under the menu when the menu was run, this will have its
// location. Otherwise it will be null. This is used to ignore mouse move
// events triggered by the menu opening, to avoid selecting the menu item
// over the mouse.
absl::optional<gfx::Point> menu_open_mouse_loc_;
// Controls behavior differences between a combobox and other types of menu
// (like a context menu).
ComboboxType combobox_type_ = ComboboxType::kNone;
// Whether the menu |owner_| needs gesture events. When set to true, the menu
// will preserve the gesture events of the |owner_| and MenuController will
// forward the gesture events to |owner_| until no |ET_GESTURE_END| event is
// captured.
bool send_gesture_events_to_owner_ = false;
// Set to true if the menu item was selected by touch.
bool item_selected_by_touch_ = false;
// Whether to use the ash system UI specific layout.
bool use_ash_system_ui_layout_ = false;
// During mouse event handling, this is the RootView to forward mouse events
// to. We need this, because if we forward one event to it (e.g., mouse
// pressed), subsequent events (like dragging) should also go to it, even if
// the mouse is no longer over the view.
raw_ptr<MenuHostRootView> current_mouse_event_target_ = nullptr;
// A mask of the EventFlags for the mouse buttons currently pressed.
int current_mouse_pressed_state_ = 0;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<MenuClosureAnimationMac> menu_closure_animation_;
std::unique_ptr<MenuCocoaWatcherMac> menu_cocoa_watcher_;
#endif
std::unique_ptr<MenuPreTargetHandler> menu_pre_target_handler_;
// Animation used for alerted MenuItemViews. Started on demand.
gfx::ThrobAnimation alert_animation_;
// Currently showing alerted menu items. Updated when submenus open and close.
base::flat_set<MenuItemView*> alerted_items_;
// The rounded corners of the context menu.
absl::optional<gfx::RoundedCornersF> rounded_corners_ = absl::nullopt;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller.h | C++ | unknown | 32,656 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_COCOA_DELEGATE_IMPL_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_COCOA_DELEGATE_IMPL_H_
#import "base/mac/scoped_nsobject.h"
#import "ui/base/cocoa/menu_controller.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/views_export.h"
VIEWS_EXPORT
@interface MenuControllerCocoaDelegateImpl
: NSObject <MenuControllerCocoaDelegate>
- (void)setAnchorRect:(gfx::Rect)rect;
@end
#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_COCOA_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller_cocoa_delegate_impl.h | Objective-C | unknown | 653 |
// 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.
#import "ui/views/controls/menu/menu_controller_cocoa_delegate_impl.h"
#include "base/logging.h"
#include "base/mac/foundation_util.h"
#import "base/mac/scoped_nsobject.h"
#import "base/message_loop/message_pump_mac.h"
#import "skia/ext/skia_utils_mac.h"
#import "ui/base/cocoa/cocoa_base_utils.h"
#include "ui/base/interaction/element_tracker_mac.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/mac/coordinate_conversion.h"
#include "ui/gfx/platform_font_mac.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/badge_painter.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/layout/layout_provider.h"
namespace {
constexpr CGFloat kIPHDotSize = 6;
NSImage* NewTagImage(const ui::ColorProvider* color_provider) {
// 1. Make the attributed string.
NSString* badge_text = l10n_util::GetNSString(features::IsChromeRefresh2023()
? IDS_NEW_BADGE_UPPERCASE
: IDS_NEW_BADGE);
// The preferred font is slightly smaller and slightly more bold than the
// menu font. The size change is required to make it look correct in the
// badge; we add a small degree of bold to prevent color smearing/blurring
// due to font smoothing. This ensures readability on all platforms and in
// both light and dark modes.
gfx::Font badge_font =
views::BadgePainter::GetBadgeFont(views::MenuConfig::instance().font_list)
.GetPrimaryFont();
DCHECK(color_provider);
NSColor* badge_text_color = skia::SkColorToSRGBNSColor(
color_provider->GetColor(ui::kColorBadgeInCocoaMenuForeground));
NSDictionary* badge_attrs = @{
NSFontAttributeName : base::mac::CFToNSCast(badge_font.GetCTFont()),
NSForegroundColorAttributeName : badge_text_color,
};
NSMutableAttributedString* badge_attr_string =
[[NSMutableAttributedString alloc] initWithString:badge_text
attributes:badge_attrs];
// 2. Calculate the size required.
NSSize badge_size = [badge_attr_string size];
badge_size.width = trunc(badge_size.width);
badge_size.height = trunc(badge_size.height);
badge_size.width += 2 * views::BadgePainter::kBadgeInternalPadding +
2 * views::BadgePainter::kBadgeHorizontalMargin;
badge_size.height += views::BadgePainter::kBadgeInternalPaddingTopMac;
// 3. Craft the image.
return [NSImage
imageWithSize:badge_size
flipped:NO
drawingHandler:^(NSRect dest_rect) {
NSRect badge_frame = NSInsetRect(
dest_rect, views::BadgePainter::kBadgeHorizontalMargin, 0);
const int badge_radius =
views::LayoutProvider::Get()->GetCornerRadiusMetric(
views::ShapeContextTokens::kBadgeRadius);
NSBezierPath* rounded_badge_rect =
[NSBezierPath bezierPathWithRoundedRect:badge_frame
xRadius:badge_radius
yRadius:badge_radius];
DCHECK(color_provider);
NSColor* badge_color = skia::SkColorToSRGBNSColor(
color_provider->GetColor(ui::kColorBadgeInCocoaMenuBackground));
[badge_color set];
[rounded_badge_rect fill];
NSPoint badge_text_location = NSMakePoint(
NSMinX(badge_frame) + views::BadgePainter::kBadgeInternalPadding,
NSMinY(badge_frame) +
views::BadgePainter::kBadgeInternalPaddingTopMac);
[badge_attr_string drawAtPoint:badge_text_location];
return YES;
}];
}
NSImage* IPHDotImage(const ui::ColorProvider* color_provider) {
// Embed horizontal centering space as NSMenuItem will otherwise left-align
// it.
return [NSImage
imageWithSize:NSMakeSize(2 * kIPHDotSize, kIPHDotSize)
flipped:NO
drawingHandler:^(NSRect dest_rect) {
NSBezierPath* dot_path = [NSBezierPath
bezierPathWithOvalInRect:NSMakeRect(kIPHDotSize / 2, 0, kIPHDotSize,
kIPHDotSize)];
NSColor* dot_color = skia::SkColorToSRGBNSColor(
color_provider->GetColor(ui::kColorButtonBackgroundProminent));
[dot_color set];
[dot_path fill];
return YES;
}];
}
} // namespace
// --- Private API begin ---
// Historically, all menu handling in macOS was handled by HI Toolbox, and the
// bridge from Cocoa to Carbon to use Carbon's menus was the class
// NSCarbonMenuImpl. However, starting in macOS 13, it looks like this is
// changing, as now a NSCocoaMenuImpl class exists, which is optionally created
// in -[NSMenu _createMenuImpl] and may possibly in the future be returned from
// -[NSMenu _menuImpl]. Therefore, abstract away into a protocol the (one)
// common method that this code uses that is present on both Impl classes.
@protocol CrNSMenuImpl <NSObject>
@optional
- (void)highlightItemAtIndex:(NSInteger)index;
@end
@interface NSMenu (Impl)
- (id<CrNSMenuImpl>)_menuImpl;
- (CGRect)_boundsIfOpen;
@end
// --- Private API end ---
// An NSTextAttachmentCell to show the [New] tag on a menu item.
//
// /!\ WARNING /!\
//
// Do NOT update to the "new in macOS 10.11" API of NSTextAttachment.image until
// macOS 10.15 is the minimum required macOS for Chromium. Because menus are
// Carbon-based, the new NSTextAttachment.image API did not function correctly
// until then. Specifically, in macOS 10.11-10.12, images that use the new API
// do not appear. In macOS 10.13-10.14, the flipped flag of -[NSImage
// imageWithSize:flipped:drawingHandler:] is not respected. Only when 10.15 is
// the minimum required OS can https://crrev.com/c/2572937 be relanded.
@interface NewTagAttachmentCell : NSTextAttachmentCell
@end
@implementation NewTagAttachmentCell
- (instancetype)initWithColorProvider:(const ui::ColorProvider*)colorProvider {
if (self = [super init]) {
self.image = NewTagImage(colorProvider);
}
return self;
}
- (NSPoint)cellBaselineOffset {
// The baseline offset of the badge image to the menu text baseline.
const int kBadgeBaselineOffset = features::IsChromeRefresh2023() ? -2 : -4;
return NSMakePoint(0, kBadgeBaselineOffset);
}
- (NSSize)cellSize {
return [self.image size];
}
@end
@interface MenuControllerCocoaDelegateImpl () {
NSMutableArray* _menuObservers;
gfx::Rect _anchorRect;
}
@end
@implementation MenuControllerCocoaDelegateImpl
- (instancetype)init {
if (self = [super init]) {
_menuObservers = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
for (NSObject* obj in _menuObservers) {
[[NSNotificationCenter defaultCenter] removeObserver:obj];
}
[_menuObservers release];
[super dealloc];
}
- (void)setAnchorRect:(gfx::Rect)rect {
_anchorRect = rect;
}
- (void)controllerWillAddItem:(NSMenuItem*)menuItem
fromModel:(ui::MenuModel*)model
atIndex:(size_t)index
withColorProvider:(const ui::ColorProvider*)colorProvider {
if (model->IsNewFeatureAt(index)) {
NSMutableAttributedString* attrTitle = [[[NSMutableAttributedString alloc]
initWithString:menuItem.title] autorelease];
// /!\ WARNING /!\ Do not update this to use NSTextAttachment.image until
// macOS 10.15 is the minimum required OS. See the details on the class
// comment above.
NSTextAttachment* attachment =
[[[NSTextAttachment alloc] init] autorelease];
attachment.attachmentCell = [[[NewTagAttachmentCell alloc]
initWithColorProvider:colorProvider] autorelease];
[attrTitle
appendAttributedString:[NSAttributedString
attributedStringWithAttachment:attachment]];
menuItem.attributedTitle = attrTitle;
}
if (model->IsAlertedAt(index)) {
NSImage* iphDotImage = IPHDotImage(colorProvider);
menuItem.onStateImage = iphDotImage;
menuItem.offStateImage = iphDotImage;
menuItem.mixedStateImage = iphDotImage;
}
}
- (void)controllerWillAddMenu:(NSMenu*)menu fromModel:(ui::MenuModel*)model {
absl::optional<size_t> alerted_index;
// This list will be copied into callback blocks later if it's non-empty, but
// since it's fairly small that's not a big deal.
std::vector<ui::ElementIdentifier> element_ids;
for (size_t i = 0; i < model->GetItemCount(); ++i) {
if (model->IsAlertedAt(i)) {
DCHECK(!alerted_index.has_value());
alerted_index = i;
}
const ui::ElementIdentifier identifier = model->GetElementIdentifierAt(i);
if (identifier) {
element_ids.push_back(identifier);
}
}
if (alerted_index.has_value() || !element_ids.empty()) {
auto shown_callback = ^(NSNotification* note) {
NSMenu* const menu_obj = note.object;
if (alerted_index.has_value()) {
if ([menu respondsToSelector:@selector(_menuImpl)]) {
id<CrNSMenuImpl> menuImpl = [menu_obj _menuImpl];
if ([menuImpl respondsToSelector:@selector(highlightItemAtIndex:)]) {
const auto index =
base::checked_cast<NSInteger>(alerted_index.value());
[menuImpl highlightItemAtIndex:index];
}
}
}
// This situation is broken.
//
// First, NSMenuDidBeginTrackingNotification is the best way to get called
// right before the menu is shown, but at the moment of the call, the menu
// isn't open yet. Second, to make things worse, the implementation of
// -_boundsIfOpen *tries* to return an NSZeroRect if the menu isn't open
// yet but fails to detect it correctly, and instead falls over and
// returns a bogus bounds. Fortunately, those bounds are broken in a
// predictable way, so that situation can be detected. Don't even bother
// trying to make the -_boundsIfOpen call on the notification; there's no
// point.
//
// However, it takes just one trip through the main loop for the menu to
// appear and the -_boundsIfOpen call to work.
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC),
dispatch_get_main_queue(), ^{
// Even though all supported macOS releases have `-_boundsIfOpen`,
// because it's not official API, retain the fallback code written
// for earlier versions of macOSes.
//
// The fallback bounds are intentionally twice as wide as they
// should be because even though we could check the RTL bit and
// guess whether the menu should appear to the left or right of the
// anchor, if the anchor is near one side of the screen the menu
// could end up on the other side.
gfx::Rect screen_rect = _anchorRect;
CGSize menu_size = [menu_obj size];
screen_rect.Inset(gfx::Insets::TLBR(
0, -menu_size.width, -menu_size.height, -menu_size.width));
if ([menu_obj respondsToSelector:@selector(_boundsIfOpen)]) {
CGRect bounds = [menu_obj _boundsIfOpen];
// A broken bounds for a menu that isn't
// actually yet open looks like: {{zeroish,
// main display height}, {zeroish, zeroish}}.
auto is_zeroish = [](CGFloat f) { return f >= 0 && f < 0.00001; };
if (is_zeroish(bounds.origin.x) && bounds.origin.y > 300 &&
is_zeroish(bounds.size.width) &&
is_zeroish(bounds.size.height)) {
// FYI, this never actually happens.
LOG(ERROR) << "Get menu bounds failed.";
} else {
screen_rect = gfx::ScreenRectFromNSRect(bounds);
}
}
for (ui::ElementIdentifier element_id : element_ids) {
ui::ElementTrackerMac::GetInstance()->NotifyMenuItemShown(
menu_obj, element_id, screen_rect);
}
});
};
[_menuObservers
addObject:[[NSNotificationCenter defaultCenter]
addObserverForName:NSMenuDidBeginTrackingNotification
object:menu
queue:nil
usingBlock:shown_callback]];
}
if (!element_ids.empty()) {
auto hidden_callback = ^(NSNotification* note) {
NSMenu* const menu_obj = note.object;
// We expect to see the following order of events:
// - element shown
// - element activated (optional)
// - element hidden
// However, the code that detects menu item activation is called *after*
// the current callback. To make sure the events happen in the right order
// we'll defer processing of element hidden events until the end of the
// current system event queue.
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC),
dispatch_get_main_queue(), ^{
for (ui::ElementIdentifier element_id : element_ids) {
ui::ElementTrackerMac::GetInstance()->NotifyMenuItemHidden(
menu_obj, element_id);
}
});
};
[_menuObservers
addObject:[[NSNotificationCenter defaultCenter]
addObserverForName:NSMenuDidEndTrackingNotification
object:menu
queue:nil
usingBlock:hidden_callback]];
}
}
@end
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller_cocoa_delegate_impl.mm | Objective-C++ | unknown | 13,760 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_
namespace views {
class MenuItemView;
// This is internal as there should be no need for usage of this class outside
// of views.
namespace internal {
// Used by MenuController to notify of interesting events that are intended for
// the class using MenuController. This is implemented by MenuRunnerImpl.
class MenuControllerDelegate {
public:
enum NotifyType { NOTIFY_DELEGATE, DONT_NOTIFY_DELEGATE };
// Invoked when MenuController closes. unless the owner deletes the
// MenuController during MenuDelegate::ExecuteCommand. |mouse_event_flags| are
// the flags set on the ui::MouseEvent which selected |menu|, otherwise 0.
virtual void OnMenuClosed(NotifyType type,
MenuItemView* menu,
int mouse_event_flags) = 0;
// Invoked when the MenuDelegate::GetSiblingMenu() returns non-NULL.
virtual void SiblingMenuCreated(MenuItemView* menu) = 0;
protected:
virtual ~MenuControllerDelegate() = default;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller_delegate.h | C++ | unknown | 1,356 |
// Copyright 2014 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/menu_controller.h"
#include <vector>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_mode.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_handler.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/menu/menu_controller_delegate.h"
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/controls/menu/menu_host.h"
#include "ui/views/controls/menu/menu_host_root_view.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_types.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/test/menu_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget_utils.h"
#if defined(USE_AURA)
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_client_observer.h"
#include "ui/aura/null_window_targeter.h"
#include "ui/aura/scoped_window_targeter.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/views/controls/menu/menu_pre_target_handler.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/buildflags.h"
#include "ui/ozone/public/ozone_platform.h"
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif
#if defined(USE_OZONE_PLATFORM_X11)
#include "ui/events/test/events_test_utils_x11.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/windows_version.h"
#endif
namespace views::test {
namespace {
using ::ui::mojom::DragOperation;
bool ShouldIgnoreScreenBoundsForMenus() {
#if BUILDFLAG(IS_OZONE)
// Some platforms, such as Wayland, disallow client applications to manipulate
// global screen coordinates, requiring menus to be positioned relative to
// their parent windows. See comment in ozone_platform_wayland.cc.
return !ui::OzonePlatform::GetInstance()
->GetPlatformProperties()
.supports_global_screen_coordinates;
#else
return false;
#endif
}
// Test implementation of MenuControllerDelegate that only reports the values
// called of OnMenuClosed.
class TestMenuControllerDelegate : public internal::MenuControllerDelegate {
public:
TestMenuControllerDelegate();
TestMenuControllerDelegate(const TestMenuControllerDelegate&) = delete;
TestMenuControllerDelegate& operator=(const TestMenuControllerDelegate&) =
delete;
~TestMenuControllerDelegate() override = default;
int on_menu_closed_called() { return on_menu_closed_called_; }
NotifyType on_menu_closed_notify_type() {
return on_menu_closed_notify_type_;
}
MenuItemView* on_menu_closed_menu() { return on_menu_closed_menu_; }
int on_menu_closed_mouse_event_flags() {
return on_menu_closed_mouse_event_flags_;
}
// On a subsequent call to OnMenuClosed |controller| will be deleted.
void set_on_menu_closed_callback(base::RepeatingClosure callback) {
on_menu_closed_callback_ = std::move(callback);
}
// internal::MenuControllerDelegate:
void OnMenuClosed(NotifyType type,
MenuItemView* menu,
int mouse_event_flags) override;
void SiblingMenuCreated(MenuItemView* menu) override;
private:
// Number of times OnMenuClosed has been called.
int on_menu_closed_called_ = 0;
// The values passed on the last call of OnMenuClosed.
NotifyType on_menu_closed_notify_type_ = NOTIFY_DELEGATE;
raw_ptr<MenuItemView> on_menu_closed_menu_ = nullptr;
int on_menu_closed_mouse_event_flags_ = 0;
// Optional callback triggered during OnMenuClosed
base::RepeatingClosure on_menu_closed_callback_;
};
TestMenuControllerDelegate::TestMenuControllerDelegate() = default;
void TestMenuControllerDelegate::OnMenuClosed(NotifyType type,
MenuItemView* menu,
int mouse_event_flags) {
on_menu_closed_called_++;
on_menu_closed_notify_type_ = type;
on_menu_closed_menu_ = menu;
on_menu_closed_mouse_event_flags_ = mouse_event_flags;
if (!on_menu_closed_callback_.is_null())
on_menu_closed_callback_.Run();
}
void TestMenuControllerDelegate::SiblingMenuCreated(MenuItemView* menu) {}
class SubmenuViewShown : public SubmenuView {
public:
using SubmenuView::SubmenuView;
SubmenuViewShown(const SubmenuViewShown&) = delete;
SubmenuViewShown& operator=(const SubmenuViewShown&) = delete;
~SubmenuViewShown() override = default;
bool IsShowing() const override { return true; }
};
class TestEventHandler : public ui::EventHandler {
public:
TestEventHandler() = default;
TestEventHandler(const TestEventHandler&) = delete;
TestEventHandler& operator=(const TestEventHandler&) = delete;
void OnTouchEvent(ui::TouchEvent* event) override {
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
outstanding_touches_++;
break;
case ui::ET_TOUCH_RELEASED:
case ui::ET_TOUCH_CANCELLED:
outstanding_touches_--;
break;
default:
break;
}
}
int outstanding_touches() const { return outstanding_touches_; }
private:
int outstanding_touches_ = 0;
};
// A test widget that counts gesture events.
class GestureTestWidget : public Widget {
public:
GestureTestWidget() = default;
GestureTestWidget(const GestureTestWidget&) = delete;
GestureTestWidget& operator=(const GestureTestWidget&) = delete;
void OnGestureEvent(ui::GestureEvent* event) override { ++gesture_count_; }
int gesture_count() const { return gesture_count_; }
private:
int gesture_count_ = 0;
};
#if defined(USE_AURA)
// A DragDropClient which does not trigger a nested run loop. Instead a
// callback is triggered during StartDragAndDrop in order to allow testing.
class TestDragDropClient : public aura::client::DragDropClient {
public:
explicit TestDragDropClient(base::RepeatingClosure callback)
: start_drag_and_drop_callback_(std::move(callback)) {}
TestDragDropClient(const TestDragDropClient&) = delete;
TestDragDropClient& operator=(const TestDragDropClient&) = delete;
~TestDragDropClient() override = default;
// aura::client::DragDropClient:
DragOperation StartDragAndDrop(std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& screen_location,
int allowed_operations,
ui::mojom::DragEventSource source) override;
#if BUILDFLAG(IS_LINUX)
void UpdateDragImage(const gfx::ImageSkia& image,
const gfx::Vector2d& offset) override {}
#endif
void DragCancel() override;
bool IsDragDropInProgress() override;
void AddObserver(aura::client::DragDropClientObserver* observer) override {}
void RemoveObserver(aura::client::DragDropClientObserver* observer) override {
}
private:
base::RepeatingClosure start_drag_and_drop_callback_;
bool drag_in_progress_ = false;
};
DragOperation TestDragDropClient::StartDragAndDrop(
std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& screen_location,
int allowed_operations,
ui::mojom::DragEventSource source) {
drag_in_progress_ = true;
start_drag_and_drop_callback_.Run();
return DragOperation::kNone;
}
void TestDragDropClient::DragCancel() {
drag_in_progress_ = false;
}
bool TestDragDropClient::IsDragDropInProgress() {
return drag_in_progress_;
}
#endif // defined(USE_AURA)
// View which cancels the menu it belongs to on mouse press.
class CancelMenuOnMousePressView : public View {
public:
explicit CancelMenuOnMousePressView(MenuController* controller)
: controller_(controller) {}
// View:
bool OnMousePressed(const ui::MouseEvent& event) override {
controller_->Cancel(MenuController::ExitType::kAll);
return true;
}
// This is needed to prevent the view from being "squashed" to zero height
// when the menu which owns it is shown. In such state the logic which
// determines if the menu contains the mouse press location doesn't work.
gfx::Size CalculatePreferredSize() const override { return size(); }
private:
raw_ptr<MenuController> controller_;
};
} // namespace
class TestMenuItemViewShown : public MenuItemView {
public:
explicit TestMenuItemViewShown(MenuDelegate* delegate)
: MenuItemView(delegate) {
submenu_ = new SubmenuViewShown(this);
}
TestMenuItemViewShown(const TestMenuItemViewShown&) = delete;
TestMenuItemViewShown& operator=(const TestMenuItemViewShown&) = delete;
~TestMenuItemViewShown() override = default;
void SetController(MenuController* controller) { set_controller(controller); }
void AddEmptyMenusForTest() { AddEmptyMenus(); }
void SetActualMenuPosition(MenuItemView::MenuPosition position) {
set_actual_menu_position(position);
}
MenuItemView::MenuPosition ActualMenuPosition() {
return actual_menu_position();
}
};
class TestMenuItemViewNotShown : public MenuItemView {
public:
explicit TestMenuItemViewNotShown(MenuDelegate* delegate)
: MenuItemView(delegate) {
submenu_ = new SubmenuView(this);
}
TestMenuItemViewNotShown(const TestMenuItemViewNotShown&) = delete;
TestMenuItemViewNotShown& operator=(const TestMenuItemViewNotShown&) = delete;
~TestMenuItemViewNotShown() override = default;
void SetController(MenuController* controller) { set_controller(controller); }
};
struct MenuBoundsOptions {
public:
gfx::Rect anchor_bounds = gfx::Rect(500, 500, 10, 10);
gfx::Rect monitor_bounds = gfx::Rect(0, 0, 1000, 1000);
gfx::Size menu_size = gfx::Size(100, 100);
MenuAnchorPosition menu_anchor = MenuAnchorPosition::kTopLeft;
MenuItemView::MenuPosition menu_position =
MenuItemView::MenuPosition::kBestFit;
};
class MenuControllerTest : public ViewsTestBase,
public testing::WithParamInterface<bool> {
public:
MenuControllerTest() = default;
MenuControllerTest(const MenuControllerTest&) = delete;
MenuControllerTest& operator=(const MenuControllerTest&) = delete;
~MenuControllerTest() override = default;
// ViewsTestBase:
void SetUp() override {
if (testing::UnitTest::GetInstance()->current_test_info()->value_param()) {
// Setup right to left environment if necessary.
if (GetParam())
base::i18n::SetRTLForTesting(true);
}
auto test_views_delegate = std::make_unique<ReleaseRefTestViewsDelegate>();
test_views_delegate_ = test_views_delegate.get();
// ViewsTestBase takes ownership, destroying during Teardown.
set_views_delegate(std::move(test_views_delegate));
ViewsTestBase::SetUp();
Init();
ASSERT_TRUE(base::CurrentUIThread::IsSet());
}
void TearDown() override {
owner_->CloseNow();
DestroyMenuController();
ViewsTestBase::TearDown();
base::i18n::SetRTLForTesting(false);
}
void ReleaseTouchId(int id) { event_generator_->ReleaseTouchId(id); }
void PressKey(ui::KeyboardCode key_code) {
event_generator_->PressKey(key_code, 0);
}
void DispatchKey(ui::KeyboardCode key_code) {
ui::KeyEvent event(ui::EventType::ET_KEY_PRESSED, key_code, 0);
menu_controller_->OnWillDispatchKeyEvent(&event);
}
gfx::Rect CalculateMenuBounds(const MenuBoundsOptions& options) {
SetUpMenuControllerForCalculateBounds(options);
bool is_leading;
ui::OwnedWindowAnchor anchor;
return menu_controller_->CalculateMenuBounds(menu_item_.get(), true,
&is_leading, &anchor);
}
gfx::Rect CalculateBubbleMenuBounds(const MenuBoundsOptions& options,
MenuItemView* menu_item) {
SetUpMenuControllerForCalculateBounds(options);
bool is_leading;
ui::OwnedWindowAnchor anchor;
return menu_controller_->CalculateBubbleMenuBounds(menu_item, true,
&is_leading, &anchor);
}
gfx::Rect CalculateBubbleMenuBounds(const MenuBoundsOptions& options) {
return CalculateBubbleMenuBounds(options, menu_item_.get());
}
gfx::Rect CalculateExpectedMenuAnchorRect(MenuItemView* menu_item,
const gfx::Rect& item_bounds) {
if (menu_item->GetParentMenuItem()) {
gfx::Rect anchor_rect = item_bounds;
anchor_rect.set_size({1, 1});
const MenuConfig& menu_config = MenuConfig::instance();
const int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
const int left_of_parent = menu_item->GetBoundsInScreen().x() -
item_bounds.width() + submenu_horizontal_inset;
// TODO(1163646): handle RTL layout.
anchor_rect.set_x(left_of_parent + item_bounds.width());
anchor_rect.set_width(item_bounds.x() - anchor_rect.x());
return anchor_rect;
}
return menu_item->bounds();
}
void MenuChildrenChanged(MenuItemView* item) {
menu_controller_->MenuChildrenChanged(item);
}
static MenuAnchorPosition AdjustAnchorPositionForRtl(
MenuAnchorPosition position) {
return MenuController::AdjustAnchorPositionForRtl(position);
}
#if defined(USE_AURA)
// Verifies that a non-nested menu fully closes when receiving an escape key.
void TestAsyncEscapeKey() {
ui::KeyEvent event(ui::EventType::ET_KEY_PRESSED, ui::VKEY_ESCAPE, 0);
menu_controller_->OnWillDispatchKeyEvent(&event);
}
// Verifies that an open menu receives a cancel event, and closes.
void TestCancelEvent() {
EXPECT_EQ(MenuController::ExitType::kNone, menu_controller_->exit_type());
ui::CancelModeEvent cancel_event;
event_generator_->Dispatch(&cancel_event);
EXPECT_EQ(MenuController::ExitType::kAll, menu_controller_->exit_type());
}
#endif // defined(USE_AURA)
// Verifies the state of the |menu_controller_| before destroying it.
void VerifyDragCompleteThenDestroy() {
EXPECT_FALSE(menu_controller()->drag_in_progress());
EXPECT_EQ(MenuController::ExitType::kAll, menu_controller()->exit_type());
DestroyMenuController();
}
// Setups |menu_controller_delegate_| to be destroyed when OnMenuClosed is
// called.
void TestDragCompleteThenDestroyOnMenuClosed() {
menu_controller_delegate_->set_on_menu_closed_callback(
base::BindRepeating(&MenuControllerTest::VerifyDragCompleteThenDestroy,
base::Unretained(this)));
}
// Tests destroying the active |menu_controller_| and replacing it with a new
// active instance.
void TestMenuControllerReplacementDuringDrag() {
DestroyMenuController();
menu_item()->GetSubmenu()->Close();
const bool for_drop = false;
menu_controller_ =
new MenuController(for_drop, menu_controller_delegate_.get());
menu_controller_->owner_ = owner_.get();
menu_controller_->showing_ = true;
}
// Tests that the menu does not destroy itself when canceled during a drag.
void TestCancelAllDuringDrag() {
menu_controller_->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(0, menu_controller_delegate_->on_menu_closed_called());
}
// Tests that destroying the menu during ViewsDelegate::ReleaseRef does not
// cause a crash.
void TestDestroyedDuringViewsRelease() {
// |test_views_delegate_| is owned by views::ViewsTestBase and not deleted
// until TearDown. MenuControllerTest outlives it.
test_views_delegate_->set_release_ref_callback(base::BindRepeating(
&MenuControllerTest::DestroyMenuController, base::Unretained(this)));
menu_controller_->ExitMenu();
}
void TestMenuFitsOnScreen(MenuAnchorPosition menu_anchor_position,
const gfx::Rect& monitor_bounds) {
SCOPED_TRACE(base::StringPrintf(
"MenuAnchorPosition: %d, monitor_bounds: @%s\n", menu_anchor_position,
monitor_bounds.ToString().c_str()));
MenuBoundsOptions options;
options.menu_anchor = menu_anchor_position;
options.monitor_bounds = monitor_bounds;
const gfx::Point monitor_center = monitor_bounds.CenterPoint();
// Simulate a bottom shelf with a tall menu.
const int button_size = 50;
options.anchor_bounds =
gfx::Rect(monitor_center.x(), monitor_bounds.bottom() - button_size,
button_size, button_size);
gfx::Rect final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/false);
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu will show on screen.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
// Simulate a left shelf with a tall menu.
options.anchor_bounds = gfx::Rect(monitor_bounds.x(), monitor_center.y(),
button_size, button_size);
final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu will show on screen.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
// Simulate right shelf with a tall menu.
options.anchor_bounds =
gfx::Rect(monitor_bounds.right() - button_size, monitor_center.y(),
button_size, button_size);
final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu will show on screen.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
}
void TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition menu_anchor_position,
const gfx::Rect& monitor_bounds) {
SCOPED_TRACE(base::StringPrintf(
"MenuAnchorPosition: %d, monitor_bounds: @%s\n", menu_anchor_position,
monitor_bounds.ToString().c_str()));
MenuBoundsOptions options;
options.menu_anchor = menu_anchor_position;
options.monitor_bounds = monitor_bounds;
const gfx::Size anchor_size(0, 0);
// Simulate a click on the top left corner.
options.anchor_bounds = gfx::Rect(monitor_bounds.origin(), anchor_size);
gfx::Rect final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/false);
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu is within the monitor bounds.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
// Simulate a click on the bottom left corner.
options.anchor_bounds =
gfx::Rect(monitor_bounds.bottom_left(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu is within the monitor bounds.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
// Simulate a click on the top right corner.
options.anchor_bounds = gfx::Rect(monitor_bounds.top_right(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu is within the monitor bounds.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
// Simulate a click on the bottom right corner.
options.anchor_bounds =
gfx::Rect(monitor_bounds.bottom_right(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
// Adjust the final bounds to not include the shadow and border.
final_bounds.Inset(border_and_shadow_insets);
// Test that the menu is within the monitor bounds.
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds));
}
void TestMenuFitsOnSmallScreen(MenuAnchorPosition menu_anchor_position,
const gfx::Rect& monitor_bounds) {
SCOPED_TRACE(base::StringPrintf(
"MenuAnchorPosition: %d, monitor_bounds: @%s\n", menu_anchor_position,
monitor_bounds.ToString().c_str()));
MenuBoundsOptions options;
options.menu_anchor = menu_anchor_position;
options.monitor_bounds = monitor_bounds;
options.menu_size = monitor_bounds.size();
options.menu_size.Enlarge(100, 100);
const gfx::Size anchor_size(0, 0);
// Adjust the final bounds to not include the shadow and border.
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/false);
options.anchor_bounds = gfx::Rect(monitor_bounds.origin(), anchor_size);
gfx::Rect final_bounds = CalculateBubbleMenuBounds(options);
final_bounds.Inset(border_and_shadow_insets);
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
options.anchor_bounds =
gfx::Rect(monitor_bounds.bottom_left(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
final_bounds.Inset(border_and_shadow_insets);
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
options.anchor_bounds =
gfx::Rect(monitor_bounds.bottom_right(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
final_bounds.Inset(border_and_shadow_insets);
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
options.anchor_bounds = gfx::Rect(monitor_bounds.top_right(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
final_bounds.Inset(border_and_shadow_insets);
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
options.anchor_bounds =
gfx::Rect(monitor_bounds.CenterPoint(), anchor_size);
final_bounds = CalculateBubbleMenuBounds(options);
final_bounds.Inset(border_and_shadow_insets);
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
}
void TestSubmenuFitsOnScreen(MenuItemView* item,
const gfx::Rect& monitor_bounds,
const gfx::Rect& parent_bounds,
MenuAnchorPosition menu_anchor) {
MenuBoundsOptions options;
options.menu_anchor = menu_anchor;
options.monitor_bounds = monitor_bounds;
// Adjust the final bounds to not include the shadow and border.
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/true);
MenuItemView* parent_item = item->GetParentMenuItem();
SubmenuView* sub_menu = parent_item->GetSubmenu();
parent_item->SetBoundsRect(parent_bounds);
MenuHost::InitParams params;
params.parent = owner();
params.bounds = parent_item->bounds();
params.do_capture = false;
sub_menu->ShowAt(params);
gfx::Rect final_bounds = CalculateBubbleMenuBounds(options, item);
final_bounds.Inset(border_and_shadow_insets);
sub_menu->Close();
EXPECT_TRUE(options.monitor_bounds.Contains(final_bounds))
<< options.monitor_bounds.ToString() << " does not contain "
<< final_bounds.ToString();
}
protected:
void SetPendingStateItem(MenuItemView* item) {
menu_controller_->pending_state_.item = item;
menu_controller_->pending_state_.submenu_open = true;
}
void SetState(MenuItemView* item) {
menu_controller_->state_.item = item;
menu_controller_->state_.submenu_open = true;
}
void ResetSelection() {
menu_controller_->SetSelection(
nullptr, MenuController::SELECTION_EXIT |
MenuController::SELECTION_UPDATE_IMMEDIATELY);
}
void IncrementSelection() {
menu_controller_->IncrementSelection(
MenuController::INCREMENT_SELECTION_DOWN);
}
void DecrementSelection() {
menu_controller_->IncrementSelection(
MenuController::INCREMENT_SELECTION_UP);
}
void DestroyMenuControllerOnMenuClosed(TestMenuControllerDelegate* delegate) {
// Unretained() is safe here as the test should outlive the delegate. If not
// we want to know.
delegate->set_on_menu_closed_callback(base::BindRepeating(
&MenuControllerTest::DestroyMenuController, base::Unretained(this)));
}
MenuItemView* FindInitialSelectableMenuItemDown(MenuItemView* parent) {
return menu_controller_->FindInitialSelectableMenuItem(
parent, MenuController::INCREMENT_SELECTION_DOWN);
}
MenuItemView* FindInitialSelectableMenuItemUp(MenuItemView* parent) {
return menu_controller_->FindInitialSelectableMenuItem(
parent, MenuController::INCREMENT_SELECTION_UP);
}
internal::MenuControllerDelegate* GetCurrentDelegate() {
return menu_controller_->delegate_;
}
bool IsShowing() { return menu_controller_->showing_; }
MenuHost* GetMenuHost(SubmenuView* submenu) { return submenu->host_; }
MenuHostRootView* CreateMenuHostRootView(MenuHost* host) {
return static_cast<MenuHostRootView*>(host->CreateRootView());
}
void MenuHostOnDragWillStart(MenuHost* host) { host->OnDragWillStart(); }
void MenuHostOnDragComplete(MenuHost* host) { host->OnDragComplete(); }
void SelectByChar(char16_t character) {
menu_controller_->SelectByChar(character);
}
void SetDropMenuItem(MenuItemView* target,
MenuDelegate::DropPosition position) {
menu_controller_->SetDropMenuItem(target, position);
}
void SetComboboxType(MenuController::ComboboxType combobox_type) {
menu_controller_->set_combobox_type(combobox_type);
}
void SetSelectionOnPointerDown(SubmenuView* source,
const ui::LocatedEvent* event) {
menu_controller_->SetSelectionOnPointerDown(source, event);
}
// Note that coordinates of events passed to MenuController must be in that of
// the MenuScrollViewContainer.
void ProcessGestureEvent(SubmenuView* source, ui::GestureEvent& event) {
menu_controller_->OnGestureEvent(source, &event);
}
void ProcessMousePressed(SubmenuView* source, const ui::MouseEvent& event) {
menu_controller_->OnMousePressed(source, event);
}
void ProcessMouseDragged(SubmenuView* source, const ui::MouseEvent& event) {
menu_controller_->OnMouseDragged(source, event);
}
void ProcessMouseMoved(SubmenuView* source, const ui::MouseEvent& event) {
menu_controller_->OnMouseMoved(source, event);
}
void ProcessMouseReleased(SubmenuView* source, const ui::MouseEvent& event) {
menu_controller_->OnMouseReleased(source, event);
}
void Accept(MenuItemView* item, int event_flags) {
menu_controller_->Accept(item, event_flags);
views::test::WaitForMenuClosureAnimation();
}
// Causes the |menu_controller_| to begin dragging. Use TestDragDropClient to
// avoid nesting message loops.
void StartDrag() {
const gfx::Point location;
menu_controller_->state_.item = menu_item()->GetSubmenu()->GetMenuItemAt(0);
menu_controller_->StartDrag(
menu_item()->GetSubmenu()->GetMenuItemAt(0)->CreateSubmenu(), location);
}
void SetUpMenuControllerForCalculateBounds(const MenuBoundsOptions& options) {
menu_controller_->state_.anchor = options.menu_anchor;
menu_controller_->state_.initial_bounds = options.anchor_bounds;
menu_controller_->state_.monitor_bounds = options.monitor_bounds;
menu_item_->SetActualMenuPosition(options.menu_position);
menu_item_->GetSubmenu()->GetScrollViewContainer()->SetPreferredSize(
options.menu_size);
}
GestureTestWidget* owner() { return owner_.get(); }
ui::test::EventGenerator* event_generator() { return event_generator_.get(); }
TestMenuItemViewShown* menu_item() { return menu_item_.get(); }
TestMenuDelegate* menu_delegate() { return menu_delegate_.get(); }
TestMenuControllerDelegate* menu_controller_delegate() {
return menu_controller_delegate_.get();
}
MenuController* menu_controller() { return menu_controller_; }
const MenuItemView* pending_state_item() const {
return menu_controller_->pending_state_.item;
}
MenuController::ExitType menu_exit_type() const {
return menu_controller_->exit_type_;
}
// Adds a menu item having buttons as children and returns it. If
// `single_child` is true, the hosting menu item has only one child button.
MenuItemView* AddButtonMenuItems(bool single_child) {
menu_item()->SetBounds(0, 0, 200, 300);
MenuItemView* item_view = menu_item()->AppendMenuItem(5, u"Five");
const size_t children_count = single_child ? 1 : 3;
for (size_t i = 0; i < children_count; ++i) {
LabelButton* button =
new LabelButton(Button::PressedCallback(), u"Label");
// This is an in-menu button. Hence it must be always focusable.
button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
item_view->AddChildView(button);
}
MenuHost::InitParams params;
params.parent = owner();
params.bounds = menu_item()->bounds();
params.do_capture = false;
menu_item()->GetSubmenu()->ShowAt(params);
return item_view;
}
void DestroyMenuItem() { menu_item_.reset(); }
Button* GetHotButton() { return menu_controller_->hot_button_; }
void SetHotTrackedButton(Button* hot_button) {
menu_controller_->SetHotTrackedButton(hot_button);
}
void ExitMenuRun() {
menu_controller_->SetExitType(MenuController::ExitType::kOutermost);
menu_controller_->ExitTopMostMenu();
}
void DestroyMenuController() {
if (!menu_controller_)
return;
if (!owner_->IsClosed())
owner_->RemoveObserver(menu_controller_);
menu_controller_->showing_ = false;
menu_controller_->owner_ = nullptr;
delete menu_controller_;
menu_controller_ = nullptr;
}
int CountOwnerOnGestureEvent() const { return owner_->gesture_count(); }
bool SelectionWraps() {
return MenuConfig::instance().arrow_key_selection_wraps;
}
void OpenMenu(MenuItemView* parent) {
menu_controller_->OpenMenuImpl(parent, true);
}
gfx::Insets GetBorderAndShadowInsets(bool is_submenu) {
const MenuConfig& menu_config = MenuConfig::instance();
int elevation = menu_config.touchable_menu_shadow_elevation;
BubbleBorder::Shadow shadow_type = BubbleBorder::STANDARD_SHADOW;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Increase the submenu shadow elevation and change the shadow style to
// ChromeOS system UI shadow style when using Ash System UI layout.
if (menu_controller_->use_ash_system_ui_layout()) {
if (is_submenu)
elevation = menu_config.touchable_submenu_shadow_elevation;
shadow_type = BubbleBorder::CHROMEOS_SYSTEM_UI_SHADOW;
}
#endif
return BubbleBorder::GetBorderAndShadowInsets(elevation, shadow_type);
}
private:
void Init() {
owner_ = std::make_unique<GestureTestWidget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
owner_->Init(std::move(params));
event_generator_ =
std::make_unique<ui::test::EventGenerator>(GetRootWindow(owner()));
owner_->Show();
SetupMenuItem();
SetupMenuController();
}
void SetupMenuItem() {
menu_delegate_ = std::make_unique<TestMenuDelegate>();
menu_item_ = std::make_unique<TestMenuItemViewShown>(menu_delegate_.get());
menu_item_->AppendMenuItem(1, u"One");
menu_item_->AppendMenuItem(2, u"Two");
menu_item_->AppendMenuItem(3, u"Three");
menu_item_->AppendMenuItem(4, u"Four");
}
void SetupMenuController() {
menu_controller_delegate_ = std::make_unique<TestMenuControllerDelegate>();
const bool for_drop = false;
menu_controller_ =
new MenuController(for_drop, menu_controller_delegate_.get());
menu_controller_->owner_ = owner_.get();
menu_controller_->showing_ = true;
menu_controller_->SetSelection(
menu_item_.get(), MenuController::SELECTION_UPDATE_IMMEDIATELY);
menu_item_->SetController(menu_controller_);
}
// Not owned.
raw_ptr<ReleaseRefTestViewsDelegate> test_views_delegate_ = nullptr;
std::unique_ptr<GestureTestWidget> owner_;
std::unique_ptr<ui::test::EventGenerator> event_generator_;
std::unique_ptr<TestMenuItemViewShown> menu_item_;
std::unique_ptr<TestMenuControllerDelegate> menu_controller_delegate_;
std::unique_ptr<TestMenuDelegate> menu_delegate_;
raw_ptr<MenuController> menu_controller_ = nullptr;
};
INSTANTIATE_TEST_SUITE_P(All, MenuControllerTest, testing::Bool());
#if defined(USE_AURA)
// Tests that an event targeter which blocks events will be honored by the menu
// event dispatcher.
TEST_F(MenuControllerTest, EventTargeter) {
{
// With the aura::NullWindowTargeter instantiated and assigned we expect
// the menu to not handle the key event.
aura::ScopedWindowTargeter scoped_targeter(
GetRootWindow(owner()), std::make_unique<aura::NullWindowTargeter>());
PressKey(ui::VKEY_ESCAPE);
EXPECT_EQ(MenuController::ExitType::kNone, menu_exit_type());
}
// Now that the targeter has been destroyed, expect to exit the menu
// normally when hitting escape.
TestAsyncEscapeKey();
EXPECT_EQ(MenuController::ExitType::kAll, menu_exit_type());
}
#endif // defined(USE_AURA)
#if defined(USE_OZONE_PLATFORM_X11)
// Tests that touch event ids are released correctly. See crbug.com/439051 for
// details. When the ids aren't managed correctly, we get stuck down touches.
TEST_F(MenuControllerTest, TouchIdsReleasedCorrectly) {
// Run this test only for X11.
if (ui::OzonePlatform::GetPlatformNameForTest() != "x11")
GTEST_SKIP();
TestEventHandler test_event_handler;
GetRootWindow(owner())->AddPreTargetHandler(&test_event_handler);
std::vector<int> devices;
devices.push_back(1);
ui::SetUpTouchDevicesForTest(devices);
event_generator()->PressTouchId(0);
event_generator()->PressTouchId(1);
event_generator()->ReleaseTouchId(0);
menu_controller()->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
MenuControllerTest::ReleaseTouchId(1);
TestAsyncEscapeKey();
EXPECT_EQ(MenuController::ExitType::kAll, menu_exit_type());
EXPECT_EQ(0, test_event_handler.outstanding_touches());
GetRootWindow(owner())->RemovePreTargetHandler(&test_event_handler);
}
#endif // defined(USE_OZONE_PLATFORM_X11)
// Tests that initial selected menu items are correct when items are enabled or
// disabled.
TEST_F(MenuControllerTest, InitialSelectedItem) {
// Leave items "Two", "Three", and "Four" enabled.
menu_item()->GetSubmenu()->GetMenuItemAt(0)->SetEnabled(false);
// The first selectable item should be item "Two".
MenuItemView* first_selectable =
FindInitialSelectableMenuItemDown(menu_item());
ASSERT_NE(nullptr, first_selectable);
EXPECT_EQ(2, first_selectable->GetCommand());
// The last selectable item should be item "Four".
MenuItemView* last_selectable = FindInitialSelectableMenuItemUp(menu_item());
ASSERT_NE(nullptr, last_selectable);
EXPECT_EQ(4, last_selectable->GetCommand());
// Leave items "One" and "Two" enabled.
menu_item()->GetSubmenu()->GetMenuItemAt(0)->SetEnabled(true);
menu_item()->GetSubmenu()->GetMenuItemAt(1)->SetEnabled(true);
menu_item()->GetSubmenu()->GetMenuItemAt(2)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(3)->SetEnabled(false);
// The first selectable item should be item "One".
first_selectable = FindInitialSelectableMenuItemDown(menu_item());
ASSERT_NE(nullptr, first_selectable);
EXPECT_EQ(1, first_selectable->GetCommand());
// The last selectable item should be item "Two".
last_selectable = FindInitialSelectableMenuItemUp(menu_item());
ASSERT_NE(nullptr, last_selectable);
EXPECT_EQ(2, last_selectable->GetCommand());
// Leave only a single item "One" enabled.
menu_item()->GetSubmenu()->GetMenuItemAt(0)->SetEnabled(true);
menu_item()->GetSubmenu()->GetMenuItemAt(1)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(2)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(3)->SetEnabled(false);
// The first selectable item should be item "One".
first_selectable = FindInitialSelectableMenuItemDown(menu_item());
ASSERT_NE(nullptr, first_selectable);
EXPECT_EQ(1, first_selectable->GetCommand());
// The last selectable item should be item "One".
last_selectable = FindInitialSelectableMenuItemUp(menu_item());
ASSERT_NE(nullptr, last_selectable);
EXPECT_EQ(1, last_selectable->GetCommand());
// Leave only a single item "Three" enabled.
menu_item()->GetSubmenu()->GetMenuItemAt(0)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(1)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(2)->SetEnabled(true);
menu_item()->GetSubmenu()->GetMenuItemAt(3)->SetEnabled(false);
// The first selectable item should be item "Three".
first_selectable = FindInitialSelectableMenuItemDown(menu_item());
ASSERT_NE(nullptr, first_selectable);
EXPECT_EQ(3, first_selectable->GetCommand());
// The last selectable item should be item "Three".
last_selectable = FindInitialSelectableMenuItemUp(menu_item());
ASSERT_NE(nullptr, last_selectable);
EXPECT_EQ(3, last_selectable->GetCommand());
// Leave only a single item ("Two") selected. It should be the first and the
// last selectable item.
menu_item()->GetSubmenu()->GetMenuItemAt(0)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(1)->SetEnabled(true);
menu_item()->GetSubmenu()->GetMenuItemAt(2)->SetEnabled(false);
menu_item()->GetSubmenu()->GetMenuItemAt(3)->SetEnabled(false);
first_selectable = FindInitialSelectableMenuItemDown(menu_item());
ASSERT_NE(nullptr, first_selectable);
EXPECT_EQ(2, first_selectable->GetCommand());
last_selectable = FindInitialSelectableMenuItemUp(menu_item());
ASSERT_NE(nullptr, last_selectable);
EXPECT_EQ(2, last_selectable->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
// Verifies that the context menu bubble should prioritize its cached menu
// position (above or below the anchor) after its size updates
// (https://crbug.com/1126244).
TEST_F(MenuControllerTest, VerifyMenuBubblePositionAfterSizeChanges) {
constexpr gfx::Rect monitor_bounds(0, 0, 500, 500);
constexpr gfx::Size menu_size(100, 200);
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/false);
// Calculate the suitable anchor point to ensure that if the menu shows below
// the anchor point, the bottom of the menu should be one pixel off the
// bottom of the display. It means that there is insufficient space for the
// menu below the anchor.
const gfx::Point anchor_point(monitor_bounds.width() / 2,
monitor_bounds.bottom() + 1 -
menu_size.height() +
border_and_shadow_insets.top());
MenuBoundsOptions options;
options.menu_anchor = MenuAnchorPosition::kBubbleRight;
options.monitor_bounds = monitor_bounds;
options.anchor_bounds = gfx::Rect(anchor_point, gfx::Size());
// Case 1: There is insufficient space for the menu below `anchor_point` and
// there is no cached menu position. The menu should show above the anchor.
{
options.menu_size = menu_size;
ASSERT_GT(options.anchor_bounds.y() - border_and_shadow_insets.top() +
menu_size.height(),
monitor_bounds.bottom());
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
// Case 2: There is insufficient space for the menu below `anchor_point`. The
// cached position is below the anchor. The menu should show above the anchor.
{
options.menu_size = menu_size;
options.menu_position = MenuItemView::MenuPosition::kBelowBounds;
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
// Case 3: There is enough space for the menu below `anchor_point`. The cached
// menu position is above the anchor. The menu should show above the anchor.
{
// Shrink the menu size. Verify that there is enough space below the anchor
// point now.
constexpr gfx::Size updated_size(menu_size.width(), menu_size.height() / 2);
options.menu_size = updated_size;
EXPECT_LE(options.anchor_bounds.y() - border_and_shadow_insets.top() +
updated_size.height(),
monitor_bounds.bottom());
options.menu_position = MenuItemView::MenuPosition::kAboveBounds;
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
}
// Verifies that the context menu bubble position,
// MenuAnchorPosition::kBubbleBottomRight, does not shift as items are removed.
// The menu position will shift if items are added and the menu no longer fits
// in its previous position.
TEST_F(MenuControllerTest, VerifyContextMenuBubblePositionAfterSizeChanges) {
constexpr gfx::Rect kMonitorBounds(0, 0, 500, 500);
constexpr gfx::Size kMenuSize(100, 200);
const gfx::Insets border_and_shadow_insets =
GetBorderAndShadowInsets(/*is_submenu=*/false);
// Calculate the suitable anchor point to ensure that if the menu shows below
// the anchor point, the bottom of the menu should be one pixel off the
// bottom of the display. It means that there is insufficient space for the
// menu below the anchor.
const gfx::Point anchor_point(kMonitorBounds.width() / 2,
kMonitorBounds.bottom() + 1 -
kMenuSize.height() +
border_and_shadow_insets.top());
MenuBoundsOptions options;
options.menu_anchor = MenuAnchorPosition::kBubbleBottomRight;
options.monitor_bounds = kMonitorBounds;
options.anchor_bounds = gfx::Rect(anchor_point, gfx::Size());
// Case 1: There is insufficient space for the menu below `anchor_point` and
// there is no cached menu position. The menu should show above the anchor.
{
options.menu_size = kMenuSize;
ASSERT_GT(options.anchor_bounds.y() - border_and_shadow_insets.top() +
kMenuSize.height(),
kMonitorBounds.bottom());
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
// Case 2: There is insufficient space for the menu below `anchor_point`. The
// cached position is below the anchor. The menu should show above the anchor
// point.
{
options.menu_position = MenuItemView::MenuPosition::kBelowBounds;
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
// Case 3: There is enough space for the menu below `anchor_point`. The cached
// menu position is above the anchor. The menu should show above the anchor.
{
// Shrink the menu size. Verify that there is enough space below the anchor
// point now.
constexpr gfx::Size kUpdatedSize(kMenuSize.width(), kMenuSize.height() / 2);
options.menu_size = kUpdatedSize;
EXPECT_LE(options.anchor_bounds.y() - border_and_shadow_insets.top() +
kUpdatedSize.height(),
kMonitorBounds.bottom());
options.menu_position = MenuItemView::MenuPosition::kAboveBounds;
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kAboveBounds,
menu_item()->ActualMenuPosition());
}
// Case 4: There is enough space for the menu below `anchor_point`. The cached
// menu position is below the anchor. The menu should show below the anchor.
{
options.menu_position = MenuItemView::MenuPosition::kBelowBounds;
CalculateBubbleMenuBounds(options);
EXPECT_EQ(MenuItemView::MenuPosition::kBelowBounds,
menu_item()->ActualMenuPosition());
}
}
// Tests that opening the menu and pressing 'Home' selects the first menu item.
TEST_F(MenuControllerTest, FirstSelectedItem) {
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(0));
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Select the first menu item.
DispatchKey(ui::VKEY_HOME);
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Fake initial root item selection and submenu showing.
SetPendingStateItem(menu_item());
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Select the first menu item.
DispatchKey(ui::VKEY_HOME);
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Select the last item.
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(3));
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Select the first menu item.
DispatchKey(ui::VKEY_HOME);
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
// Tests that opening the menu and pressing 'End' selects the last enabled menu
// item.
TEST_F(MenuControllerTest, LastSelectedItem) {
// Fake initial root item selection and submenu showing.
SetPendingStateItem(menu_item());
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Select the last menu item.
DispatchKey(ui::VKEY_END);
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Select the last item.
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(3));
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Select the last menu item.
DispatchKey(ui::VKEY_END);
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Select the first item.
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(0));
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Select the last menu item.
DispatchKey(ui::VKEY_END);
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
// MenuController tests which set expectations about how menu item selection
// behaves should verify test cases work as intended for all supported selection
// mechanisms.
class MenuControllerSelectionTest : public MenuControllerTest {
public:
MenuControllerSelectionTest() = default;
~MenuControllerSelectionTest() override = default;
protected:
// Models a mechanism by which menu item selection can be incremented and/or
// decremented.
struct SelectionMechanism {
base::RepeatingClosure IncrementSelection;
base::RepeatingClosure DecrementSelection;
};
// Returns all mechanisms by which menu item selection can be incremented
// and/or decremented.
const std::vector<SelectionMechanism>& selection_mechanisms() {
return selection_mechanisms_;
}
private:
const std::vector<SelectionMechanism> selection_mechanisms_ = {
// Updates selection via IncrementSelection()/DecrementSelection().
SelectionMechanism{
base::BindLambdaForTesting([this]() { IncrementSelection(); }),
base::BindLambdaForTesting([this]() { DecrementSelection(); })},
// Updates selection via down/up arrow keys.
SelectionMechanism{
base::BindLambdaForTesting([this]() { DispatchKey(ui::VKEY_DOWN); }),
base::BindLambdaForTesting([this]() { DispatchKey(ui::VKEY_UP); })},
// Updates selection via next/prior keys.
SelectionMechanism{
base::BindLambdaForTesting([this]() { DispatchKey(ui::VKEY_NEXT); }),
base::BindLambdaForTesting(
[this]() { DispatchKey(ui::VKEY_PRIOR); })}};
};
// Tests that opening menu and exercising various mechanisms to update selection
// iterates over enabled items.
TEST_F(MenuControllerSelectionTest, NextSelectedItem) {
for (const auto& selection_mechanism : selection_mechanisms()) {
// Disabling the item "Three" gets it skipped when using keyboard to
// navigate.
menu_item()->GetSubmenu()->GetMenuItemAt(2)->SetEnabled(false);
// Fake initial hot selection.
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(0));
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Move down in the menu.
// Select next item.
selection_mechanism.IncrementSelection.Run();
EXPECT_EQ(2, pending_state_item()->GetCommand());
// Skip disabled item.
selection_mechanism.IncrementSelection.Run();
EXPECT_EQ(4, pending_state_item()->GetCommand());
if (SelectionWraps()) {
// Wrap around.
selection_mechanism.IncrementSelection.Run();
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Move up in the menu.
// Wrap around.
selection_mechanism.DecrementSelection.Run();
EXPECT_EQ(4, pending_state_item()->GetCommand());
} else {
// Don't wrap.
selection_mechanism.IncrementSelection.Run();
EXPECT_EQ(4, pending_state_item()->GetCommand());
}
// Skip disabled item.
selection_mechanism.DecrementSelection.Run();
EXPECT_EQ(2, pending_state_item()->GetCommand());
// Select previous item.
selection_mechanism.DecrementSelection.Run();
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going
// away.
ResetSelection();
}
}
// Tests that opening menu and exercising various mechanisms to decrement
// selection selects the last enabled menu item.
TEST_F(MenuControllerSelectionTest, PreviousSelectedItem) {
for (const auto& selection_mechanism : selection_mechanisms()) {
// Disabling the item "Four" gets it skipped when using keyboard to
// navigate.
menu_item()->GetSubmenu()->GetMenuItemAt(3)->SetEnabled(false);
// Fake initial root item selection and submenu showing.
SetPendingStateItem(menu_item());
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Move up and select a previous (in our case the last enabled) item.
selection_mechanism.DecrementSelection.Run();
EXPECT_EQ(3, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going
// away.
ResetSelection();
}
}
// Tests that the APIs related to the current selected item work correctly.
TEST_F(MenuControllerTest, CurrentSelectedItem) {
SetPendingStateItem(menu_item()->GetSubmenu()->GetMenuItemAt(0));
EXPECT_EQ(1, pending_state_item()->GetCommand());
// Select the first menu-item.
DispatchKey(ui::VKEY_HOME);
EXPECT_EQ(pending_state_item(), menu_controller()->GetSelectedMenuItem());
// The API should let the submenu stay open if already so, but clear any
// selections within it.
EXPECT_TRUE(IsShowing());
EXPECT_EQ(1, pending_state_item()->GetCommand());
menu_controller()->SelectItemAndOpenSubmenu(menu_item());
EXPECT_TRUE(IsShowing());
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
// Tests that opening menu and calling SelectByChar works correctly.
TEST_F(MenuControllerTest, SelectByChar) {
SetComboboxType(MenuController::ComboboxType::kReadonly);
// Handle null character should do nothing.
SelectByChar(0);
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Handle searching for 'f'; should find "Four".
SelectByChar('f');
EXPECT_EQ(4, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
TEST_F(MenuControllerTest, SelectChildButtonView) {
AddButtonMenuItems(/*single_child=*/false);
View* buttons_view = menu_item()->GetSubmenu()->children()[4];
ASSERT_NE(nullptr, buttons_view);
Button* button1 = Button::AsButton(buttons_view->children()[0]);
ASSERT_NE(nullptr, button1);
Button* button2 = Button::AsButton(buttons_view->children()[1]);
ASSERT_NE(nullptr, button2);
Button* button3 = Button::AsButton(buttons_view->children()[2]);
ASSERT_NE(nullptr, button2);
// Handle searching for 'f'; should find "Four".
SelectByChar('f');
EXPECT_EQ(4, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_FALSE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Move selection to |button1|.
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_TRUE(button1->IsHotTracked());
EXPECT_FALSE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Move selection to |button2|.
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Move selection to |button3|.
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_FALSE(button2->IsHotTracked());
EXPECT_TRUE(button3->IsHotTracked());
// Move a mouse to hot track the |button1|.
SubmenuView* sub_menu = menu_item()->GetSubmenu();
gfx::Point location(button1->GetBoundsInScreen().CenterPoint());
View::ConvertPointFromScreen(sub_menu->GetScrollViewContainer(), &location);
ui::MouseEvent event(ui::ET_MOUSE_MOVED, location, location,
ui::EventTimeForNow(), 0, 0);
ProcessMouseMoved(sub_menu, event);
EXPECT_EQ(button1, GetHotButton());
EXPECT_TRUE(button1->IsHotTracked());
// Incrementing selection should move hot tracking to the second button (next
// after the first button).
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Increment selection twice to wrap around.
IncrementSelection();
IncrementSelection();
if (SelectionWraps())
EXPECT_EQ(1, pending_state_item()->GetCommand());
else
EXPECT_EQ(5, pending_state_item()->GetCommand());
// Clear references in menu controller to the menu item that is going away.
ResetSelection();
}
TEST_F(MenuControllerTest, DeleteChildButtonView) {
AddButtonMenuItems(/*single_child=*/false);
// Handle searching for 'f'; should find "Four".
SelectByChar('f');
EXPECT_EQ(4, pending_state_item()->GetCommand());
View* buttons_view = menu_item()->GetSubmenu()->children()[4];
ASSERT_NE(nullptr, buttons_view);
Button* button1 = Button::AsButton(buttons_view->children()[0]);
ASSERT_NE(nullptr, button1);
Button* button2 = Button::AsButton(buttons_view->children()[1]);
ASSERT_NE(nullptr, button2);
Button* button3 = Button::AsButton(buttons_view->children()[2]);
ASSERT_NE(nullptr, button2);
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_FALSE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Increment twice to move selection to |button2|.
IncrementSelection();
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Delete |button2| while it is hot-tracked.
// This should update MenuController via ViewHierarchyChanged and reset
// |hot_button_|.
delete button2;
// Incrementing selection should now set hot-tracked item to |button1|.
// It should not crash.
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_TRUE(button1->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
}
// Verifies that the child button is hot tracked after the host menu item is
// selected by `MenuController::SelectItemAndOpenSubmenu()`.
TEST_F(MenuControllerTest, ChildButtonHotTrackedAfterMenuItemSelection) {
// Add a menu item which owns a button as child.
MenuItemView* hosting_menu_item = AddButtonMenuItems(/*single_child=*/true);
ASSERT_FALSE(hosting_menu_item->IsSelected());
const Button* button = Button::AsButton(hosting_menu_item->children()[0]);
EXPECT_FALSE(button->IsHotTracked());
menu_controller()->SelectItemAndOpenSubmenu(hosting_menu_item);
EXPECT_TRUE(hosting_menu_item->IsSelected());
EXPECT_TRUE(button->IsHotTracked());
}
// Verifies that the child button of the menu item which is under mouse hovering
// is hot tracked (https://crbug.com/1135000).
TEST_F(MenuControllerTest, ChildButtonHotTrackedAfterMouseMove) {
// Add a menu item which owns a button as child.
MenuItemView* hosting_menu_item = AddButtonMenuItems(/*single_child=*/true);
const Button* button = Button::AsButton(hosting_menu_item->children()[0]);
EXPECT_FALSE(button->IsHotTracked());
SubmenuView* sub_menu = menu_item()->GetSubmenu();
gfx::Point location(button->GetBoundsInScreen().CenterPoint());
View::ConvertPointFromScreen(sub_menu->GetScrollViewContainer(), &location);
ui::MouseEvent event(ui::ET_MOUSE_MOVED, location, location,
ui::EventTimeForNow(), 0, 0);
ProcessMouseMoved(sub_menu, event);
// After the mouse moves to `button`, `button` should be hot tracked.
EXPECT_EQ(button, GetHotButton());
EXPECT_TRUE(button->IsHotTracked());
}
// Creates a menu with Button child views, simulates running a nested
// menu and tests that existing the nested run restores hot-tracked child view.
TEST_F(MenuControllerTest, ChildButtonHotTrackedWhenNested) {
AddButtonMenuItems(/*single_child=*/false);
// Handle searching for 'f'; should find "Four".
SelectByChar('f');
EXPECT_EQ(4, pending_state_item()->GetCommand());
View* buttons_view = menu_item()->GetSubmenu()->children()[4];
ASSERT_NE(nullptr, buttons_view);
Button* button1 = Button::AsButton(buttons_view->children()[0]);
ASSERT_NE(nullptr, button1);
Button* button2 = Button::AsButton(buttons_view->children()[1]);
ASSERT_NE(nullptr, button2);
Button* button3 = Button::AsButton(buttons_view->children()[2]);
ASSERT_NE(nullptr, button2);
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_FALSE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
// Increment twice to move selection to |button2|.
IncrementSelection();
IncrementSelection();
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_FALSE(button3->IsHotTracked());
EXPECT_EQ(button2, GetHotButton());
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
// |button2| should stay in hot-tracked state but menu controller should not
// track it anymore (preventing resetting hot-tracked state when changing
// selection while a nested run is active).
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_EQ(nullptr, GetHotButton());
// Setting hot-tracked button while nested should get reverted when nested
// menu run ends.
SetHotTrackedButton(button1);
EXPECT_TRUE(button1->IsHotTracked());
EXPECT_EQ(button1, GetHotButton());
// Setting the hot tracked state twice on the same button via the
// menu controller should still set the hot tracked state on the button again.
button1->SetHotTracked(false);
SetHotTrackedButton(button1);
EXPECT_TRUE(button1->IsHotTracked());
EXPECT_EQ(button1, GetHotButton());
ExitMenuRun();
EXPECT_FALSE(button1->IsHotTracked());
EXPECT_TRUE(button2->IsHotTracked());
EXPECT_EQ(button2, GetHotButton());
}
// Tests that a menu opened asynchronously, will notify its
// MenuControllerDelegate when Accept is called.
TEST_F(MenuControllerTest, AsynchronousAccept) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
MenuItemView* accepted = menu_item()->GetSubmenu()->GetMenuItemAt(0);
const int kEventFlags = 42;
Accept(accepted, kEventFlags);
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(accepted, delegate->on_menu_closed_menu());
EXPECT_EQ(kEventFlags, delegate->on_menu_closed_mouse_event_flags());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
delegate->on_menu_closed_notify_type());
}
// Tests that a menu opened asynchronously, will notify its
// MenuControllerDelegate when CancelAll is called.
TEST_F(MenuControllerTest, AsynchronousCancelAll) {
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
controller->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, delegate->on_menu_closed_menu());
EXPECT_EQ(0, delegate->on_menu_closed_mouse_event_flags());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
delegate->on_menu_closed_notify_type());
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that canceling a nested menu restores the previous
// MenuControllerDelegate, and notifies each delegate.
TEST_F(MenuControllerTest, AsynchronousNestedDelegate) {
MenuController* controller = menu_controller();
TestMenuControllerDelegate* delegate = menu_controller_delegate();
std::unique_ptr<TestMenuControllerDelegate> nested_delegate(
new TestMenuControllerDelegate());
controller->AddNestedDelegate(nested_delegate.get());
EXPECT_EQ(nested_delegate.get(), GetCurrentDelegate());
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
controller->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(delegate, GetCurrentDelegate());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(1, nested_delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, nested_delegate->on_menu_closed_menu());
EXPECT_EQ(0, nested_delegate->on_menu_closed_mouse_event_flags());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
nested_delegate->on_menu_closed_notify_type());
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that dropping within an asynchronous menu stops the menu from showing
// and does not notify the controller.
TEST_F(MenuControllerTest, AsynchronousPerformDrop) {
MenuController* controller = menu_controller();
SubmenuView* source = menu_item()->GetSubmenu();
MenuItemView* target = source->GetMenuItemAt(0);
SetDropMenuItem(target, MenuDelegate::DropPosition::kAfter);
ui::OSExchangeData drop_data;
gfx::PointF location(target->origin());
ui::DropTargetEvent target_event(drop_data, location, location,
ui::DragDropTypes::DRAG_MOVE);
auto drop_cb = controller->GetDropCallback(source, target_event);
ui::mojom::DragOperation output_drag_op = ui::mojom::DragOperation::kNone;
std::move(drop_cb).Run(target_event, output_drag_op,
/*drag_image_layer_owner=*/nullptr);
TestMenuDelegate* menu_delegate =
static_cast<TestMenuDelegate*>(target->GetDelegate());
TestMenuControllerDelegate* controller_delegate = menu_controller_delegate();
EXPECT_TRUE(menu_delegate->is_drop_performed());
EXPECT_FALSE(IsShowing());
EXPECT_EQ(0, controller_delegate->on_menu_closed_called());
}
// Tests that dragging within an asynchronous menu notifies the
// MenuControllerDelegate for shutdown.
TEST_F(MenuControllerTest, AsynchronousDragComplete) {
MenuController* controller = menu_controller();
TestDragCompleteThenDestroyOnMenuClosed();
controller->OnDragWillStart();
controller->OnDragComplete(true);
TestMenuControllerDelegate* controller_delegate = menu_controller_delegate();
EXPECT_EQ(1, controller_delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, controller_delegate->on_menu_closed_menu());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
controller_delegate->on_menu_closed_notify_type());
}
// Tests that if Cancel is called during a drag, that OnMenuClosed is still
// notified when the drag completes.
TEST_F(MenuControllerTest, AsynchronousCancelDuringDrag) {
MenuController* controller = menu_controller();
TestDragCompleteThenDestroyOnMenuClosed();
controller->OnDragWillStart();
controller->Cancel(MenuController::ExitType::kAll);
controller->OnDragComplete(true);
TestMenuControllerDelegate* controller_delegate = menu_controller_delegate();
EXPECT_EQ(1, controller_delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, controller_delegate->on_menu_closed_menu());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
controller_delegate->on_menu_closed_notify_type());
}
// Tests that if a menu is destroyed while drag operations are occurring, that
// the MenuHost does not crash as the drag completes.
TEST_F(MenuControllerTest, AsynchronousDragHostDeleted) {
SubmenuView* submenu = menu_item()->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = menu_item()->bounds();
params.do_capture = false;
submenu->ShowAt(params);
MenuHost* host = GetMenuHost(submenu);
MenuHostOnDragWillStart(host);
submenu->Close();
DestroyMenuItem();
MenuHostOnDragComplete(host);
}
// Tests that getting the drop callback stops the menu from showing and
// does not notify the controller.
TEST_F(MenuControllerTest, AsycDropCallback) {
MenuController* controller = menu_controller();
SubmenuView* source = menu_item()->GetSubmenu();
MenuItemView* target = source->GetMenuItemAt(0);
SetDropMenuItem(target, MenuDelegate::DropPosition::kAfter);
ui::OSExchangeData drop_data;
gfx::PointF location(target->origin());
ui::DropTargetEvent target_event(drop_data, location, location,
ui::DragDropTypes::DRAG_MOVE);
auto drop_cb = controller->GetDropCallback(source, target_event);
TestMenuDelegate* menu_delegate =
static_cast<TestMenuDelegate*>(target->GetDelegate());
TestMenuControllerDelegate* controller_delegate = menu_controller_delegate();
EXPECT_FALSE(menu_delegate->is_drop_performed());
EXPECT_FALSE(IsShowing());
EXPECT_EQ(0, controller_delegate->on_menu_closed_called());
ui::mojom::DragOperation output_drag_op;
std::move(drop_cb).Run(target_event, output_drag_op,
/*drag_image_layer_owner=*/nullptr);
EXPECT_TRUE(menu_delegate->is_drop_performed());
}
// Widget destruction and cleanup occurs on the MessageLoop after the
// MenuController has been destroyed. A MenuHostRootView should not attempt to
// access a destroyed MenuController. This test should not cause a crash.
TEST_F(MenuControllerTest, HostReceivesInputBeforeDestruction) {
SubmenuView* submenu = menu_item()->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = menu_item()->bounds();
params.do_capture = false;
submenu->ShowAt(params);
gfx::Point location(submenu->bounds().bottom_right());
location.Offset(1, 1);
MenuHost* host = GetMenuHost(submenu);
// Normally created as the full Widget is brought up. Explicitly created here
// for testing.
std::unique_ptr<MenuHostRootView> root_view(CreateMenuHostRootView(host));
DestroyMenuController();
ui::MouseEvent event(ui::ET_MOUSE_MOVED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
// This should not attempt to access the destroyed MenuController and should
// not crash.
root_view->OnMouseMoved(event);
}
// Tests that an asynchronous menu nested within an asynchronous menu closes
// both menus, and notifies both delegates.
TEST_F(MenuControllerTest, DoubleAsynchronousNested) {
MenuController* controller = menu_controller();
TestMenuControllerDelegate* delegate = menu_controller_delegate();
std::unique_ptr<TestMenuControllerDelegate> nested_delegate(
new TestMenuControllerDelegate());
// Nested run
controller->AddNestedDelegate(nested_delegate.get());
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
controller->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(1, nested_delegate->on_menu_closed_called());
}
// Tests that setting send_gesture_events_to_owner flag forwards gesture events
// to owner and the forwarding stops when the current gesture sequence ends.
TEST_F(MenuControllerTest, PreserveGestureForOwner) {
MenuController* controller = menu_controller();
MenuItemView* item = menu_item();
controller->Run(owner(), nullptr, item, gfx::Rect(),
MenuAnchorPosition::kBottomCenter, false, false);
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = true;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_left().x(),
sub_menu->bounds().bottom_left().y() + 10);
ui::GestureEvent event(location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
// Gesture events should not be forwarded if the flag is not set.
EXPECT_EQ(CountOwnerOnGestureEvent(), 0);
EXPECT_FALSE(controller->send_gesture_events_to_owner());
controller->OnGestureEvent(sub_menu, &event);
EXPECT_EQ(CountOwnerOnGestureEvent(), 0);
// The menu's owner should receive gestures triggered outside the menu.
controller->set_send_gesture_events_to_owner(true);
controller->OnGestureEvent(sub_menu, &event);
EXPECT_EQ(CountOwnerOnGestureEvent(), 1);
ui::GestureEvent event2(location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
controller->OnGestureEvent(sub_menu, &event2);
EXPECT_EQ(CountOwnerOnGestureEvent(), 2);
// ET_GESTURE_END resets the |send_gesture_events_to_owner_| flag, so further
// gesture events should not be sent to the owner.
controller->OnGestureEvent(sub_menu, &event2);
EXPECT_EQ(CountOwnerOnGestureEvent(), 2);
}
#if defined(USE_AURA)
// Tests that setting `send_gesture_events_to_owner` flag forwards gesture
// events to the NativeView specified for gestures and not the owner's
// NativeView.
TEST_F(MenuControllerTest, ForwardsEventsToNativeViewForGestures) {
aura::test::EventCountDelegate child_delegate;
auto child_window = std::make_unique<aura::Window>(&child_delegate);
child_window->Init(ui::LAYER_TEXTURED);
owner()->GetNativeView()->AddChild(child_window.get());
MenuController* controller = menu_controller();
MenuItemView* item = menu_item();
// Ensure menu is closed before running with the menu with `child_window` as
// the NativeView for gestures.
controller->Cancel(MenuController::ExitType::kAll);
controller->Run(owner(), nullptr, item, gfx::Rect(),
MenuAnchorPosition::kBottomCenter, false, false,
child_window.get());
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = false;
params.native_view_for_gestures = child_window.get();
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_left().x(),
sub_menu->bounds().bottom_left().y() + 10);
ui::GestureEvent event(location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
// Gesture events should not be forwarded to either the `child_window` or the
// hosts native window if the flag is not set.
EXPECT_EQ(0, CountOwnerOnGestureEvent());
EXPECT_EQ(0, child_delegate.GetGestureCountAndReset());
EXPECT_FALSE(controller->send_gesture_events_to_owner());
controller->OnGestureEvent(sub_menu, &event);
EXPECT_EQ(0, CountOwnerOnGestureEvent());
EXPECT_EQ(0, child_delegate.GetGestureCountAndReset());
// The `child_window` should receive gestures triggered outside the menu.
controller->set_send_gesture_events_to_owner(true);
controller->OnGestureEvent(sub_menu, &event);
EXPECT_EQ(0, CountOwnerOnGestureEvent());
EXPECT_EQ(1, child_delegate.GetGestureCountAndReset());
ui::GestureEvent event2(location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
controller->OnGestureEvent(sub_menu, &event2);
EXPECT_EQ(0, CountOwnerOnGestureEvent());
EXPECT_EQ(1, child_delegate.GetGestureCountAndReset());
// ET_GESTURE_END resets the `send_gesture_events_to_owner_` flag, so further
// gesture events should not be sent to the `child_window`.
controller->OnGestureEvent(sub_menu, &event2);
EXPECT_EQ(0, CountOwnerOnGestureEvent());
EXPECT_EQ(0, child_delegate.GetGestureCountAndReset());
}
#endif
// Tests that touch outside menu does not closes the menu when forwarding
// gesture events to owner.
TEST_F(MenuControllerTest, NoTouchCloseWhenSendingGesturesToOwner) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
// Owner wants the gesture events.
controller->set_send_gesture_events_to_owner(true);
// Show a sub menu and touch outside of it.
MenuItemView* item = menu_item();
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = false;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_right());
location.Offset(1, 1);
ui::TouchEvent touch_event(
ui::ET_TOUCH_PRESSED, location, ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 0));
controller->OnTouchEvent(sub_menu, &touch_event);
// Menu should still be visible.
EXPECT_TRUE(IsShowing());
// The current gesture sequence ends.
ui::GestureEvent gesture_end_event(
location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
controller->OnGestureEvent(sub_menu, &gesture_end_event);
// Touch outside again and menu should be closed.
controller->OnTouchEvent(sub_menu, &touch_event);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(IsShowing());
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that a nested menu does not crash when trying to repost events that
// occur outside of the bounds of the menu. Instead a proper shutdown should
// occur.
TEST_F(MenuControllerTest, AsynchronousRepostEvent) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
TestMenuControllerDelegate* delegate = menu_controller_delegate();
std::unique_ptr<TestMenuControllerDelegate> nested_delegate(
new TestMenuControllerDelegate());
controller->AddNestedDelegate(nested_delegate.get());
EXPECT_EQ(nested_delegate.get(), GetCurrentDelegate());
MenuItemView* item = menu_item();
controller->Run(owner(), nullptr, item, gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
// Show a sub menu to target with a pointer selection. However have the event
// occur outside of the bounds of the entire menu.
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = false;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_right());
location.Offset(1, 1);
ui::MouseEvent event(ui::ET_MOUSE_PRESSED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
// When attempting to select outside of all menus this should lead to a
// shutdown. This should not crash while attempting to repost the event.
SetSelectionOnPointerDown(sub_menu, &event);
views::test::WaitForMenuClosureAnimation();
EXPECT_EQ(delegate, GetCurrentDelegate());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(1, nested_delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, nested_delegate->on_menu_closed_menu());
EXPECT_EQ(0, nested_delegate->on_menu_closed_mouse_event_flags());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
nested_delegate->on_menu_closed_notify_type());
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that an asynchronous menu reposts touch events that occur outside of
// the bounds of the menu, and that the menu closes.
TEST_F(MenuControllerTest, AsynchronousTouchEventRepostEvent) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
TestMenuControllerDelegate* delegate = menu_controller_delegate();
// Show a sub menu to target with a touch event. However have the event occur
// outside of the bounds of the entire menu.
MenuItemView* item = menu_item();
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = false;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_right());
location.Offset(1, 1);
ui::TouchEvent event(ui::ET_TOUCH_PRESSED, location, ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 0));
controller->OnTouchEvent(sub_menu, &event);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(IsShowing());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, delegate->on_menu_closed_menu());
EXPECT_EQ(0, delegate->on_menu_closed_mouse_event_flags());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
delegate->on_menu_closed_notify_type());
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that having the MenuController deleted during RepostEvent does not
// cause a crash. ASAN bots should not detect use-after-free in MenuController.
TEST_F(MenuControllerTest, AsynchronousRepostEventDeletesController) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
std::unique_ptr<TestMenuControllerDelegate> nested_delegate(
new TestMenuControllerDelegate());
controller->AddNestedDelegate(nested_delegate.get());
EXPECT_EQ(nested_delegate.get(), GetCurrentDelegate());
MenuItemView* item = menu_item();
controller->Run(owner(), nullptr, item, gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
// Show a sub menu to target with a pointer selection. However have the event
// occur outside of the bounds of the entire menu.
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = true;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().bottom_right());
location.Offset(1, 1);
ui::MouseEvent event(ui::ET_MOUSE_PRESSED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
// This will lead to MenuController being deleted during the event repost.
// The remainder of this test, and TearDown should not crash.
DestroyMenuControllerOnMenuClosed(nested_delegate.get());
// When attempting to select outside of all menus this should lead to a
// shutdown. This should not crash while attempting to repost the event.
SetSelectionOnPointerDown(sub_menu, &event);
views::test::WaitForMenuClosureAnimation();
// Close to remove observers before test TearDown
sub_menu->Close();
EXPECT_EQ(1, nested_delegate->on_menu_closed_called());
}
// Tests that having the MenuController deleted during OnGestureEvent does not
// cause a crash. ASAN bots should not detect use-after-free in MenuController.
TEST_F(MenuControllerTest, AsynchronousGestureDeletesController) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
std::unique_ptr<TestMenuControllerDelegate> nested_delegate(
new TestMenuControllerDelegate());
controller->AddNestedDelegate(nested_delegate.get());
EXPECT_EQ(nested_delegate.get(), GetCurrentDelegate());
MenuItemView* item = menu_item();
controller->Run(owner(), nullptr, item, gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
// Show a sub menu to target with a tap event.
SubmenuView* sub_menu = item->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = true;
sub_menu->ShowAt(params);
gfx::Point location(sub_menu->bounds().CenterPoint());
ui::GestureEvent event(location.x(), location.y(), 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP));
// This will lead to MenuController being deleted during the processing of the
// gesture event. The remainder of this test, and TearDown should not crash.
DestroyMenuControllerOnMenuClosed(nested_delegate.get());
controller->OnGestureEvent(sub_menu, &event);
views::test::WaitForMenuClosureAnimation();
// Close to remove observers before test TearDown
sub_menu->Close();
EXPECT_EQ(1, nested_delegate->on_menu_closed_called());
}
// Test that the menu is properly placed where it best fits.
TEST_F(MenuControllerTest, CalculateMenuBoundsBestFitTest) {
MenuBoundsOptions options;
gfx::Rect expected;
const bool ignore_screen_bounds_for_menus =
ShouldIgnoreScreenBoundsForMenus();
// Fits in all locations -> placed below.
options.anchor_bounds =
gfx::Rect(options.menu_size.width(), options.menu_size.height(), 0, 0);
options.monitor_bounds =
gfx::Rect(0, 0, options.anchor_bounds.right() + options.menu_size.width(),
options.anchor_bounds.bottom() + options.menu_size.height());
expected =
gfx::Rect(options.anchor_bounds.x(), options.anchor_bounds.bottom(),
options.menu_size.width(), options.menu_size.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Fits above and to both sides -> placed above.
options.anchor_bounds =
gfx::Rect(options.menu_size.width(), options.menu_size.height(), 0, 0);
options.monitor_bounds =
gfx::Rect(0, 0, options.anchor_bounds.right() + options.menu_size.width(),
options.anchor_bounds.bottom());
if (ignore_screen_bounds_for_menus) {
expected = gfx::Rect(options.anchor_bounds.origin(), options.menu_size);
} else {
expected = gfx::Rect(options.anchor_bounds.x(),
options.anchor_bounds.y() - options.menu_size.height(),
options.menu_size.width(), options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Fits on both sides, prefer right -> placed right.
options.anchor_bounds = gfx::Rect(options.menu_size.width(),
options.menu_size.height() / 2, 0, 0);
options.monitor_bounds =
gfx::Rect(0, 0, options.anchor_bounds.right() + options.menu_size.width(),
options.menu_size.height());
if (ignore_screen_bounds_for_menus) {
expected = gfx::Rect(options.anchor_bounds.origin(), options.menu_size);
} else {
expected =
gfx::Rect(options.anchor_bounds.right(),
options.monitor_bounds.bottom() - options.menu_size.height(),
options.menu_size.width(), options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Fits only on left -> placed left.
options.anchor_bounds = gfx::Rect(options.menu_size.width(),
options.menu_size.height() / 2, 0, 0);
options.monitor_bounds = gfx::Rect(0, 0, options.anchor_bounds.right(),
options.menu_size.height());
if (ignore_screen_bounds_for_menus) {
expected = gfx::Rect(options.anchor_bounds.origin(), options.menu_size);
} else {
expected =
gfx::Rect(options.anchor_bounds.x() - options.menu_size.width(),
options.monitor_bounds.bottom() - options.menu_size.height(),
options.menu_size.width(), options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Fits on both sides, prefer left -> placed left.
options.menu_anchor = MenuAnchorPosition::kTopRight;
options.anchor_bounds = gfx::Rect(options.menu_size.width(),
options.menu_size.height() / 2, 0, 0);
options.monitor_bounds =
gfx::Rect(0, 0, options.anchor_bounds.right() + options.menu_size.width(),
options.menu_size.height());
if (ignore_screen_bounds_for_menus) {
expected =
gfx::Rect({options.anchor_bounds.right() - options.menu_size.width(),
options.anchor_bounds.origin().y()},
options.menu_size);
} else {
expected =
gfx::Rect(options.anchor_bounds.x() - options.menu_size.width(),
options.monitor_bounds.bottom() - options.menu_size.height(),
options.menu_size.width(), options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Fits only on right -> placed right.
options.anchor_bounds = gfx::Rect(0, options.menu_size.height() / 2, 0, 0);
options.monitor_bounds =
gfx::Rect(0, 0, options.anchor_bounds.right() + options.menu_size.width(),
options.menu_size.height());
if (ignore_screen_bounds_for_menus) {
expected =
gfx::Rect({options.anchor_bounds.right() - options.menu_size.width(),
options.anchor_bounds.origin().y()},
options.menu_size);
} else {
expected =
gfx::Rect(options.anchor_bounds.right(),
options.monitor_bounds.bottom() - options.menu_size.height(),
options.menu_size.width(), options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
}
// Tests that the menu is properly placed according to its anchor.
TEST_F(MenuControllerTest, CalculateMenuBoundsAnchorTest) {
MenuBoundsOptions options;
gfx::Rect expected;
options.menu_anchor = MenuAnchorPosition::kTopLeft;
expected =
gfx::Rect(options.anchor_bounds.x(), options.anchor_bounds.bottom(),
options.menu_size.width(), options.menu_size.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
options.menu_anchor = MenuAnchorPosition::kTopRight;
expected =
gfx::Rect(options.anchor_bounds.right() - options.menu_size.width(),
options.anchor_bounds.bottom(), options.menu_size.width(),
options.menu_size.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Menu will be placed above or below with an offset.
options.menu_anchor = MenuAnchorPosition::kBottomCenter;
const int kTouchYPadding = 15;
// Menu fits above -> placed above.
expected = gfx::Rect(
options.anchor_bounds.x() +
(options.anchor_bounds.width() - options.menu_size.width()) / 2,
options.anchor_bounds.y() - options.menu_size.height() - kTouchYPadding,
options.menu_size.width(), options.menu_size.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
// Menu does not fit above -> placed below.
options.anchor_bounds = gfx::Rect(options.menu_size.height() / 2,
options.menu_size.width(), 0, 0);
if (ShouldIgnoreScreenBoundsForMenus()) {
expected = gfx::Rect(
options.anchor_bounds.x() +
(options.anchor_bounds.width() - options.menu_size.width()) / 2,
options.anchor_bounds.y() - options.anchor_bounds.bottom() -
kTouchYPadding,
options.menu_size.width(), options.menu_size.height());
} else {
expected = gfx::Rect(
options.anchor_bounds.x() +
(options.anchor_bounds.width() - options.menu_size.width()) / 2,
options.anchor_bounds.y() + kTouchYPadding, options.menu_size.width(),
options.menu_size.height());
}
EXPECT_EQ(expected, CalculateMenuBounds(options));
}
// Regression test for https://crbug.com/1217711
TEST_F(MenuControllerTest, MenuAnchorPositionFlippedInRtl) {
ASSERT_FALSE(base::i18n::IsRTL());
// Test the AdjustAnchorPositionForRtl() method directly, rather than running
// the menu, because it's awkward to access the menu's window. Also, the menu
// bounds are already tested separately.
EXPECT_EQ(MenuAnchorPosition::kTopLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kTopLeft));
EXPECT_EQ(MenuAnchorPosition::kTopRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kTopRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleTopLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleTopLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleTopRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleTopRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleBottomLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleBottomLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleBottomRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleBottomRight));
base::i18n::SetRTLForTesting(true);
// Anchor positions are left/right flipped in RTL.
EXPECT_EQ(MenuAnchorPosition::kTopLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kTopRight));
EXPECT_EQ(MenuAnchorPosition::kTopRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kTopLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleTopLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleTopRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleTopRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleTopLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleLeft));
EXPECT_EQ(MenuAnchorPosition::kBubbleBottomLeft,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleBottomRight));
EXPECT_EQ(MenuAnchorPosition::kBubbleBottomRight,
AdjustAnchorPositionForRtl(MenuAnchorPosition::kBubbleBottomLeft));
base::i18n::SetRTLForTesting(false);
}
TEST_F(MenuControllerTest, CalculateMenuBoundsMonitorFitTest) {
MenuBoundsOptions options;
gfx::Rect expected;
options.monitor_bounds = gfx::Rect(0, 0, 100, 100);
options.anchor_bounds = gfx::Rect();
options.menu_size = gfx::Size(options.monitor_bounds.width() / 2,
options.monitor_bounds.height() * 2);
expected =
gfx::Rect(options.anchor_bounds.x(), options.anchor_bounds.bottom(),
options.menu_size.width(), options.monitor_bounds.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
options.menu_size = gfx::Size(options.monitor_bounds.width() * 2,
options.monitor_bounds.height() / 2);
expected =
gfx::Rect(options.anchor_bounds.x(), options.anchor_bounds.bottom(),
options.monitor_bounds.width(), options.menu_size.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
options.menu_size = gfx::Size(options.monitor_bounds.width() * 2,
options.monitor_bounds.height() * 2);
expected = gfx::Rect(
options.anchor_bounds.x(), options.anchor_bounds.bottom(),
options.monitor_bounds.width(), options.monitor_bounds.height());
EXPECT_EQ(expected, CalculateMenuBounds(options));
}
// Test that menus show up on screen with non-zero sized anchors.
TEST_P(MenuControllerTest, TestMenuFitsOnScreen) {
const int display_size = 500;
// Simulate multiple display layouts.
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
const gfx::Rect monitor_bounds(x * display_size, y * display_size,
display_size, display_size);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleTopLeft, monitor_bounds);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleTopRight, monitor_bounds);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleLeft, monitor_bounds);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleRight, monitor_bounds);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleBottomLeft,
monitor_bounds);
TestMenuFitsOnScreen(MenuAnchorPosition::kBubbleBottomRight,
monitor_bounds);
}
}
}
// Test that menus show up on screen with zero sized anchors.
TEST_P(MenuControllerTest, TestMenuFitsOnScreenSmallAnchor) {
const int display_size = 500;
// Simulate multiple display layouts.
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
const gfx::Rect monitor_bounds(x * display_size, y * display_size,
display_size, display_size);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleTopLeft,
monitor_bounds);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleTopRight,
monitor_bounds);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleLeft,
monitor_bounds);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleRight,
monitor_bounds);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleBottomLeft,
monitor_bounds);
TestMenuFitsOnScreenSmallAnchor(MenuAnchorPosition::kBubbleBottomRight,
monitor_bounds);
}
}
}
// Test that menus fit a small screen.
TEST_P(MenuControllerTest, TestMenuFitsOnSmallScreen) {
const int display_size = 500;
// Simulate multiple display layouts.
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
const gfx::Rect monitor_bounds(x * display_size, y * display_size,
display_size, display_size);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleTopLeft,
monitor_bounds);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleTopRight,
monitor_bounds);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleLeft,
monitor_bounds);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleRight,
monitor_bounds);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleBottomLeft,
monitor_bounds);
TestMenuFitsOnSmallScreen(MenuAnchorPosition::kBubbleBottomRight,
monitor_bounds);
}
}
}
// Test that submenus are displayed within the screen bounds on smaller screens.
TEST_P(MenuControllerTest, TestSubmenuFitsOnScreen) {
menu_controller()->set_use_ash_system_ui_layout(true);
MenuItemView* sub_item = menu_item()->GetSubmenu()->GetMenuItemAt(0);
sub_item->AppendMenuItem(11, u"Subitem.One");
const int menu_width = MenuConfig::instance().touchable_menu_min_width;
const gfx::Size parent_size(menu_width, menu_width);
const gfx::Size parent_size_wide(menu_width * 2, menu_width);
const int kDisplayWidth = parent_size.width() * 3;
const int kDisplayHeight = parent_size.height() * 3;
// For both kBubbleTopLeft and kBubbleTopRight.
for (auto menu_position : {MenuAnchorPosition::kBubbleTopLeft,
MenuAnchorPosition::kBubbleTopRight}) {
// Simulate multiple display layouts.
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
const gfx::Rect monitor_bounds(x * kDisplayWidth, y * kDisplayHeight,
kDisplayWidth, kDisplayHeight);
const int x_min = monitor_bounds.x();
const int x_max = monitor_bounds.right() - parent_size.width();
const int x_mid = (x_min + x_max) / 2;
const int x_qtr = x_min + (x_max - x_min) / 4;
const int y_min = monitor_bounds.y();
const int y_max = monitor_bounds.bottom() - parent_size.height();
const int y_mid = (y_min + y_max) / 2;
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_min, y_min), parent_size), menu_position);
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_max, y_min), parent_size), menu_position);
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_mid, y_min), parent_size), menu_position);
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_min, y_mid), parent_size), menu_position);
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_min, y_max), parent_size), menu_position);
// Extra wide menu: test with insufficient room on both sides.
TestSubmenuFitsOnScreen(
sub_item, monitor_bounds,
gfx::Rect(gfx::Point(x_qtr, y_min), parent_size_wide),
menu_position);
}
}
}
}
// Test that a menu that was originally drawn below the anchor does not get
// squished or move above the anchor when it grows vertically and horizontally
// beyond the monitor bounds.
TEST_F(MenuControllerTest, GrowingMenuMovesLaterallyNotVertically) {
// We can't know the position of windows in Wayland. Thus, this case is not
// valid for Wayland.
if (ShouldIgnoreScreenBoundsForMenus())
return;
MenuBoundsOptions options;
options.monitor_bounds = gfx::Rect(0, 0, 100, 100);
// The anchor should be near the bottom right side of the screen.
options.anchor_bounds = gfx::Rect(80, 70, 15, 10);
// The menu should fit the available space, below the anchor.
options.menu_size = gfx::Size(20, 20);
// Ensure the menu is initially drawn below the bounds, and the MenuPosition
// is set to MenuPosition::kBelowBounds;
const gfx::Rect first_drawn_expected(80, 80, 20, 20);
EXPECT_EQ(first_drawn_expected, CalculateMenuBounds(options));
EXPECT_EQ(MenuItemView::MenuPosition::kBelowBounds,
menu_item()->ActualMenuPosition());
options.menu_position = MenuItemView::MenuPosition::kBelowBounds;
// The menu bounds are larger than the remaining space on the monitor. This
// simulates the case where the menu has been grown vertically and
// horizontally to where it would no longer fit on the screen.
options.menu_size = gfx::Size(50, 50);
// The menu bounds should move left to show the wider menu, and grow to fill
// the remaining vertical space without moving upwards.
const gfx::Rect final_expected(50, 80, 50, 20);
EXPECT_EQ(final_expected, CalculateMenuBounds(options));
}
#if defined(USE_AURA)
// This tests that mouse moved events from the initial position of the mouse
// when the menu was shown don't select the menu item at the mouse position.
TEST_F(MenuControllerTest, MouseAtMenuItemOnShow) {
// Most tests create an already shown menu but this test needs one that's
// not shown, so it can show it. The mouse position is remembered when
// the menu is shown.
std::unique_ptr<TestMenuItemViewNotShown> menu_item(
new TestMenuItemViewNotShown(menu_delegate()));
MenuItemView* first_item = menu_item->AppendMenuItem(1, u"One");
menu_item->AppendMenuItem(2, u"Two");
menu_item->SetController(menu_controller());
// Move the mouse to where the first menu item will be shown,
// and show the menu.
gfx::Size item_size = first_item->CalculatePreferredSize();
gfx::Point location(item_size.width() / 2, item_size.height() / 2);
GetRootWindow(owner())->MoveCursorTo(location);
menu_controller()->Run(owner(), nullptr, menu_item.get(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Synthesize an event at the mouse position when the menu was opened.
// It should be ignored, and selected item shouldn't change.
SubmenuView* sub_menu = menu_item->GetSubmenu();
View::ConvertPointFromScreen(sub_menu->GetScrollViewContainer(), &location);
ui::MouseEvent event(ui::ET_MOUSE_MOVED, location, location,
ui::EventTimeForNow(), 0, 0);
ProcessMouseMoved(sub_menu, event);
EXPECT_EQ(0, pending_state_item()->GetCommand());
// Synthesize an event at a slightly different mouse position. It
// should cause the item under the cursor to be selected.
location.Offset(0, 1);
ui::MouseEvent second_event(ui::ET_MOUSE_MOVED, location, location,
ui::EventTimeForNow(), 0, 0);
ProcessMouseMoved(sub_menu, second_event);
EXPECT_EQ(1, pending_state_item()->GetCommand());
}
// Tests that when an asynchronous menu receives a cancel event, that it closes.
TEST_F(MenuControllerTest, AsynchronousCancelEvent) {
ExitMenuRun();
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
EXPECT_EQ(MenuController::ExitType::kNone, controller->exit_type());
ui::CancelModeEvent cancel_event;
event_generator()->Dispatch(&cancel_event);
EXPECT_EQ(MenuController::ExitType::kAll, controller->exit_type());
}
// Tests that menus without parent widgets do not crash in MenuPreTargetHandler.
TEST_F(MenuControllerTest, RunWithoutWidgetDoesntCrash) {
ExitMenuRun();
MenuController* controller = menu_controller();
controller->Run(nullptr, nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
}
// Tests that if a MenuController is destroying during drag/drop, and another
// MenuController becomes active, that the exiting of drag does not cause a
// crash.
TEST_F(MenuControllerTest, MenuControllerReplacedDuringDrag) {
// Build the menu so that the appropriate root window is available to set the
// drag drop client on.
AddButtonMenuItems(/*single_child=*/false);
TestDragDropClient drag_drop_client(base::BindRepeating(
&MenuControllerTest::TestMenuControllerReplacementDuringDrag,
base::Unretained(this)));
aura::client::SetDragDropClient(
GetRootWindow(menu_item()->GetSubmenu()->GetWidget()), &drag_drop_client);
StartDrag();
}
// Tests that if a CancelAll is called during drag-and-drop that it does not
// destroy the MenuController. On Windows and Linux this destruction also
// destroys the Widget used for drag-and-drop, thereby ending the drag.
TEST_F(MenuControllerTest, CancelAllDuringDrag) {
// Build the menu so that the appropriate root window is available to set the
// drag drop client on.
AddButtonMenuItems(/*single_child=*/false);
TestDragDropClient drag_drop_client(base::BindRepeating(
&MenuControllerTest::TestCancelAllDuringDrag, base::Unretained(this)));
aura::client::SetDragDropClient(
GetRootWindow(menu_item()->GetSubmenu()->GetWidget()), &drag_drop_client);
StartDrag();
}
// Tests that when releasing the ref on ViewsDelegate and MenuController is
// deleted, that shutdown occurs without crashing.
TEST_F(MenuControllerTest, DestroyedDuringViewsRelease) {
ExitMenuRun();
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
TestDestroyedDuringViewsRelease();
}
// Tests that when a context menu is opened above an empty menu item, and a
// right-click occurs over the empty item, that the bottom menu is not hidden,
// that a request to relaunch the context menu is received, and that
// subsequently pressing ESC does not crash the browser.
TEST_F(MenuControllerTest, RepostEventToEmptyMenuItem) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
// Setup a submenu. Additionally hook up appropriate Widget and View
// containers, with bounds, so that hit testing works.
MenuController* controller = menu_controller();
MenuItemView* base_menu = menu_item();
base_menu->SetBounds(0, 0, 200, 200);
SubmenuView* base_submenu = base_menu->GetSubmenu();
base_submenu->SetBounds(0, 0, 200, 200);
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 200, 200);
params.do_capture = false;
base_submenu->ShowAt(params);
GetMenuHost(base_submenu)
->SetContentsView(base_submenu->GetScrollViewContainer());
// Build the submenu to have an empty menu item. Additionally hook up
// appropriate Widget and View containers with bounds, so that hit testing
// works.
std::unique_ptr<TestMenuDelegate> sub_menu_item_delegate =
std::make_unique<TestMenuDelegate>();
std::unique_ptr<TestMenuItemViewShown> sub_menu_item =
std::make_unique<TestMenuItemViewShown>(sub_menu_item_delegate.get());
sub_menu_item->AddEmptyMenusForTest();
sub_menu_item->SetController(controller);
sub_menu_item->SetBounds(0, 50, 50, 50);
base_submenu->AddChildView(sub_menu_item.get());
SubmenuView* sub_menu_view = sub_menu_item->GetSubmenu();
sub_menu_view->SetBounds(0, 50, 50, 50);
params.parent = owner();
params.bounds = gfx::Rect(0, 50, 50, 50);
params.do_capture = false;
sub_menu_view->ShowAt(params);
GetMenuHost(sub_menu_view)
->SetContentsView(sub_menu_view->GetScrollViewContainer());
// Set that the last selection target was the item which launches the submenu,
// as the empty item can never become a target.
SetPendingStateItem(sub_menu_item.get());
// Nest a context menu.
std::unique_ptr<TestMenuDelegate> nested_menu_delegate_1 =
std::make_unique<TestMenuDelegate>();
std::unique_ptr<TestMenuItemViewShown> nested_menu_item_1 =
std::make_unique<TestMenuItemViewShown>(nested_menu_delegate_1.get());
nested_menu_item_1->SetBounds(0, 0, 100, 100);
nested_menu_item_1->SetController(controller);
std::unique_ptr<TestMenuControllerDelegate> nested_controller_delegate_1 =
std::make_unique<TestMenuControllerDelegate>();
controller->AddNestedDelegate(nested_controller_delegate_1.get());
controller->Run(owner(), nullptr, nested_menu_item_1.get(),
gfx::Rect(150, 50, 100, 100), MenuAnchorPosition::kTopLeft,
true, false);
SubmenuView* nested_menu_submenu = nested_menu_item_1->GetSubmenu();
nested_menu_submenu->SetBounds(0, 0, 100, 100);
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = false;
nested_menu_submenu->ShowAt(params);
GetMenuHost(nested_menu_submenu)
->SetContentsView(nested_menu_submenu->GetScrollViewContainer());
// Press down outside of the context menu, and within the empty menu item.
// This should close the first context menu.
gfx::Point press_location(sub_menu_view->bounds().CenterPoint());
ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_RIGHT_MOUSE_BUTTON, 0);
ProcessMousePressed(nested_menu_submenu, press_event);
EXPECT_EQ(nested_controller_delegate_1->on_menu_closed_called(), 1);
EXPECT_EQ(menu_controller_delegate(), GetCurrentDelegate());
// While the current state is the menu item which launched the sub menu, cause
// a drag in the empty menu item. This should not hide the menu.
SetState(sub_menu_item.get());
press_location.Offset(-5, 0);
ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_RIGHT_MOUSE_BUTTON, 0);
ProcessMouseDragged(sub_menu_view, drag_event);
EXPECT_EQ(menu_delegate()->will_hide_menu_count(), 0);
// Release the mouse in the empty menu item, triggering a context menu
// request.
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_RIGHT_MOUSE_BUTTON, 0);
ProcessMouseReleased(sub_menu_view, release_event);
EXPECT_EQ(sub_menu_item_delegate->show_context_menu_count(), 1);
EXPECT_EQ(sub_menu_item_delegate->show_context_menu_source(),
sub_menu_item.get());
// Nest a context menu.
std::unique_ptr<TestMenuDelegate> nested_menu_delegate_2 =
std::make_unique<TestMenuDelegate>();
std::unique_ptr<TestMenuItemViewShown> nested_menu_item_2 =
std::make_unique<TestMenuItemViewShown>(nested_menu_delegate_2.get());
nested_menu_item_2->SetBounds(0, 0, 100, 100);
nested_menu_item_2->SetController(controller);
std::unique_ptr<TestMenuControllerDelegate> nested_controller_delegate_2 =
std::make_unique<TestMenuControllerDelegate>();
controller->AddNestedDelegate(nested_controller_delegate_2.get());
controller->Run(owner(), nullptr, nested_menu_item_2.get(),
gfx::Rect(150, 50, 100, 100), MenuAnchorPosition::kTopLeft,
true, false);
// The escape key should only close the nested menu. SelectByChar should not
// crash.
TestAsyncEscapeKey();
EXPECT_EQ(nested_controller_delegate_2->on_menu_closed_called(), 1);
EXPECT_EQ(menu_controller_delegate(), GetCurrentDelegate());
}
// Drag the mouse from an external view into a menu
// When the mouse leaves the menu while still in the process of dragging
// the menu item view highlight should turn off
TEST_F(MenuControllerTest, DragFromViewIntoMenuAndExit) {
SubmenuView* sub_menu = menu_item()->GetSubmenu();
MenuItemView* first_item = sub_menu->GetMenuItemAt(0);
std::unique_ptr<View> drag_view = std::make_unique<View>();
drag_view->SetBoundsRect(gfx::Rect(0, 500, 100, 100));
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = false;
sub_menu->ShowAt(params);
gfx::Point press_location(drag_view->bounds().CenterPoint());
gfx::Point drag_location(first_item->bounds().CenterPoint());
gfx::Point release_location(200, 50);
// Begin drag on an external view
ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
drag_view->OnMousePressed(press_event);
// Drag into a menu item
ui::MouseEvent drag_event_enter(ui::ET_MOUSE_DRAGGED, drag_location,
drag_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
ProcessMouseDragged(sub_menu, drag_event_enter);
EXPECT_TRUE(first_item->IsSelected());
// Drag out of the menu item
ui::MouseEvent drag_event_exit(ui::ET_MOUSE_DRAGGED, release_location,
release_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
ProcessMouseDragged(sub_menu, drag_event_exit);
EXPECT_FALSE(first_item->IsSelected());
// Complete drag with release
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, release_location,
release_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
ProcessMouseReleased(sub_menu, release_event);
}
// Tests that |MenuHost::InitParams| are correctly forwarded to the created
// |aura::Window|.
TEST_F(MenuControllerTest, AuraWindowIsInitializedWithMenuHostInitParams) {
SubmenuView* sub_menu = menu_item()->GetSubmenu();
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = false;
params.menu_type = ui::MenuType::kRootMenu;
sub_menu->ShowAt(params);
aura::Window* window = sub_menu->GetWidget()->GetNativeWindow();
EXPECT_EQ(ui::MenuType::kRootMenu,
window->GetProperty(aura::client::kMenuType));
}
// Tests that |aura::Window| has the correct properties when a context menu is
// shown.
TEST_F(MenuControllerTest, ContextMenuInitializesAuraWindowWhenShown) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
SubmenuView* sub_menu = menu_item()->GetSubmenu();
// Checking that context menu properties are calculated correctly.
menu_controller()->Run(owner(), nullptr, menu_item(), menu_item()->bounds(),
MenuAnchorPosition::kTopLeft, true, false);
OpenMenu(menu_item());
aura::Window* window = sub_menu->GetWidget()->GetNativeWindow();
EXPECT_EQ(ui::MenuType::kRootContextMenu,
window->GetProperty(aura::client::kMenuType));
ui::OwnedWindowAnchor* anchor =
window->GetProperty(aura::client::kOwnedWindowAnchor);
EXPECT_TRUE(anchor);
EXPECT_EQ(ui::OwnedWindowAnchorPosition::kBottomLeft,
anchor->anchor_position);
EXPECT_EQ(ui::OwnedWindowAnchorGravity::kBottomRight, anchor->anchor_gravity);
EXPECT_EQ((ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY),
anchor->constraint_adjustment);
EXPECT_EQ(
CalculateExpectedMenuAnchorRect(menu_item(), window->GetBoundsInScreen()),
anchor->anchor_rect);
// Checking that child menu properties are calculated correctly.
MenuItemView* const child_menu = menu_item()->GetSubmenu()->GetMenuItemAt(0);
child_menu->CreateSubmenu();
ASSERT_NE(nullptr, child_menu->GetParentMenuItem());
menu_controller()->Run(owner(), nullptr, child_menu, child_menu->bounds(),
MenuAnchorPosition::kTopRight, false, false);
OpenMenu(child_menu);
ASSERT_NE(nullptr, child_menu->GetWidget());
window = child_menu->GetSubmenu()->GetWidget()->GetNativeWindow();
anchor = window->GetProperty(aura::client::kOwnedWindowAnchor);
EXPECT_TRUE(anchor);
EXPECT_EQ(ui::MenuType::kChildMenu,
window->GetProperty(aura::client::kMenuType));
EXPECT_EQ(ui::OwnedWindowAnchorPosition::kTopRight, anchor->anchor_position);
EXPECT_EQ(ui::OwnedWindowAnchorGravity::kBottomRight, anchor->anchor_gravity);
EXPECT_EQ((ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY),
anchor->constraint_adjustment);
EXPECT_EQ(
CalculateExpectedMenuAnchorRect(child_menu, window->GetBoundsInScreen()),
anchor->anchor_rect);
}
// Tests that |aura::Window| has the correct properties when a root or a child
// menu is shown.
TEST_F(MenuControllerTest, RootAndChildMenusInitializeAuraWindowWhenShown) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
SubmenuView* sub_menu = menu_item()->GetSubmenu();
// Checking that root menu properties are calculated correctly.
menu_controller()->Run(owner(), nullptr, menu_item(), menu_item()->bounds(),
MenuAnchorPosition::kTopLeft, false, false);
OpenMenu(menu_item());
aura::Window* window = sub_menu->GetWidget()->GetNativeWindow();
ui::OwnedWindowAnchor* anchor =
window->GetProperty(aura::client::kOwnedWindowAnchor);
EXPECT_TRUE(anchor);
EXPECT_EQ(ui::MenuType::kRootMenu,
window->GetProperty(aura::client::kMenuType));
EXPECT_EQ(ui::OwnedWindowAnchorPosition::kBottomLeft,
anchor->anchor_position);
EXPECT_EQ(ui::OwnedWindowAnchorGravity::kBottomRight, anchor->anchor_gravity);
EXPECT_EQ((ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY),
anchor->constraint_adjustment);
EXPECT_EQ(
CalculateExpectedMenuAnchorRect(menu_item(), window->GetBoundsInScreen()),
anchor->anchor_rect);
// Checking that child menu properties are calculated correctly.
MenuItemView* const child_menu = menu_item()->GetSubmenu()->GetMenuItemAt(0);
child_menu->CreateSubmenu();
ASSERT_NE(nullptr, child_menu->GetParentMenuItem());
menu_controller()->Run(owner(), nullptr, child_menu, child_menu->bounds(),
MenuAnchorPosition::kTopRight, false, false);
OpenMenu(child_menu);
ASSERT_NE(nullptr, child_menu->GetWidget());
window = child_menu->GetSubmenu()->GetWidget()->GetNativeWindow();
anchor = window->GetProperty(aura::client::kOwnedWindowAnchor);
EXPECT_TRUE(anchor);
EXPECT_EQ(ui::MenuType::kChildMenu,
window->GetProperty(aura::client::kMenuType));
EXPECT_EQ(ui::OwnedWindowAnchorPosition::kTopRight, anchor->anchor_position);
EXPECT_EQ(ui::OwnedWindowAnchorGravity::kBottomRight, anchor->anchor_gravity);
EXPECT_EQ((ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentRezizeY),
anchor->constraint_adjustment);
auto anchor_rect = anchor->anchor_rect;
EXPECT_EQ(
CalculateExpectedMenuAnchorRect(child_menu, window->GetBoundsInScreen()),
anchor->anchor_rect);
// Try to reposition the existing menu. Its anchor must change.
child_menu->SetY(menu_item()->bounds().y() + 2);
menu_controller()->Run(owner(), nullptr, child_menu, child_menu->bounds(),
MenuAnchorPosition::kTopLeft, false, false);
MenuChildrenChanged(child_menu);
EXPECT_EQ(
CalculateExpectedMenuAnchorRect(child_menu, window->GetBoundsInScreen()),
anchor->anchor_rect);
// New anchor mustn't be the same as the old one.
EXPECT_NE(anchor->anchor_rect, anchor_rect);
}
#endif // defined(USE_AURA)
// Tests that having the MenuController deleted during OnMousePressed does not
// cause a crash. ASAN bots should not detect use-after-free in MenuController.
TEST_F(MenuControllerTest, NoUseAfterFreeWhenMenuCanceledOnMousePress) {
MenuController* controller = menu_controller();
DestroyMenuControllerOnMenuClosed(menu_controller_delegate());
// Creating own MenuItem for a minimal test environment.
auto item = std::make_unique<TestMenuItemViewNotShown>(menu_delegate());
item->SetController(controller);
item->SetBounds(0, 0, 50, 50);
SubmenuView* sub_menu = item->CreateSubmenu();
auto* canceling_view = new CancelMenuOnMousePressView(controller);
sub_menu->AddChildView(canceling_view);
canceling_view->SetBoundsRect(item->bounds());
controller->Run(owner(), nullptr, item.get(), item->bounds(),
MenuAnchorPosition::kTopLeft, false, false);
MenuHost::InitParams params;
params.parent = owner();
params.bounds = item->bounds();
params.do_capture = true;
sub_menu->ShowAt(params);
// Simulate a mouse press in the middle of the |closing_widget|.
gfx::Point location(canceling_view->bounds().CenterPoint());
ui::MouseEvent event(ui::ET_MOUSE_PRESSED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0);
EXPECT_TRUE(controller->OnMousePressed(sub_menu, event));
// Close to remove observers before test TearDown.
sub_menu->Close();
}
TEST_F(MenuControllerTest, SetSelectionIndices_MenuItemsOnly) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
OpenMenu(menu_item());
ui::AXNodeData data;
item1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(3, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item4->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
TEST_F(MenuControllerTest,
SetSelectionIndices_MenuItemsOnly_SkipHiddenAndDisabled) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
item1->SetEnabled(false);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
item3->SetVisible(false);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
OpenMenu(menu_item());
ui::AXNodeData data;
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item4->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
TEST_F(MenuControllerTest, SetSelectionIndices_Buttons) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
AddButtonMenuItems(/*single_child=*/false);
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4);
Button* const button1 = Button::AsButton(item5->children()[0]);
Button* const button2 = Button::AsButton(item5->children()[1]);
Button* const button3 = Button::AsButton(item5->children()[2]);
OpenMenu(menu_item());
ui::AXNodeData data;
item1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(3, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item4->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
button1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
button2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(6, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
button3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(7, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
TEST_F(MenuControllerTest, SetSelectionIndices_Buttons_SkipHiddenAndDisabled) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
AddButtonMenuItems(/*single_child=*/false);
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4);
Button* const button1 = Button::AsButton(item5->children()[0]);
button1->SetEnabled(false);
Button* const button2 = Button::AsButton(item5->children()[1]);
button2->SetVisible(false);
Button* const button3 = Button::AsButton(item5->children()[2]);
OpenMenu(menu_item());
ui::AXNodeData data;
item1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(3, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item4->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
button3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
TEST_F(MenuControllerTest, SetSelectionIndices_NestedButtons) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
// This simulates how buttons are nested in views in the main app menu.
View* const container_view = new View();
container_view->GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenu);
item4->AddChildView(container_view);
// There's usually a label before the traversable elements.
container_view->AddChildView(new Label());
// Add two focusable buttons (buttons in menus are always focusable).
Button* const button1 =
container_view->AddChildView(std::make_unique<LabelButton>());
button1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button1->GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenuItem);
Button* const button2 =
container_view->AddChildView(std::make_unique<LabelButton>());
button2->GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenuItem);
button2->SetFocusBehavior(View::FocusBehavior::ALWAYS);
OpenMenu(menu_item());
ui::AXNodeData data;
item1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(3, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
data = ui::AXNodeData();
button1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
data = ui::AXNodeData();
button2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(5, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
TEST_F(MenuControllerTest, SetSelectionIndices_ChildrenChanged) {
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
AddButtonMenuItems(/*single_child=*/false);
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4);
Button* const button1 = Button::AsButton(item5->children()[0]);
Button* const button2 = Button::AsButton(item5->children()[1]);
Button* const button3 = Button::AsButton(item5->children()[2]);
OpenMenu(menu_item());
auto expect_coordinates = [](View* v, absl::optional<int> pos,
absl::optional<int> size) {
ui::AXNodeData data;
v->GetViewAccessibility().GetAccessibleNodeData(&data);
if (pos.has_value()) {
EXPECT_EQ(pos.value(),
data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
} else {
EXPECT_FALSE(data.HasIntAttribute(ax::mojom::IntAttribute::kPosInSet));
}
if (size.has_value()) {
EXPECT_EQ(size.value(),
data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
} else {
EXPECT_FALSE(data.HasIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
};
expect_coordinates(item1, 1, 7);
expect_coordinates(item2, 2, 7);
expect_coordinates(item3, 3, 7);
expect_coordinates(item4, 4, 7);
expect_coordinates(button1, 5, 7);
expect_coordinates(button2, 6, 7);
expect_coordinates(button3, 7, 7);
// Simulate a menu model update.
item1->SetEnabled(false);
button1->SetEnabled(false);
MenuItemView* item6 = menu_item()->AppendMenuItem(6, u"Six");
menu_item()->RemoveMenuItem(item2);
item2 = nullptr;
MenuChildrenChanged(menu_item());
// Verify that disabled menu items no longer have PosInSet or SetSize.
expect_coordinates(item1, absl::nullopt, absl::nullopt);
expect_coordinates(button1, absl::nullopt, absl::nullopt);
expect_coordinates(item3, 1, 5);
expect_coordinates(item4, 2, 5);
expect_coordinates(button2, 3, 5);
expect_coordinates(button3, 4, 5);
expect_coordinates(item6, 5, 5);
}
// Tests that a menu opened asynchronously, will notify its
// MenuControllerDelegate when accessibility performs a do default action.
TEST_F(MenuControllerTest, AccessibilityDoDefaultCallsAccept) {
views::test::DisableMenuClosureAnimations();
MenuController* controller = menu_controller();
controller->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
MenuItemView* accepted = menu_item()->GetSubmenu()->GetMenuItemAt(0);
ui::AXActionData data;
data.action = ax::mojom::Action::kDoDefault;
accepted->HandleAccessibleAction(data);
views::test::WaitForMenuClosureAnimation();
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(accepted, delegate->on_menu_closed_menu());
EXPECT_EQ(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
delegate->on_menu_closed_notify_type());
}
// Test that the kSelectedChildrenChanged event is emitted on
// the root menu item when the selected menu item changes.
TEST_F(MenuControllerTest, AccessibilityEmitsSelectChildrenChanged) {
AXEventCounter ax_counter(views::AXEventManager::Get());
menu_controller()->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
// Arrow down to select an item checking the event has been emitted.
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged), 0);
DispatchKey(ui::VKEY_DOWN);
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged), 1);
DispatchKey(ui::VKEY_DOWN);
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged), 2);
}
// Test that in accessibility mode disabled menu items are taken into account
// during items indices assignment.
TEST_F(MenuControllerTest, AccessibilityDisabledItemsIndices) {
ScopedAXModeSetter ax_mode_setter_{ui::AXMode::kNativeAPIs};
#if BUILDFLAG(IS_WIN)
// TODO(crbug.com/1286137): This test is consistently failing on Win11.
if (base::win::OSInfo::GetInstance()->version() >=
base::win::Version::WIN11) {
GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater";
}
#endif
MenuItemView* const item1 = menu_item()->GetSubmenu()->GetMenuItemAt(0);
MenuItemView* const item2 = menu_item()->GetSubmenu()->GetMenuItemAt(1);
MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2);
MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3);
item2->SetEnabled(false);
OpenMenu(menu_item());
ui::AXNodeData data;
item1->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(1, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item2->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(2, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item3->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(3, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
item4->GetViewAccessibility().GetAccessibleNodeData(&data);
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_EQ(4, data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
#if BUILDFLAG(IS_MAC)
// This test exercises a Mac-specific behavior, by which hotkeys using modifiers
// cause menus to close and the hotkeys to be handled by the browser window.
// This specific test case tries using cmd-ctrl-f, which normally means
// "Fullscreen".
TEST_F(MenuControllerTest, BrowserHotkeysCancelMenusAndAreRedispatched) {
menu_controller()->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
int options = ui::EF_COMMAND_DOWN;
ui::KeyEvent press_cmd(ui::ET_KEY_PRESSED, ui::VKEY_COMMAND, options);
menu_controller()->OnWillDispatchKeyEvent(&press_cmd);
EXPECT_TRUE(IsShowing()); // ensure the command press itself doesn't cancel
options |= ui::EF_CONTROL_DOWN;
ui::KeyEvent press_ctrl(ui::ET_KEY_PRESSED, ui::VKEY_CONTROL, options);
menu_controller()->OnWillDispatchKeyEvent(&press_ctrl);
EXPECT_TRUE(IsShowing());
ui::KeyEvent press_f(ui::ET_KEY_PRESSED, ui::VKEY_F, options);
menu_controller()->OnWillDispatchKeyEvent(&press_f); // to pay respects
EXPECT_FALSE(IsShowing());
EXPECT_FALSE(press_f.handled());
EXPECT_FALSE(press_f.stopped_propagation());
}
#endif
#if BUILDFLAG(IS_WIN)
#define MAYBE_SubmenuOpenByKey DISABLED_SubmenuOpenByKey
#else
#define MAYBE_SubmenuOpenByKey SubmenuOpenByKey
#endif
TEST_F(MenuControllerTest, MAYBE_SubmenuOpenByKey) {
// Create a submenu.
MenuItemView* const child_menu = menu_item()->GetSubmenu()->GetMenuItemAt(0);
SubmenuView* sub_menu = child_menu->CreateSubmenu();
child_menu->AppendMenuItem(5, u"Five");
child_menu->AppendMenuItem(6, u"Six");
// Open the menu and select the menu item that has a submenu.
OpenMenu(menu_item());
SetPendingStateItem(child_menu);
SetState(child_menu);
EXPECT_EQ(1, pending_state_item()->GetCommand());
EXPECT_EQ(nullptr, sub_menu->host());
// Dispatch a key to open the submenu.
DispatchKey(ui::VKEY_RIGHT);
EXPECT_EQ(5, pending_state_item()->GetCommand());
EXPECT_NE(nullptr, sub_menu->host());
}
class ExecuteCommandWithoutClosingMenuTest : public MenuControllerTest {
public:
void SetUp() override {
MenuControllerTest::SetUp();
views::test::DisableMenuClosureAnimations();
menu_controller()->Run(owner(), nullptr, menu_item(), gfx::Rect(),
MenuAnchorPosition::kTopLeft, false, false);
MenuHost::InitParams params;
params.parent = owner();
params.bounds = gfx::Rect(0, 0, 100, 100);
params.do_capture = false;
menu_item()->GetSubmenu()->ShowAt(params);
menu_delegate()->set_should_execute_command_without_closing_menu(true);
}
};
TEST_F(ExecuteCommandWithoutClosingMenuTest, OnClick) {
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
MenuItemView* menu_item_view = menu_item()->GetSubmenu()->GetMenuItemAt(0);
gfx::Point press_location(menu_item_view->bounds().CenterPoint());
ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, press_location,
press_location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
ProcessMousePressed(menu_item()->GetSubmenu(), press_event);
ProcessMouseReleased(menu_item()->GetSubmenu(), release_event);
EXPECT_EQ(0, delegate->on_menu_closed_called());
EXPECT_TRUE(IsShowing());
EXPECT_EQ(menu_delegate()->execute_command_id(),
menu_item_view->GetCommand());
}
TEST_F(ExecuteCommandWithoutClosingMenuTest, OnTap) {
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
MenuItemView* menu_item_view = menu_item()->GetSubmenu()->GetMenuItemAt(0);
gfx::Point tap_location(menu_item_view->bounds().CenterPoint());
ui::GestureEvent event(tap_location.x(), tap_location.y(), 0,
ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP));
ProcessGestureEvent(menu_item()->GetSubmenu(), event);
EXPECT_EQ(0, delegate->on_menu_closed_called());
EXPECT_TRUE(IsShowing());
EXPECT_EQ(menu_delegate()->execute_command_id(),
menu_item_view->GetCommand());
}
TEST_F(ExecuteCommandWithoutClosingMenuTest, OnReturnKey) {
TestMenuControllerDelegate* delegate = menu_controller_delegate();
EXPECT_EQ(0, delegate->on_menu_closed_called());
DispatchKey(ui::VKEY_DOWN);
DispatchKey(ui::VKEY_RETURN);
EXPECT_EQ(0, delegate->on_menu_closed_called());
EXPECT_TRUE(IsShowing());
EXPECT_EQ(menu_delegate()->execute_command_id(),
menu_item()->GetSubmenu()->GetMenuItemAt(0)->GetCommand());
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_controller_unittest.cc | C++ | unknown | 143,452 |
// 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/menu_delegate.h"
#include "base/functional/callback_helpers.h"
#include "base/notreached.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/events/event.h"
#include "ui/views/controls/menu/menu_config.h"
namespace views {
MenuDelegate::~MenuDelegate() = default;
bool MenuDelegate::IsItemChecked(int id) const {
return false;
}
std::u16string MenuDelegate::GetLabel(int id) const {
return std::u16string();
}
const gfx::FontList* MenuDelegate::GetLabelFontList(int id) const {
return nullptr;
}
absl::optional<SkColor> MenuDelegate::GetLabelColor(int id) const {
return absl::nullopt;
}
std::u16string MenuDelegate::GetTooltipText(
int id,
const gfx::Point& screen_loc) const {
return std::u16string();
}
bool MenuDelegate::GetAccelerator(int id, ui::Accelerator* accelerator) const {
return false;
}
bool MenuDelegate::ShowContextMenu(MenuItemView* source,
int id,
const gfx::Point& p,
ui::MenuSourceType source_type) {
return false;
}
bool MenuDelegate::SupportsCommand(int id) const {
return true;
}
bool MenuDelegate::IsCommandEnabled(int id) const {
return true;
}
bool MenuDelegate::IsCommandVisible(int id) const {
return true;
}
bool MenuDelegate::GetContextualLabel(int id, std::u16string* out) const {
return false;
}
bool MenuDelegate::ShouldCloseAllMenusOnExecute(int id) {
return true;
}
void MenuDelegate::ExecuteCommand(int id, int mouse_event_flags) {
ExecuteCommand(id);
}
bool MenuDelegate::ShouldExecuteCommandWithoutClosingMenu(int id,
const ui::Event& e) {
return false;
}
bool MenuDelegate::IsTriggerableEvent(MenuItemView* source,
const ui::Event& e) {
return e.type() == ui::ET_GESTURE_TAP ||
e.type() == ui::ET_GESTURE_TAP_DOWN ||
(e.IsMouseEvent() &&
(e.flags() & (ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON)));
}
bool MenuDelegate::CanDrop(MenuItemView* menu, const OSExchangeData& data) {
return false;
}
bool MenuDelegate::GetDropFormats(
MenuItemView* menu,
int* formats,
std::set<ui::ClipboardFormatType>* format_types) {
return false;
}
bool MenuDelegate::AreDropTypesRequired(MenuItemView* menu) {
return false;
}
ui::mojom::DragOperation MenuDelegate::GetDropOperation(
MenuItemView* item,
const ui::DropTargetEvent& event,
DropPosition* position) {
NOTREACHED_NORETURN()
<< "If you override CanDrop, you must override this too";
}
views::View::DropCallback MenuDelegate::GetDropCallback(
MenuItemView* menu,
DropPosition position,
const ui::DropTargetEvent& event) {
NOTREACHED_NORETURN()
<< "If you override CanDrop, you must override this too";
}
bool MenuDelegate::CanDrag(MenuItemView* menu) {
return false;
}
void MenuDelegate::WriteDragData(MenuItemView* sender, OSExchangeData* data) {
NOTREACHED_NORETURN()
<< "If you override CanDrag, you must override this too.";
}
int MenuDelegate::GetDragOperations(MenuItemView* sender) {
NOTREACHED_NORETURN()
<< "If you override CanDrag, you must override this too.";
}
bool MenuDelegate::ShouldCloseOnDragComplete() {
return true;
}
MenuItemView* MenuDelegate::GetSiblingMenu(MenuItemView* menu,
const gfx::Point& screen_point,
MenuAnchorPosition* anchor,
bool* has_mnemonics,
MenuButton** button) {
return nullptr;
}
int MenuDelegate::GetMaxWidthForMenu(MenuItemView* menu) {
// NOTE: this needs to be large enough to accommodate the wrench menu with
// big fonts.
return 800;
}
void MenuDelegate::WillShowMenu(MenuItemView* menu) {}
void MenuDelegate::WillHideMenu(MenuItemView* menu) {}
bool MenuDelegate::ShouldTryPositioningBesideAnchor() const {
return true;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_delegate.cc | C++ | unknown | 4,244 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_
#include <set>
#include <string>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
using ui::OSExchangeData;
namespace gfx {
class FontList;
class Point;
} // namespace gfx
namespace ui {
class Accelerator;
class DropTargetEvent;
} // namespace ui
namespace views {
class MenuButton;
class MenuItemView;
// MenuDelegate --------------------------------------------------------------
// Delegate for a menu. This class is used as part of MenuItemView, see it
// for details.
// TODO(sky): merge this with ui::MenuModel.
class VIEWS_EXPORT MenuDelegate {
public:
// Used during drag and drop to indicate where the drop indicator should
// be rendered.
enum class DropPosition {
kUnknow = -1,
// Indicates a drop is not allowed here.
kNone,
// Indicates the drop should occur before the item.
kBefore,
// Indicates the drop should occur after the item.
kAfter,
// Indicates the drop should occur on the item.
kOn
};
virtual ~MenuDelegate();
// Whether or not an item should be shown as checked. This is invoked for
// radio buttons and check buttons.
virtual bool IsItemChecked(int id) const;
// The string shown for the menu item. This is only invoked when an item is
// added with an empty label.
virtual std::u16string GetLabel(int id) const;
// The font and color for the menu item label.
virtual const gfx::FontList* GetLabelFontList(int id) const;
virtual absl::optional<SkColor> GetLabelColor(int id) const;
// Override the text color of a given menu item dependent on the |command_id|
// and its |is_hovered| state. |is_minor| will be true for accelerator text.
// Returns true if it chooses to override the color.
virtual bool GetTextColor(int command_id,
bool is_minor,
bool is_hovered,
SkColor* override_color) const { return false; }
// Override the background color of a given menu item dependent on the
// |command_id| and its |is_hovered| state. Returns true if it chooses to
// override the color.
virtual bool GetBackgroundColor(int command_id,
bool is_hovered,
SkColor* override_color) const
{ return false; }
// The tooltip shown for the menu item. This is invoked when the user
// hovers over the item, and no tooltip text has been set for that item.
virtual std::u16string GetTooltipText(int id,
const gfx::Point& screen_loc) const;
// If there is an accelerator for the menu item with id |id| it is set in
// |accelerator| and true is returned.
virtual bool GetAccelerator(int id, ui::Accelerator* accelerator) const;
// Shows the context menu with the specified id. This is invoked when the
// user does the appropriate gesture to show a context menu. The id
// identifies the id of the menu to show the context menu for.
// is_mouse_gesture is true if this is the result of a mouse gesture.
// If this is not the result of a mouse gesture |p| is the recommended
// location to display the content menu at. In either case, |p| is in
// screen coordinates.
// Returns true if a context menu was displayed, otherwise false
virtual bool ShowContextMenu(MenuItemView* source,
int id,
const gfx::Point& p,
ui::MenuSourceType source_type);
// Controller
virtual bool SupportsCommand(int id) const;
virtual bool IsCommandEnabled(int id) const;
virtual bool IsCommandVisible(int id) const;
virtual bool GetContextualLabel(int id, std::u16string* out) const;
virtual void ExecuteCommand(int id) {}
// If nested menus are showing (nested menus occur when a menu shows a context
// menu) this is invoked to determine if all the menus should be closed when
// the user selects the menu with the command |id|. This returns true to
// indicate that all menus should be closed. Return false if only the
// context menu should be closed.
virtual bool ShouldCloseAllMenusOnExecute(int id);
// Executes the specified command. mouse_event_flags give the flags of the
// mouse event that triggered this to be invoked (ui::MouseEvent
// flags). mouse_event_flags is 0 if this is triggered by a user gesture
// other than a mouse event.
virtual void ExecuteCommand(int id, int mouse_event_flags);
// Returns true if ExecuteCommand() should be invoked while leaving the
// menu open. Default implementation returns false.
virtual bool ShouldExecuteCommandWithoutClosingMenu(int id,
const ui::Event& e);
// Returns true if the specified event is one the user can use to trigger, or
// accept, the item. Defaults to left or right mouse buttons or tap.
virtual bool IsTriggerableEvent(MenuItemView* view, const ui::Event& e);
// Invoked to determine if drops can be accepted for a submenu. This is
// ONLY invoked for menus that have submenus and indicates whether or not
// a drop can occur on any of the child items of the item. For example,
// consider the following menu structure:
//
// A
// B
// C
//
// Where A has a submenu with children B and C. This is ONLY invoked for
// A, not B and C.
//
// To restrict which children can be dropped on override GetDropOperation.
virtual bool CanDrop(MenuItemView* menu, const OSExchangeData& data);
// See view for a description of this method.
virtual bool GetDropFormats(MenuItemView* menu,
int* formats,
std::set<ui::ClipboardFormatType>* format_types);
// See view for a description of this method.
virtual bool AreDropTypesRequired(MenuItemView* menu);
// Returns the drop operation for the specified target menu item. This is
// only invoked if CanDrop returned true for the parent menu. position
// is set based on the location of the mouse, reset to specify a different
// position.
//
// If a drop should not be allowed, returns DragOperation::kNone.
virtual ui::mojom::DragOperation GetDropOperation(
MenuItemView* item,
const ui::DropTargetEvent& event,
DropPosition* position);
// Invoked to get a callback to perform the drop operation later. This is ONLY
// invoked if CanDrop() returned true for the parent menu item, and
// GetDropOperation() returned an operation other than DragOperation::kNone.
//
// |menu| is the menu the drop occurred on.
virtual views::View::DropCallback GetDropCallback(
MenuItemView* menu,
DropPosition position,
const ui::DropTargetEvent& event);
// Invoked to determine if it is possible for the user to drag the specified
// menu item.
virtual bool CanDrag(MenuItemView* menu);
// Invoked to write the data for a drag operation to data. sender is the
// MenuItemView being dragged.
virtual void WriteDragData(MenuItemView* sender, OSExchangeData* data);
// Invoked to determine the drag operations for a drag session of sender.
// See DragDropTypes for possible values.
virtual int GetDragOperations(MenuItemView* sender);
// Returns true if the menu should close upon a drag completing. Defaults to
// true. This is only invoked for drag and drop operations performed on child
// Views that are not MenuItemViews.
virtual bool ShouldCloseOnDragComplete();
// Notification the menu has closed. This will not be called if MenuRunner is
// deleted during calls to ExecuteCommand().
virtual void OnMenuClosed(MenuItemView* menu) {}
// If the user drags the mouse outside the bounds of the menu the delegate
// is queried for a sibling menu to show. If this returns non-null the
// current menu is hidden, and the menu returned from this method is shown.
//
// The delegate owns the returned menu, not the controller.
virtual MenuItemView* GetSiblingMenu(MenuItemView* menu,
const gfx::Point& screen_point,
MenuAnchorPosition* anchor,
bool* has_mnemonics,
MenuButton** button);
// Called on unhandled open/close submenu keyboard commands. |is_rtl| will be
// true if the menu is displaying a right-to-left language.
virtual void OnUnhandledOpenSubmenu(MenuItemView* menu, bool is_rtl) {}
virtual void OnUnhandledCloseSubmenu(MenuItemView* menu, bool is_rtl) {}
// Returns the max width menus can grow to be.
virtual int GetMaxWidthForMenu(MenuItemView* menu);
// Invoked prior to a menu being shown.
virtual void WillShowMenu(MenuItemView* menu);
// Invoked prior to a menu being hidden.
virtual void WillHideMenu(MenuItemView* menu);
// Returns true if menus should fall back to positioning beside the anchor,
// rather than directly above or below it, when the menu is too tall to fit
// within the screen.
virtual bool ShouldTryPositioningBesideAnchor() const;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_delegate.h | C++ | unknown | 9,742 |
// 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/menu_host.h"
#include <utility>
#include "base/auto_reset.h"
#include "base/check_op.h"
#include "base/memory/raw_ptr.h"
#include "base/notreached.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "ui/aura/window_observer.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_host_root_view.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/submenu_view.h"
#include "ui/views/round_rect_painter.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace views {
namespace internal {
#if defined(USE_AURA)
// This class adds itself as the pre target handler for the |window|
// passed in. It currently handles touch events and forwards them to the
// controller. Reason for this approach is views does not get raw touch
// events which we need to determine if a touch happened outside the bounds
// of the menu.
class PreMenuEventDispatchHandler : public ui::EventHandler,
aura::WindowObserver {
public:
PreMenuEventDispatchHandler(const MenuController* controller,
SubmenuView* submenu,
aura::Window* window)
: menu_controller_(const_cast<MenuController*>(controller)),
submenu_(submenu),
window_(window) {
window_->AddPreTargetHandler(this);
window_->AddObserver(this);
}
PreMenuEventDispatchHandler(const PreMenuEventDispatchHandler&) = delete;
PreMenuEventDispatchHandler& operator=(const PreMenuEventDispatchHandler&) =
delete;
~PreMenuEventDispatchHandler() override { StopObserving(); }
// ui::EventHandler overrides.
void OnTouchEvent(ui::TouchEvent* event) override {
menu_controller_->OnTouchEvent(submenu_, event);
}
// aura::WindowObserver overrides.
void OnWindowDestroying(aura::Window* window) override {
DCHECK(window_ == window);
StopObserving();
}
private:
void StopObserving() {
if (!window_)
return;
window_->RemovePreTargetHandler(this);
window_->RemoveObserver(this);
window_ = nullptr;
}
raw_ptr<MenuController, DanglingUntriaged> menu_controller_;
raw_ptr<SubmenuView, DanglingUntriaged> submenu_;
raw_ptr<aura::Window, DanglingUntriaged> window_;
};
#endif // USE_AURA
void TransferGesture(ui::GestureRecognizer* gesture_recognizer,
gfx::NativeView source,
gfx::NativeView target) {
#if defined(USE_AURA)
// Use kCancel for the transfer touches behavior to ensure that `source` sees
// a valid touch stream. If kCancel is not used source's touch state may not
// be valid after the menu is closed, potentially causing it to drop touch
// events it encounters immediately after the menu is closed.
gesture_recognizer->TransferEventsTo(source, target,
ui::TransferTouchesBehavior::kCancel);
#else
NOTIMPLEMENTED();
#endif // defined(USE_AURA)
}
} // namespace internal
////////////////////////////////////////////////////////////////////////////////
// MenuHost, public:
MenuHost::MenuHost(SubmenuView* submenu) : submenu_(submenu) {
set_auto_release_capture(false);
}
MenuHost::~MenuHost() {
if (owner_)
owner_->RemoveObserver(this);
CHECK(!IsInObserverList());
}
void MenuHost::InitMenuHost(const InitParams& init_params) {
TRACE_EVENT0("views", "MenuHost::InitMenuHost");
Widget::InitParams params(Widget::InitParams::TYPE_MENU);
const MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
const MenuConfig& menu_config = MenuConfig::instance();
bool rounded_border = menu_config.CornerRadiusForMenu(menu_controller) != 0;
bool bubble_border = submenu_->GetScrollViewContainer() &&
submenu_->GetScrollViewContainer()->HasBubbleBorder();
params.shadow_type =
(bubble_border || (menu_config.use_bubble_border && rounded_border))
? Widget::InitParams::ShadowType::kNone
: Widget::InitParams::ShadowType::kDrop;
params.opacity = (bubble_border || rounded_border)
? Widget::InitParams::WindowOpacity::kTranslucent
: Widget::InitParams::WindowOpacity::kOpaque;
params.parent = init_params.parent ? init_params.parent->GetNativeView()
: gfx::kNullNativeView;
params.context = init_params.context ? init_params.context->GetNativeWindow()
: gfx::kNullNativeWindow;
params.bounds = init_params.bounds;
params.parent_widget = init_params.parent_widget;
#if defined(USE_AURA)
// TODO(msisov): remove kMenutype once positioning of anchored windows
// finally migrates to a new path.
params.init_properties_container.SetProperty(aura::client::kMenuType,
init_params.menu_type);
params.init_properties_container.SetProperty(aura::client::kOwnedWindowAnchor,
init_params.owned_window_anchor);
#endif
// If MenuHost has no parent widget, it needs to be marked
// Activatable, so that calling Show in ShowMenuHost will
// get keyboard focus.
if (init_params.parent == nullptr &&
init_params.parent_widget == gfx::kNullAcceleratedWidget)
params.activatable = Widget::InitParams::Activatable::kYes;
#if BUILDFLAG(IS_WIN)
// On Windows use the software compositor to ensure that we don't block
// the UI thread blocking issue during command buffer creation. We can
// revert this change once http://crbug.com/125248 is fixed.
params.force_software_compositing = true;
#endif
Init(std::move(params));
#if defined(USE_AURA)
pre_dispatch_handler_ =
std::make_unique<internal::PreMenuEventDispatchHandler>(
menu_controller, submenu_, GetNativeView());
#endif
DCHECK(!owner_);
owner_ = init_params.parent.get();
if (owner_)
owner_->AddObserver(this);
native_view_for_gestures_ = init_params.native_view_for_gestures;
SetContentsView(init_params.contents_view);
ShowMenuHost(init_params.do_capture);
}
bool MenuHost::IsMenuHostVisible() {
return IsVisible();
}
void MenuHost::ShowMenuHost(bool do_capture) {
// Doing a capture may make us get capture lost. Ignore it while we're in the
// process of showing.
base::AutoReset<bool> reseter(&ignore_capture_lost_, true);
ShowInactive();
if (do_capture) {
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
if (menu_controller && menu_controller->send_gesture_events_to_owner()) {
// TransferGesture when owner needs gesture events so that the incoming
// touch events after MenuHost is created are properly translated into
// gesture events instead of being dropped.
gfx::NativeView source_view = native_view_for_gestures_
? native_view_for_gestures_
: owner_->GetNativeView();
internal::TransferGesture(GetGestureRecognizer(), source_view,
GetNativeView());
} else {
GetGestureRecognizer()->CancelActiveTouchesExcept(nullptr);
}
// If MenuHost has no parent widget, it needs to call Show to get focus,
// so that it will get keyboard events.
if (owner_ == nullptr)
Show();
native_widget_private()->SetCapture();
}
}
void MenuHost::HideMenuHost() {
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
if (owner_ && menu_controller &&
menu_controller->send_gesture_events_to_owner()) {
gfx::NativeView target_view = native_view_for_gestures_
? native_view_for_gestures_
: owner_->GetNativeView();
internal::TransferGesture(GetGestureRecognizer(), GetNativeView(),
target_view);
}
ignore_capture_lost_ = true;
ReleaseMenuHostCapture();
Hide();
ignore_capture_lost_ = false;
}
void MenuHost::DestroyMenuHost() {
HideMenuHost();
destroying_ = true;
static_cast<MenuHostRootView*>(GetRootView())->ClearSubmenu();
#if defined(USE_AURA)
pre_dispatch_handler_.reset();
#endif
Close();
}
void MenuHost::SetMenuHostBounds(const gfx::Rect& bounds) {
SetBounds(bounds);
}
void MenuHost::SetMenuHostOwnedWindowAnchor(
const ui::OwnedWindowAnchor& anchor) {
#if defined(USE_AURA)
native_widget_private()->GetNativeWindow()->SetProperty(
aura::client::kOwnedWindowAnchor, anchor);
#endif
}
void MenuHost::ReleaseMenuHostCapture() {
if (native_widget_private()->HasCapture())
native_widget_private()->ReleaseCapture();
}
////////////////////////////////////////////////////////////////////////////////
// MenuHost, private:
internal::RootView* MenuHost::CreateRootView() {
return new MenuHostRootView(this, submenu_);
}
void MenuHost::OnMouseCaptureLost() {
if (destroying_ || ignore_capture_lost_)
return;
if (!ViewsDelegate::GetInstance()->ShouldCloseMenuIfMouseCaptureLost())
return;
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
if (menu_controller && !menu_controller->drag_in_progress())
menu_controller->Cancel(MenuController::ExitType::kAll);
Widget::OnMouseCaptureLost();
}
void MenuHost::OnNativeWidgetDestroyed() {
if (!destroying_) {
// We weren't explicitly told to destroy ourselves, which means the menu was
// deleted out from under us (the window we're parented to was closed). Tell
// the SubmenuView to drop references to us.
submenu_->MenuHostDestroyed();
}
Widget::OnNativeWidgetDestroyed();
}
void MenuHost::OnOwnerClosing() {
if (destroying_)
return;
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
if (menu_controller && !menu_controller->drag_in_progress())
menu_controller->Cancel(MenuController::ExitType::kAll);
}
void MenuHost::OnDragWillStart() {
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
DCHECK(menu_controller);
menu_controller->OnDragWillStart();
}
void MenuHost::OnDragComplete() {
// If we are being destroyed there is no guarantee that the menu items are
// available.
if (destroying_)
return;
MenuController* menu_controller =
submenu_->GetMenuItem()->GetMenuController();
if (!menu_controller)
return;
bool should_close = true;
// If the view came from outside menu code (i.e., not a MenuItemView), we
// should consult the MenuDelegate to determine whether or not to close on
// exit.
if (!menu_controller->did_initiate_drag()) {
MenuDelegate* menu_delegate = submenu_->GetMenuItem()->GetDelegate();
should_close = menu_delegate ? menu_delegate->ShouldCloseOnDragComplete()
: should_close;
}
menu_controller->OnDragComplete(should_close);
// We may have lost capture in the drag and drop, but are remaining open.
// Return capture so we get MouseCaptureLost events.
if (!should_close)
native_widget_private()->SetCapture();
}
Widget* MenuHost::GetPrimaryWindowWidget() {
return owner_ ? owner_->GetPrimaryWindowWidget()
: Widget::GetPrimaryWindowWidget();
}
void MenuHost::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(owner_, widget);
owner_->RemoveObserver(this);
owner_ = nullptr;
native_view_for_gestures_ = nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_host.cc | C++ | unknown | 12,169 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class SubmenuView;
class View;
class Widget;
namespace internal {
#if defined(USE_AURA)
// This class is internal to views.
class PreMenuEventDispatchHandler;
#endif // defined(USE_AURA)
} // namespace internal
namespace test {
class MenuControllerTest;
} // namespace test
// SubmenuView uses a MenuHost to house the SubmenuView.
//
// SubmenuView owns the MenuHost. When SubmenuView is done with the MenuHost
// |DestroyMenuHost| is invoked. The one exception to this is if the native
// OS destroys the widget out from under us, in which case |MenuHostDestroyed|
// is invoked back on the SubmenuView and the SubmenuView then drops references
// to the MenuHost.
class MenuHost : public Widget, public WidgetObserver {
public:
struct InitParams {
raw_ptr<Widget> parent = nullptr;
gfx::Rect bounds;
raw_ptr<View> contents_view = nullptr;
bool do_capture = false;
gfx::NativeView native_view_for_gestures;
ui::MenuType menu_type = ui::MenuType::kRootContextMenu;
// Window that is stacked below a new menu window (can be different from the
// |parent|).
raw_ptr<Widget> context = nullptr;
// Additional information that helps to position anchored windows in such
// backends as Wayland.
ui::OwnedWindowAnchor owned_window_anchor;
gfx::AcceleratedWidget parent_widget = gfx::kNullAcceleratedWidget;
};
explicit MenuHost(SubmenuView* submenu);
MenuHost(const MenuHost&) = delete;
MenuHost& operator=(const MenuHost&) = delete;
~MenuHost() override;
// Initializes and shows the MenuHost.
// WARNING: |init_params.parent| may be NULL.
void InitMenuHost(const InitParams& init_params);
// Returns true if the menu host is visible.
bool IsMenuHostVisible();
// Shows the menu host. If |do_capture| is true the menu host should do a
// mouse grab.
void ShowMenuHost(bool do_capture);
// Hides the menu host.
void HideMenuHost();
// Destroys and deletes the menu host.
void DestroyMenuHost();
// Sets the bounds of the menu host.
void SetMenuHostBounds(const gfx::Rect& bounds);
// Sets the anchor of the menu host.
void SetMenuHostOwnedWindowAnchor(const ui::OwnedWindowAnchor& anchor);
// Releases a mouse grab installed by |ShowMenuHost|.
void ReleaseMenuHostCapture();
private:
friend class test::MenuControllerTest;
// Widget:
internal::RootView* CreateRootView() override;
void OnMouseCaptureLost() override;
void OnNativeWidgetDestroyed() override;
void OnOwnerClosing() override;
void OnDragWillStart() override;
void OnDragComplete() override;
Widget* GetPrimaryWindowWidget() override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
// Parent of the MenuHost widget.
raw_ptr<Widget, DanglingUntriaged> owner_ = nullptr;
gfx::NativeView native_view_for_gestures_ = nullptr;
// The view we contain.
raw_ptr<SubmenuView, DanglingUntriaged> submenu_;
// If true, DestroyMenuHost has been invoked.
bool destroying_ = false;
// If true and capture is lost we don't notify the delegate.
bool ignore_capture_lost_ = false;
#if defined(USE_AURA)
// Handles raw touch events at the moment.
std::unique_ptr<internal::PreMenuEventDispatchHandler> pre_dispatch_handler_;
#endif // defined(USE_AURA)
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_host.h | C++ | unknown | 3,890 |
// 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/menu_host_root_view.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/submenu_view.h"
namespace views {
MenuHostRootView::MenuHostRootView(Widget* widget, SubmenuView* submenu)
: internal::RootView(widget), submenu_(submenu) {}
bool MenuHostRootView::OnMousePressed(const ui::MouseEvent& event) {
return GetMenuControllerForInputEvents() &&
GetMenuControllerForInputEvents()->OnMousePressed(submenu_, event);
}
bool MenuHostRootView::OnMouseDragged(const ui::MouseEvent& event) {
return GetMenuControllerForInputEvents() &&
GetMenuControllerForInputEvents()->OnMouseDragged(submenu_, event);
}
void MenuHostRootView::OnMouseReleased(const ui::MouseEvent& event) {
if (GetMenuControllerForInputEvents())
GetMenuControllerForInputEvents()->OnMouseReleased(submenu_, event);
}
void MenuHostRootView::OnMouseMoved(const ui::MouseEvent& event) {
if (GetMenuControllerForInputEvents())
GetMenuControllerForInputEvents()->OnMouseMoved(submenu_, event);
}
bool MenuHostRootView::OnMouseWheel(const ui::MouseWheelEvent& event) {
return GetMenuControllerForInputEvents() &&
GetMenuControllerForInputEvents()->OnMouseWheel(submenu_, event);
}
View* MenuHostRootView::GetTooltipHandlerForPoint(const gfx::Point& point) {
return GetMenuControllerForInputEvents()
? GetMenuControllerForInputEvents()->GetTooltipHandlerForPoint(
submenu_, point)
: nullptr;
}
void MenuHostRootView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (GetMenuControllerForInputEvents())
GetMenuControllerForInputEvents()->ViewHierarchyChanged(submenu_, details);
RootView::ViewHierarchyChanged(details);
}
bool MenuHostRootView::ProcessMousePressed(const ui::MouseEvent& event) {
return RootView::OnMousePressed(event);
}
bool MenuHostRootView::ProcessMouseDragged(const ui::MouseEvent& event) {
return RootView::OnMouseDragged(event);
}
void MenuHostRootView::ProcessMouseReleased(const ui::MouseEvent& event) {
RootView::OnMouseReleased(event);
}
void MenuHostRootView::ProcessMouseMoved(const ui::MouseEvent& event) {
RootView::OnMouseMoved(event);
}
View* MenuHostRootView::ProcessGetTooltipHandlerForPoint(
const gfx::Point& point) {
return RootView::GetTooltipHandlerForPoint(point);
}
void MenuHostRootView::OnEventProcessingFinished(ui::Event* event) {
RootView::OnEventProcessingFinished(event);
// Forward unhandled gesture events to our menu controller.
// TODO(tdanderson): Investigate whether this should be moved into a
// post-target handler installed on |this| instead
// (invoked only if event->target() == this).
if (event->IsGestureEvent() && !event->handled() && GetMenuController())
GetMenuController()->OnGestureEvent(submenu_, event->AsGestureEvent());
}
MenuController* MenuHostRootView::GetMenuController() {
return submenu_ ? submenu_->GetMenuItem()->GetMenuController() : nullptr;
}
MenuController* MenuHostRootView::GetMenuControllerForInputEvents() {
return GetMenuController() && GetMenuController()->CanProcessInputEvents()
? GetMenuController()
: nullptr;
}
BEGIN_METADATA(MenuHostRootView, internal::RootView)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_host_root_view.cc | C++ | unknown | 3,606 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/widget/root_view.h"
namespace views {
class MenuController;
class SubmenuView;
// MenuHostRootView is the RootView of the window showing the menu.
// SubmenuView's scroll view is added as a child of MenuHostRootView.
// MenuHostRootView forwards relevant events to the MenuController.
//
// As all the menu items are owned by the root menu item, care must be taken
// such that when MenuHostRootView is deleted it doesn't delete the menu items.
class MenuHostRootView : public internal::RootView {
public:
METADATA_HEADER(MenuHostRootView);
MenuHostRootView(Widget* widget, SubmenuView* submenu);
MenuHostRootView(const MenuHostRootView&) = delete;
MenuHostRootView& operator=(const MenuHostRootView&) = delete;
void ClearSubmenu() { submenu_ = nullptr; }
// Overridden from View:
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnMouseMoved(const ui::MouseEvent& event) override;
bool OnMouseWheel(const ui::MouseWheelEvent& event) override;
View* GetTooltipHandlerForPoint(const gfx::Point& point) override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
bool ProcessMousePressed(const ui::MouseEvent& event);
bool ProcessMouseDragged(const ui::MouseEvent& event);
void ProcessMouseReleased(const ui::MouseEvent& event);
void ProcessMouseMoved(const ui::MouseEvent& event);
View* ProcessGetTooltipHandlerForPoint(const gfx::Point& point);
private:
// ui::EventProcessor:
void OnEventProcessingFinished(ui::Event* event) override;
// Returns the MenuController for this MenuHostRootView.
MenuController* GetMenuController();
MenuController* GetMenuControllerForInputEvents();
// The SubmenuView we contain.
raw_ptr<SubmenuView> submenu_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_host_root_view.h | C++ | unknown | 2,266 |
// 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/menu_image_util.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/vector_icon_types.h"
#include "ui/views/vector_icons.h"
namespace views {
gfx::ImageSkia GetMenuCheckImage(SkColor icon_color) {
return gfx::CreateVectorIcon(kMenuCheckIcon, icon_color);
}
gfx::ImageSkia GetSubmenuArrowImage(SkColor icon_color) {
return gfx::CreateVectorIcon(vector_icons::kSubmenuArrowIcon, icon_color);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_image_util.cc | C++ | unknown | 690 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/image/image_skia.h"
namespace views {
// The width/height of the check and submenu arrows.
constexpr int kMenuCheckSize = 16;
constexpr int kSubmenuArrowSize = 8;
// Returns the Menu Check box image (always checked).
gfx::ImageSkia GetMenuCheckImage(SkColor icon_color);
// Returns the image for submenu arrow for current RTL setting.
gfx::ImageSkia GetSubmenuArrowImage(SkColor icon_color);
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_image_util.h | C++ | unknown | 786 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_
#include <windows.h>
namespace views {
class MenuInsertionDelegateWin {
public:
// Returns the index to insert items into the menu at.
virtual size_t GetInsertionIndex(HMENU native_menu) = 0;
protected:
virtual ~MenuInsertionDelegateWin() = default;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_insertion_delegate_win.h | C++ | unknown | 622 |
// 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/menu_item_view.h"
#include <math.h>
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <numeric>
#include <utility>
#include "base/auto_reset.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/i18n/case_conversion.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/models/menu_model.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/text_utils.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/badge_painter.h"
#include "ui/views/controls/button/menu_button.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_image_util.h"
#include "ui/views/controls/menu/menu_scroll_view_container.h"
#include "ui/views/controls/menu/menu_separator.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/controls/separator.h"
#include "ui/views/style/typography.h"
#include "ui/views/vector_icons.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_MAC)
#include "ui/views/accessibility/view_accessibility.h"
#endif // BUILDFLAG(IS_MAC)
namespace views {
namespace {
// EmptyMenuMenuItem ----------------------------------------------------------
// EmptyMenuMenuItem is used when a menu has no menu items. EmptyMenuMenuItem
// is itself a MenuItemView, but it uses a different ID so that it isn't
// identified as a MenuItemView.
class EmptyMenuMenuItem : public MenuItemView {
public:
explicit EmptyMenuMenuItem(MenuItemView* parent)
: MenuItemView(parent, 0, Type::kEmpty) {
// Set this so that we're not identified as a normal menu item.
SetID(kEmptyMenuItemViewID);
SetTitle(l10n_util::GetStringUTF16(IDS_APP_MENU_EMPTY_SUBMENU));
SetEnabled(false);
}
EmptyMenuMenuItem(const EmptyMenuMenuItem&) = delete;
EmptyMenuMenuItem& operator=(const EmptyMenuMenuItem&) = delete;
std::u16string GetTooltipText(const gfx::Point& p) const override {
// Empty menu items shouldn't have a tooltip.
return std::u16string();
}
};
// VerticalSeparator ----------------------------------------------------------
class VerticalSeparator : public Separator {
public:
METADATA_HEADER(VerticalSeparator);
VerticalSeparator();
VerticalSeparator(const VerticalSeparator&) = delete;
VerticalSeparator& operator=(const VerticalSeparator&) = delete;
~VerticalSeparator() override = default;
};
VerticalSeparator::VerticalSeparator() {
SetFocusBehavior(FocusBehavior::NEVER);
const MenuConfig& config = MenuConfig::instance();
SetPreferredSize(
gfx::Size(config.actionable_submenu_vertical_separator_width,
config.actionable_submenu_vertical_separator_height));
SetCanProcessEventsWithinSubtree(false);
ui::ColorId id = ui::kColorMenuSeparator;
#if BUILDFLAG(IS_CHROMEOS_ASH)
id = ui::kColorAshSystemUIMenuSeparator;
#endif
SetColorId(id);
}
BEGIN_METADATA(VerticalSeparator, Separator)
END_METADATA
} // namespace
// Padding between child views.
static constexpr int kChildXPadding = 8;
// MenuItemView ---------------------------------------------------------------
// static
const int MenuItemView::kMenuItemViewID = 1001;
// static
const int MenuItemView::kEmptyMenuItemViewID =
MenuItemView::kMenuItemViewID + 1;
// static
int MenuItemView::icon_area_width_ = 0;
// static
int MenuItemView::label_start_;
// static
int MenuItemView::item_right_margin_;
// static
int MenuItemView::pref_menu_height_;
MenuItemView::MenuItemView(MenuDelegate* delegate)
: MenuItemView(/* parent */ nullptr,
/* command */ 0,
Type::kSubMenu,
delegate) {}
void MenuItemView::ChildPreferredSizeChanged(View* child) {
invalidate_dimensions();
PreferredSizeChanged();
}
void MenuItemView::OnThemeChanged() {
View::OnThemeChanged();
// Force updating as the colors may have changed.
if (!IsScheduledForDeletion())
UpdateSelectionBasedState(ShouldPaintAsSelected(PaintMode::kNormal));
}
void MenuItemView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
// Whether the selection is painted may change based on the number of
// children.
if (details.parent == this &&
update_selection_based_state_in_view_herarchy_changed_) {
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
}
}
std::u16string MenuItemView::GetTooltipText(const gfx::Point& p) const {
if (!tooltip_.empty())
return tooltip_;
if (type_ == Type::kSeparator)
return std::u16string();
const MenuController* controller = GetMenuController();
if (!controller ||
controller->exit_type() != MenuController::ExitType::kNone) {
// Either the menu has been closed or we're in the process of closing the
// menu. Don't attempt to query the delegate as it may no longer be valid.
return std::u16string();
}
const MenuItemView* root_menu_item = GetRootMenuItem();
if (root_menu_item->canceled_) {
// TODO(sky): if |canceled_| is true, controller->exit_type() should be
// something other than ExitType::kNone, but crash reports seem to indicate
// otherwise. Figure out why this is needed.
return std::u16string();
}
const MenuDelegate* delegate = GetDelegate();
if (!delegate)
return std::u16string();
gfx::Point location(p);
ConvertPointToScreen(this, &location);
return delegate->GetTooltipText(command_, location);
}
void MenuItemView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
// Set the role based on the type of menu item.
switch (type_) {
case Type::kCheckbox:
node_data->role = ax::mojom::Role::kMenuItemCheckBox;
break;
case Type::kRadio:
node_data->role = ax::mojom::Role::kMenuItemRadio;
break;
default:
node_data->role = ax::mojom::Role::kMenuItem;
break;
}
node_data->SetName(CalculateAccessibleName());
switch (type_) {
case Type::kSubMenu:
case Type::kActionableSubMenu:
// Note: This is neither necessary nor sufficient for macOS. See
// CreateSubmenu() for virtual child creation and explanation.
node_data->SetHasPopup(ax::mojom::HasPopup::kMenu);
break;
case Type::kCheckbox:
case Type::kRadio: {
const bool is_checked =
GetDelegate() && GetDelegate()->IsItemChecked(GetCommand());
node_data->SetCheckedState(is_checked ? ax::mojom::CheckedState::kTrue
: ax::mojom::CheckedState::kFalse);
} break;
case Type::kTitle:
case Type::kNormal:
case Type::kSeparator:
case Type::kEmpty:
case Type::kHighlighted:
// No additional accessibility states currently for these menu states.
break;
}
char16_t mnemonic = GetMnemonic();
if (mnemonic != '\0') {
node_data->AddStringAttribute(
ax::mojom::StringAttribute::kKeyShortcuts,
base::UTF16ToUTF8(std::u16string(1, mnemonic)));
}
if (IsTraversableByKeyboard()) {
node_data->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected,
IsSelected());
}
}
bool MenuItemView::HandleAccessibleAction(const ui::AXActionData& action_data) {
if (action_data.action != ax::mojom::Action::kDoDefault)
return View::HandleAccessibleAction(action_data);
// kDoDefault in View would simulate a mouse click in the center of this
// MenuItemView. However, mouse events for menus are dispatched via
// Widget::SetCapture() to the MenuController rather than to MenuItemView, so
// there is no effect. VKEY_RETURN provides a better UX anyway, since it will
// move focus to a submenu.
ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::DomCode::ENTER,
ui::EF_NONE, ui::DomKey::ENTER, ui::EventTimeForNow());
GetMenuController()->SetSelection(this, MenuController::SELECTION_DEFAULT);
GetMenuController()->OnWillDispatchKeyEvent(&event);
return true;
}
View::FocusBehavior MenuItemView::GetFocusBehavior() const {
// If the creator/owner of the MenuItemView has explicitly set the focus
// behavior to something other than the default NEVER, don't override it.
View::FocusBehavior focus_behavior = View::GetFocusBehavior();
if (focus_behavior != FocusBehavior::NEVER)
return focus_behavior;
// Some MenuItemView types are presumably never focusable, even by assistive
// technologies.
if (type_ == Type::kEmpty || type_ == Type::kSeparator)
return FocusBehavior::NEVER;
// The rest of the MenuItemView types are presumably focusable, at least by
// assistive technologies. But if they lack presentable information, then
// there won't be anything for ATs to convey to the user. Filter those out.
if (title_.empty() && secondary_title_.empty() && minor_text_.empty()) {
return FocusBehavior::NEVER;
}
return FocusBehavior::ACCESSIBLE_ONLY;
}
// static
bool MenuItemView::IsBubble(MenuAnchorPosition anchor) {
switch (anchor) {
case MenuAnchorPosition::kTopLeft:
case MenuAnchorPosition::kTopRight:
case MenuAnchorPosition::kBottomCenter:
return false;
case MenuAnchorPosition::kBubbleTopLeft:
case MenuAnchorPosition::kBubbleTopRight:
case MenuAnchorPosition::kBubbleLeft:
case MenuAnchorPosition::kBubbleRight:
case MenuAnchorPosition::kBubbleBottomLeft:
case MenuAnchorPosition::kBubbleBottomRight:
return true;
}
}
// static
std::u16string MenuItemView::GetAccessibleNameForMenuItem(
const std::u16string& item_text,
const std::u16string& minor_text,
bool is_new_feature) {
std::u16string accessible_name = item_text;
// Filter out the "&" for accessibility clients.
size_t index = 0;
const char16_t amp = '&';
while ((index = accessible_name.find(amp, index)) != std::u16string::npos &&
index + 1 < accessible_name.length()) {
accessible_name.replace(index, accessible_name.length() - index,
accessible_name.substr(index + 1));
// Special case for "&&" (escaped for "&").
if (accessible_name[index] == '&')
++index;
}
// Append subtext.
if (!minor_text.empty()) {
accessible_name.push_back(' ');
accessible_name.append(minor_text);
}
if (is_new_feature) {
accessible_name.push_back(' ');
accessible_name.append(GetNewBadgeAccessibleDescription());
}
return accessible_name;
}
void MenuItemView::Cancel() {
if (controller_ && !canceled_) {
canceled_ = true;
controller_->Cancel(MenuController::ExitType::kAll);
}
}
MenuItemView* MenuItemView::AddMenuItemAt(
size_t index,
int item_id,
const std::u16string& label,
const std::u16string& secondary_label,
const std::u16string& minor_text,
const ui::ImageModel& minor_icon,
const ui::ImageModel& icon,
Type type,
ui::MenuSeparatorType separator_style,
absl::optional<ui::ColorId> submenu_background_color,
absl::optional<ui::ColorId> foreground_color,
absl::optional<ui::ColorId> selected_color_id) {
DCHECK_NE(type, Type::kEmpty);
if (!submenu_) {
CreateSubmenu();
// Set the submenu border color to be the same as the first submenu
// background color;
submenu_->SetBorderColorId(submenu_background_color);
if (submenu_background_color.has_value()) {
submenu_->SetBackground(
views::CreateThemedSolidBackground(submenu_background_color.value()));
}
}
DCHECK_LE(index, submenu_->children().size());
if (type == Type::kSeparator) {
submenu_->AddChildViewAt(std::make_unique<MenuSeparator>(separator_style),
index);
return nullptr;
}
MenuItemView* item = new MenuItemView(this, item_id, type);
if (label.empty() && GetDelegate())
item->SetTitle(GetDelegate()->GetLabel(item_id));
else
item->SetTitle(label);
item->SetSecondaryTitle(secondary_label);
item->SetMinorText(minor_text);
item->SetMinorIcon(minor_icon);
item->SetIcon(icon);
item->SetForegroundColorId(foreground_color);
item->SetSelectedColorId(selected_color_id);
if (type == Type::kSubMenu || type == Type::kActionableSubMenu)
item->CreateSubmenu();
if (type == Type::kHighlighted) {
const MenuConfig& config = MenuConfig::instance();
item->SetMargins(config.footnote_vertical_margin,
config.footnote_vertical_margin);
}
if (GetDelegate() && !GetDelegate()->IsCommandVisible(item_id))
item->SetVisible(false);
return submenu_->AddChildViewAt(item, index);
}
void MenuItemView::RemoveMenuItem(View* item) {
DCHECK(item);
DCHECK(submenu_);
DCHECK_EQ(submenu_, item->parent());
removed_items_.push_back(item);
submenu_->RemoveChildView(item);
}
void MenuItemView::RemoveAllMenuItems() {
DCHECK(submenu_);
removed_items_.insert(removed_items_.end(), submenu_->children().begin(),
submenu_->children().end());
submenu_->RemoveAllChildViewsWithoutDeleting();
}
MenuItemView* MenuItemView::AppendMenuItem(int item_id,
const std::u16string& label,
const ui::ImageModel& icon) {
return AppendMenuItemImpl(item_id, label, icon, Type::kNormal);
}
MenuItemView* MenuItemView::AppendSubMenu(int item_id,
const std::u16string& label,
const ui::ImageModel& icon) {
return AppendMenuItemImpl(item_id, label, icon, Type::kSubMenu);
}
void MenuItemView::AppendSeparator() {
AppendMenuItemImpl(0, std::u16string(), ui::ImageModel(), Type::kSeparator);
}
void MenuItemView::AddSeparatorAt(size_t index) {
AddMenuItemAt(index, /*item_id=*/0, /*label=*/std::u16string(),
/*secondary_label=*/std::u16string(),
/*minor_text=*/std::u16string(),
/*minor_icon=*/ui::ImageModel(),
/*icon=*/ui::ImageModel(),
/*type=*/Type::kSeparator,
/*separator_style=*/ui::NORMAL_SEPARATOR);
}
MenuItemView* MenuItemView::AppendMenuItemImpl(int item_id,
const std::u16string& label,
const ui::ImageModel& icon,
Type type) {
const size_t index = submenu_ ? submenu_->children().size() : size_t{0};
return AddMenuItemAt(index, item_id, label, std::u16string(),
std::u16string(), ui::ImageModel(), icon, type,
ui::NORMAL_SEPARATOR);
}
SubmenuView* MenuItemView::CreateSubmenu() {
if (submenu_)
return submenu_;
submenu_ = new SubmenuView(this);
#if BUILDFLAG(IS_MAC)
// All MenuItemViews of Type kSubMenu have a respective SubmenuView.
// However, in the Views hierarchy, this SubmenuView is not a child of the
// MenuItemView. This confuses VoiceOver, because it expects the submenu
// itself to be a child of the menu item. To allow VoiceOver to recognize
// submenu items, we create a virtual child of type Menu.
std::unique_ptr<AXVirtualView> virtual_child =
std::make_unique<AXVirtualView>();
virtual_child->GetCustomData().role = ax::mojom::Role::kMenu;
GetViewAccessibility().AddVirtualChildView(std::move(virtual_child));
#endif // BUILDFLAG(IS_MAC)
// Initialize the submenu indicator icon (arrow).
submenu_arrow_image_view_ = AddChildView(std::make_unique<ImageView>());
// Force an update as `submenu_arrow_image_view_` needs to be updated. The
// state is also updated when the theme changes (which is also called when
// added to a widget).
if (GetWidget())
UpdateSelectionBasedState(ShouldPaintAsSelected(PaintMode::kNormal));
SchedulePaint();
return submenu_;
}
bool MenuItemView::HasSubmenu() const {
return (submenu_ != nullptr);
}
SubmenuView* MenuItemView::GetSubmenu() const {
return submenu_;
}
bool MenuItemView::SubmenuIsShowing() const {
return HasSubmenu() && GetSubmenu()->IsShowing();
}
void MenuItemView::SetTitle(const std::u16string& title) {
title_ = title;
invalidate_dimensions(); // Triggers preferred size recalculation.
}
void MenuItemView::SetSecondaryTitle(const std::u16string& secondary_title) {
secondary_title_ = secondary_title;
invalidate_dimensions(); // Triggers preferred size recalculation.
}
void MenuItemView::SetMinorText(const std::u16string& minor_text) {
minor_text_ = minor_text;
invalidate_dimensions(); // Triggers preferred size recalculation.
}
void MenuItemView::SetMinorIcon(const ui::ImageModel& minor_icon) {
minor_icon_ = minor_icon;
invalidate_dimensions(); // Triggers preferred size recalculation.
}
void MenuItemView::SetSelected(bool selected) {
if (selected_ == selected)
return;
selected_ = selected;
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
OnPropertyChanged(&selected_, kPropertyEffectsPaint);
}
base::CallbackListSubscription MenuItemView::AddSelectedChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&selected_, std::move(callback));
}
void MenuItemView::SetSelectionOfActionableSubmenu(
bool submenu_area_of_actionable_submenu_selected) {
DCHECK_EQ(Type::kActionableSubMenu, type_);
if (submenu_area_of_actionable_submenu_selected_ ==
submenu_area_of_actionable_submenu_selected) {
return;
}
submenu_area_of_actionable_submenu_selected_ =
submenu_area_of_actionable_submenu_selected;
SchedulePaint();
}
void MenuItemView::SetTooltip(const std::u16string& tooltip, int item_id) {
MenuItemView* item = GetMenuItemByID(item_id);
DCHECK(item);
item->tooltip_ = tooltip;
}
void MenuItemView::SetIcon(const ui::ImageModel& icon) {
if (icon.IsEmpty()) {
SetIconView(nullptr);
return;
}
auto icon_view = std::make_unique<ImageView>();
icon_view->SetImage(icon);
SetIconView(std::move(icon_view));
}
void MenuItemView::SetIconView(std::unique_ptr<ImageView> icon_view) {
{
// See comment in `update_selection_based_state_in_view_herarchy_changed_`
// as to why setting the field and explicitly calling
// UpdateSelectionBasedStateIfChanged() is necessary.
base::AutoReset setter(
&update_selection_based_state_in_view_herarchy_changed_, false);
if (icon_view_) {
RemoveChildViewT(icon_view_.get());
icon_view_ = nullptr;
}
if (icon_view)
icon_view_ = AddChildView(std::move(icon_view));
}
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
InvalidateLayout();
SchedulePaint();
}
void MenuItemView::OnDropOrSelectionStatusMayHaveChanged() {
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
}
void MenuItemView::OnPaint(gfx::Canvas* canvas) {
OnPaintImpl(canvas, PaintMode::kNormal);
}
gfx::Size MenuItemView::CalculatePreferredSize() const {
const MenuItemDimensions& dimensions(GetDimensions());
return gfx::Size(dimensions.standard_width + dimensions.children_width,
dimensions.height);
}
int MenuItemView::GetHeightForWidth(int width) const {
// If this isn't a container, we can just use the preferred size's height.
if (!IsContainer())
return GetPreferredSize().height();
const gfx::Insets margins = GetContainerMargins();
int height = children().front()->GetHeightForWidth(width - margins.width());
if (!icon_view_ && GetRootMenuItem()->has_icons())
height = std::max(height, MenuConfig::instance().check_height);
height += margins.height();
return height;
}
gfx::Rect MenuItemView::GetSubmenuAreaOfActionableSubmenu() const {
DCHECK_EQ(Type::kActionableSubMenu, type_);
const MenuConfig& config = MenuConfig::instance();
return gfx::Rect(gfx::Point(vertical_separator_->bounds().right(), 0),
gfx::Size(config.actionable_submenu_width, height()));
}
const MenuItemView::MenuItemDimensions& MenuItemView::GetDimensions() const {
if (!is_dimensions_valid())
dimensions_ = CalculateDimensions();
DCHECK(is_dimensions_valid());
return dimensions_;
}
MenuController* MenuItemView::GetMenuController() {
return GetRootMenuItem()->controller_.get();
}
const MenuController* MenuItemView::GetMenuController() const {
return GetRootMenuItem()->controller_.get();
}
MenuDelegate* MenuItemView::GetDelegate() {
return GetRootMenuItem()->delegate_;
}
const MenuDelegate* MenuItemView::GetDelegate() const {
return GetRootMenuItem()->delegate_;
}
MenuItemView* MenuItemView::GetRootMenuItem() {
return const_cast<MenuItemView*>(
static_cast<const MenuItemView*>(this)->GetRootMenuItem());
}
const MenuItemView* MenuItemView::GetRootMenuItem() const {
const MenuItemView* item = this;
for (const MenuItemView* parent = GetParentMenuItem(); parent;
parent = item->GetParentMenuItem())
item = parent;
return item;
}
char16_t MenuItemView::GetMnemonic() {
if (!GetRootMenuItem()->has_mnemonics_ ||
!MenuConfig::instance().use_mnemonics || !may_have_mnemonics()) {
return 0;
}
size_t index = 0;
do {
index = title_.find('&', index);
if (index != std::u16string::npos) {
if (index + 1 != title_.size() && title_[index + 1] != '&') {
char16_t char_array[] = {title_[index + 1], 0};
// TODO(jshin): What about Turkish locale? See http://crbug.com/81719.
// If the mnemonic is capital I and the UI language is Turkish,
// lowercasing it results in 'small dotless i', which is different
// from a 'dotted i'. Similar issues may exist for az and lt locales.
return base::i18n::ToLower(char_array)[0];
}
index++;
}
} while (index != std::u16string::npos);
return 0;
}
MenuItemView* MenuItemView::GetMenuItemByID(int id) {
if (GetCommand() == id)
return this;
if (!HasSubmenu())
return nullptr;
for (MenuItemView* item : GetSubmenu()->GetMenuItems()) {
MenuItemView* result = item->GetMenuItemByID(id);
if (result)
return result;
}
return nullptr;
}
void MenuItemView::ChildrenChanged() {
MenuController* controller = GetMenuController();
if (controller) {
// Handles the case where we were empty and are no longer empty.
RemoveEmptyMenus();
// Handles the case where we were not empty, but now are.
AddEmptyMenus();
controller->MenuChildrenChanged(this);
if (submenu_) {
// Force a paint and a synchronous layout. This needs a synchronous layout
// as UpdateSubmenuSelection() looks at bounds. This handles the case of
// the top level window's size remaining the same, resulting in no change
// to the submenu's size and no layout.
submenu_->Layout();
submenu_->SchedulePaint();
// Update the menu selection after layout.
controller->UpdateSubmenuSelection(submenu_);
}
}
for (auto* item : removed_items_)
delete item;
removed_items_.clear();
}
void MenuItemView::Layout() {
if (children().empty())
return;
if (IsContainer()) {
// This MenuItemView is acting as a thin wrapper around the sole child view,
// and the size has already been set appropriately for the child's preferred
// size and margins. The child's bounds can simply be set to the content
// bounds, less the margins.
gfx::Rect bounds = GetContentsBounds();
bounds.Inset(GetContainerMargins());
children().front()->SetBoundsRect(bounds);
} else {
// Child views are laid out right aligned and given the full height. To
// right align start with the last view and progress to the first.
int child_x = width() - (use_right_margin_ ? item_right_margin_ : 0);
for (View* child : base::Reversed(children())) {
if (icon_view_ == child)
continue;
if (radio_check_image_view_ == child)
continue;
if (submenu_arrow_image_view_ == child)
continue;
if (vertical_separator_ == child)
continue;
int width = child->GetPreferredSize().width();
child->SetBounds(child_x - width, 0, width, height());
child_x -= width + kChildXPadding;
}
// Position |icon_view|.
const MenuConfig& config = MenuConfig::instance();
if (icon_view_) {
icon_view_->SizeToPreferredSize();
gfx::Size size = icon_view_->GetPreferredSize();
int x = config.item_horizontal_padding +
(icon_area_width_ - size.width()) / 2;
if (config.icons_in_label || type_ == Type::kCheckbox ||
type_ == Type::kRadio)
x = label_start_;
if (GetMenuController() &&
GetMenuController()->use_ash_system_ui_layout())
x = config.touchable_item_horizontal_padding;
int y =
(height() + GetTopMargin() - GetBottomMargin() - size.height()) / 2;
icon_view_->SetPosition(gfx::Point(x, y));
}
if (radio_check_image_view_) {
int x = config.item_horizontal_padding;
if (GetMenuController() &&
GetMenuController()->use_ash_system_ui_layout())
x = config.touchable_item_horizontal_padding;
int y =
(height() + GetTopMargin() - GetBottomMargin() - kMenuCheckSize) / 2;
radio_check_image_view_->SetBounds(x, y, kMenuCheckSize, kMenuCheckSize);
}
if (submenu_arrow_image_view_) {
int x = width() - config.arrow_width -
(type_ == Type::kActionableSubMenu
? config.actionable_submenu_arrow_to_edge_padding
: config.arrow_to_edge_padding);
int y =
(height() + GetTopMargin() - GetBottomMargin() - kSubmenuArrowSize) /
2;
submenu_arrow_image_view_->SetBounds(x, y, config.arrow_width,
kSubmenuArrowSize);
}
if (vertical_separator_) {
const gfx::Size preferred_size = vertical_separator_->GetPreferredSize();
int x = width() - config.actionable_submenu_width -
config.actionable_submenu_vertical_separator_width;
int y = (height() - preferred_size.height()) / 2;
vertical_separator_->SetBoundsRect(
gfx::Rect(gfx::Point(x, y), preferred_size));
}
}
}
void MenuItemView::SetMargins(int top_margin, int bottom_margin) {
top_margin_ = top_margin;
bottom_margin_ = bottom_margin;
invalidate_dimensions();
}
void MenuItemView::SetForcedVisualSelection(bool selected) {
if (selected == forced_visual_selection_)
return;
forced_visual_selection_ = selected;
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
SchedulePaint();
}
void MenuItemView::SetCornerRadius(int radius) {
DCHECK_EQ(Type::kHighlighted, type_);
corner_radius_ = radius;
invalidate_dimensions(); // Triggers preferred size recalculation.
}
void MenuItemView::SetAlerted() {
is_alerted_ = true;
SchedulePaint();
}
bool MenuItemView::ShouldShowNewBadge() const {
return is_new_;
}
bool MenuItemView::IsTraversableByKeyboard() const {
bool ignore_enabled = ui::AXPlatformNode::GetAccessibilityMode().has_mode(
ui::AXMode::kNativeAPIs);
return GetVisible() && (ignore_enabled || GetEnabled());
}
std::u16string MenuItemView::GetNewBadgeAccessibleDescription() {
return l10n_util::GetStringUTF16(IDS_NEW_BADGE_SCREEN_READER_MESSAGE);
}
MenuItemView::MenuItemView(MenuItemView* parent,
int command,
MenuItemView::Type type)
: MenuItemView(parent, command, type, /* delegate */ nullptr) {}
MenuItemView::~MenuItemView() {
if (GetMenuController())
GetMenuController()->OnMenuItemDestroying(this);
delete submenu_;
for (auto* item : removed_items_)
delete item;
}
void MenuItemView::UpdateMenuPartSizes() {
const MenuConfig& config = MenuConfig::instance();
item_right_margin_ = config.label_to_arrow_padding + config.arrow_width +
config.arrow_to_edge_padding;
icon_area_width_ = config.check_width;
if (has_icons_)
icon_area_width_ = std::max(icon_area_width_, GetMaxIconViewWidth());
const bool use_ash_system_ui_layout =
GetMenuController() && GetMenuController()->use_ash_system_ui_layout();
label_start_ =
(use_ash_system_ui_layout ? config.touchable_item_horizontal_padding
: config.item_horizontal_padding) +
icon_area_width_;
const bool use_padding = config.always_use_icon_to_label_padding ||
(!config.icons_in_label && has_icons_) ||
HasChecksOrRadioButtons() ||
use_ash_system_ui_layout;
int padding = use_padding ? LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_RELATED_LABEL_HORIZONTAL)
: 0;
label_start_ += padding;
EmptyMenuMenuItem menu_item(this);
menu_item.set_controller(GetMenuController());
pref_menu_height_ = menu_item.GetPreferredSize().height();
}
MenuItemView::MenuItemView(MenuItemView* parent,
int command,
Type type,
MenuDelegate* delegate)
: delegate_(delegate),
parent_menu_item_(parent),
type_(type),
command_(command) {
// Assign our ID, this allows SubmenuItemView to find MenuItemViews.
SetID(kMenuItemViewID);
if (type_ == Type::kCheckbox || type_ == Type::kRadio) {
radio_check_image_view_ = AddChildView(std::make_unique<ImageView>());
bool show_check_radio_icon =
type_ == Type::kRadio || (type_ == Type::kCheckbox && GetDelegate() &&
GetDelegate()->IsItemChecked(GetCommand()));
radio_check_image_view_->SetVisible(show_check_radio_icon);
radio_check_image_view_->SetCanProcessEventsWithinSubtree(false);
}
if (type_ == Type::kActionableSubMenu)
vertical_separator_ = AddChildView(std::make_unique<VerticalSeparator>());
// Don't request enabled status from the root menu item as it is just
// a container for real items. kEmpty items will be disabled.
MenuDelegate* root_delegate = GetDelegate();
if (parent && type != Type::kEmpty && root_delegate)
SetEnabled(root_delegate->IsCommandEnabled(command));
}
void MenuItemView::PrepareForRun(bool is_first_menu,
bool has_mnemonics,
bool show_mnemonics) {
// Currently we only support showing the root.
DCHECK(!parent_menu_item_);
// Force us to have a submenu.
CreateSubmenu();
actual_menu_position_ = requested_menu_position_;
canceled_ = false;
has_mnemonics_ = has_mnemonics;
show_mnemonics_ = has_mnemonics && show_mnemonics;
AddEmptyMenus();
if (is_first_menu) {
// Only update the menu size if there are no menus showing, otherwise
// things may shift around.
UpdateMenuPartSizes();
}
}
int MenuItemView::GetDrawStringFlags() {
int flags = 0;
if (base::i18n::IsRTL())
flags |= gfx::Canvas::TEXT_ALIGN_RIGHT;
else
flags |= gfx::Canvas::TEXT_ALIGN_LEFT;
if (GetRootMenuItem()->has_mnemonics_ && may_have_mnemonics()) {
if (MenuConfig::instance().show_mnemonics ||
GetRootMenuItem()->show_mnemonics_) {
flags |= gfx::Canvas::SHOW_PREFIX;
} else {
flags |= gfx::Canvas::HIDE_PREFIX;
}
}
return flags;
}
const gfx::FontList MenuItemView::GetFontList() const {
if (const MenuDelegate* delegate = GetDelegate()) {
if (const gfx::FontList* font_list =
delegate->GetLabelFontList(GetCommand())) {
return *font_list;
}
}
if (GetMenuController() && GetMenuController()->use_ash_system_ui_layout())
return style::GetFont(style::CONTEXT_TOUCH_MENU, style::STYLE_PRIMARY);
return MenuConfig::instance().font_list;
}
const absl::optional<SkColor> MenuItemView::GetMenuLabelColor() const {
if (const MenuDelegate* delegate = GetDelegate()) {
if (const auto& label_color = delegate->GetLabelColor(GetCommand()))
return label_color;
}
return absl::nullopt;
}
void MenuItemView::AddEmptyMenus() {
DCHECK(HasSubmenu());
if (!submenu_->HasVisibleChildren() && !submenu_->HasEmptyMenuItemView()) {
submenu_->AddChildViewAt(std::make_unique<EmptyMenuMenuItem>(this), 0);
} else {
for (MenuItemView* item : submenu_->GetMenuItems()) {
if (item->HasSubmenu())
item->AddEmptyMenus();
}
}
}
void MenuItemView::RemoveEmptyMenus() {
DCHECK(HasSubmenu());
// Copy the children, since we may mutate them as we go.
const Views children = submenu_->children();
for (View* child : children) {
if (child->GetID() == MenuItemView::kMenuItemViewID) {
MenuItemView* menu_item = static_cast<MenuItemView*>(child);
if (menu_item->HasSubmenu())
menu_item->RemoveEmptyMenus();
} else if (child->GetID() == EmptyMenuMenuItem::kEmptyMenuItemViewID) {
submenu_->RemoveChildView(child);
delete child;
}
}
}
void MenuItemView::AdjustBoundsForRTLUI(gfx::Rect* rect) const {
rect->set_x(GetMirroredXForRect(*rect));
}
void MenuItemView::PaintForDrag(gfx::Canvas* canvas) {
// Selection state may change when painting a drag operation. Set state for
// a drag operation, paint, and then set state back to non-drag (normal)
// state.
UpdateSelectionBasedStateIfChanged(PaintMode::kForDrag);
OnPaintImpl(canvas, PaintMode::kForDrag);
UpdateSelectionBasedStateIfChanged(PaintMode::kNormal);
}
void MenuItemView::OnPaintImpl(gfx::Canvas* canvas, PaintMode mode) {
const bool paint_as_selected = ShouldPaintAsSelected(mode);
// If these are out of sync, UpdateSelectionBasedStateIfChanged() was not
// called.
DCHECK_EQ(paint_as_selected, last_paint_as_selected_);
// Render the background. As MenuScrollViewContainer draws the background, we
// only need the background when we want it to look different, as when we're
// selected.
PaintBackground(canvas, mode, paint_as_selected);
const Colors colors = CalculateColors(paint_as_selected);
const gfx::FontList& font_list = GetFontList();
// Calculate the margins.
int top_margin = GetTopMargin();
const int bottom_margin = GetBottomMargin();
const int available_height = height() - top_margin - bottom_margin;
const int text_height = font_list.GetHeight();
const int total_text_height =
secondary_title().empty() ? text_height : text_height * 2;
top_margin += (available_height - total_text_height) / 2;
// Render the foreground.
int accel_width = parent_menu_item_->GetSubmenu()->max_minor_text_width();
int label_start = GetLabelStartForThisItem();
int width = this->width() - label_start - accel_width - item_right_margin_;
gfx::Rect text_bounds(label_start, top_margin, width, text_height);
text_bounds.set_x(GetMirroredXForRect(text_bounds));
int flags = GetDrawStringFlags();
if (mode == PaintMode::kForDrag)
flags |= gfx::Canvas::NO_SUBPIXEL_RENDERING;
canvas->DrawStringRectWithFlags(title(), font_list, colors.fg_color,
text_bounds, flags);
// The rest should be drawn with the minor foreground color.
if (!secondary_title().empty()) {
text_bounds.set_y(text_bounds.y() + text_height);
canvas->DrawStringRectWithFlags(secondary_title(), font_list,
colors.minor_fg_color, text_bounds, flags);
}
PaintMinorIconAndText(canvas, colors.minor_fg_color);
if (ShouldShowNewBadge()) {
BadgePainter::PaintBadge(canvas, this,
label_start +
gfx::GetStringWidth(title(), font_list) +
BadgePainter::kBadgeHorizontalMargin,
top_margin, new_badge_text_, font_list);
}
}
void MenuItemView::PaintBackground(gfx::Canvas* canvas,
PaintMode mode,
bool paint_as_selected) {
if (type_ == Type::kHighlighted || is_alerted_ ||
(paint_as_selected && selected_color_id_.has_value())) {
SkColor color = gfx::kPlaceholderColor;
ui::ColorProvider* color_provider = GetColorProvider();
if (type_ == Type::kHighlighted || selected_color_id_.has_value()) {
const ui::ColorId color_id = selected_color_id_.value_or(
paint_as_selected ? ui::kColorMenuItemBackgroundSelected
: ui::kColorMenuItemBackgroundHighlighted);
color = color_provider->GetColor(color_id);
} else {
const auto* animation = GetMenuController()->GetAlertAnimation();
color = gfx::Tween::ColorValueBetween(
animation->GetCurrentValue(),
color_provider->GetColor(ui::kColorMenuItemBackgroundAlertedInitial),
color_provider->GetColor(ui::kColorMenuItemBackgroundAlertedTarget));
}
DCHECK_NE(color, gfx::kPlaceholderColor);
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setColor(color);
// Draw a rounded rect that spills outside of the clipping area, so that the
// rounded corners only show in the bottom 2 corners. Note that
// |corner_radius_| should only be set when the highlighted item is at the
// end of the menu.
gfx::RectF spilling_rect(GetLocalBounds());
spilling_rect.set_y(spilling_rect.y() - corner_radius_);
spilling_rect.set_height(spilling_rect.height() + corner_radius_);
canvas->DrawRoundRect(spilling_rect, corner_radius_, flags);
return;
}
MenuDelegate *delegate = GetDelegate();
SkColor override_color;
if (delegate && delegate->GetBackgroundColor(GetCommand(),
paint_as_selected,
&override_color)) {
canvas->DrawColor(override_color);
} else if (paint_as_selected) {
gfx::Rect item_bounds = GetLocalBounds();
if (type_ == Type::kActionableSubMenu) {
if (submenu_area_of_actionable_submenu_selected_) {
item_bounds = GetSubmenuAreaOfActionableSubmenu();
} else {
item_bounds.set_width(item_bounds.width() -
MenuConfig::instance().actionable_submenu_width -
1);
}
}
AdjustBoundsForRTLUI(&item_bounds);
GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(),
ui::NativeTheme::kMenuItemBackground,
ui::NativeTheme::kHovered, item_bounds,
ui::NativeTheme::ExtraParams());
}
}
void MenuItemView::PaintMinorIconAndText(gfx::Canvas* canvas, SkColor color) {
std::u16string minor_text = GetMinorText();
const ui::ImageModel minor_icon = GetMinorIcon();
if (minor_text.empty() && minor_icon.IsEmpty())
return;
int available_height = height() - GetTopMargin() - GetBottomMargin();
int max_minor_text_width =
parent_menu_item_->GetSubmenu()->max_minor_text_width();
const MenuConfig& config = MenuConfig::instance();
int minor_text_right_margin = config.align_arrow_and_shortcut
? config.arrow_to_edge_padding
: item_right_margin_;
gfx::Rect minor_text_bounds(
width() - minor_text_right_margin - max_minor_text_width, GetTopMargin(),
max_minor_text_width, available_height);
minor_text_bounds.set_x(GetMirroredXForRect(minor_text_bounds));
std::unique_ptr<gfx::RenderText> render_text =
gfx::RenderText::CreateRenderText();
if (!minor_text.empty()) {
render_text->SetText(minor_text);
render_text->SetFontList(GetFontList());
render_text->SetColor(color);
render_text->SetDisplayRect(minor_text_bounds);
render_text->SetHorizontalAlignment(base::i18n::IsRTL() ? gfx::ALIGN_LEFT
: gfx::ALIGN_RIGHT);
render_text->Draw(canvas);
}
if (!minor_icon.IsEmpty()) {
const gfx::ImageSkia image = minor_icon.Rasterize(GetColorProvider());
int image_x = GetMirroredRect(minor_text_bounds).right() -
render_text->GetContentWidth() -
(minor_text.empty() ? 0 : config.item_horizontal_padding) -
image.width();
int minor_text_center_y =
minor_text_bounds.y() + minor_text_bounds.height() / 2;
int image_y = minor_text_center_y - image.height() / 2;
canvas->DrawImageInt(
image, GetMirroredXWithWidthInView(image_x, image.width()), image_y);
}
}
SkColor MenuItemView::GetTextColor(bool minor, bool paint_as_selected) const {
SkColor text_color;
const MenuDelegate *delegate = GetDelegate();
if (delegate && delegate->GetTextColor(GetCommand(), minor, paint_as_selected,
&text_color)) {
return text_color;
}
// Use a custom color if provided by the controller. If the item is selected,
// use the default color.
if (!paint_as_selected && foreground_color_id_.has_value()) {
return GetColorProvider()->GetColor(foreground_color_id_.value());
}
// If the menu item is highlighted and a custom selected color and foreground
// color have been set, use the custom foreground color. Otherwise, use the
// default color.
if (paint_as_selected && selected_color_id_.has_value() &&
foreground_color_id_.has_value()) {
return GetColorProvider()->GetColor(foreground_color_id_.value());
}
style::TextContext context =
GetMenuController() && GetMenuController()->use_ash_system_ui_layout()
? style::CONTEXT_TOUCH_MENU
: style::CONTEXT_MENU;
style::TextStyle text_style = style::STYLE_PRIMARY;
if (type_ == Type::kTitle)
text_style = style::STYLE_PRIMARY;
else if (type_ == Type::kHighlighted)
text_style = style::STYLE_HIGHLIGHTED;
else if (!GetEnabled())
text_style = style::STYLE_DISABLED;
else if (paint_as_selected)
text_style = style::STYLE_SELECTED;
else if (minor)
text_style = style::STYLE_SECONDARY;
return GetColorProvider()->GetColor(style::GetColorId(context, text_style));
}
MenuItemView::Colors MenuItemView::CalculateColors(
bool paint_as_selected) const {
const absl::optional<SkColor> label_color_from_delegate = GetMenuLabelColor();
Colors colors;
colors.fg_color = label_color_from_delegate
? *label_color_from_delegate
: GetTextColor(/*minor=*/false, paint_as_selected);
colors.icon_color = color_utils::DeriveDefaultIconColor(colors.fg_color);
colors.minor_fg_color = GetTextColor(/*minor=*/true, paint_as_selected);
return colors;
}
std::u16string MenuItemView::CalculateAccessibleName() const {
std::u16string item_text = View::GetAccessibleName();
if (!item_text.empty())
return item_text;
// Use the default accessible name if none is provided.
if (IsContainer()) {
// The first child is taking over, just use its accessible name instead of
// |title_|.
View* child = children().front();
ui::AXNodeData child_node_data;
child->GetAccessibleNodeData(&child_node_data);
item_text =
child_node_data.GetString16Attribute(ax::mojom::StringAttribute::kName);
} else {
item_text = title_;
}
return GetAccessibleNameForMenuItem(item_text, GetMinorText(),
ShouldShowNewBadge());
}
void MenuItemView::DestroyAllMenuHosts() {
if (!HasSubmenu())
return;
submenu_->Close();
for (MenuItemView* item : submenu_->GetMenuItems())
item->DestroyAllMenuHosts();
}
int MenuItemView::GetTopMargin() const {
int margin = top_margin_;
if (margin < 0) {
const MenuItemView* root = GetRootMenuItem();
margin = root && root->has_icons_
? MenuConfig::instance().item_top_margin
: MenuConfig::instance().item_no_icon_top_margin;
}
return margin;
}
int MenuItemView::GetBottomMargin() const {
int margin = bottom_margin_;
if (margin < 0) {
const MenuItemView* root = GetRootMenuItem();
margin = root && root->has_icons_
? MenuConfig::instance().item_bottom_margin
: MenuConfig::instance().item_no_icon_bottom_margin;
}
return margin;
}
gfx::Size MenuItemView::GetChildPreferredSize() const {
if (children().empty())
return gfx::Size();
if (IsContainer())
return children().front()->GetPreferredSize();
const auto add_width = [this](int width, const View* child) {
if (child == icon_view_ || child == radio_check_image_view_ ||
child == submenu_arrow_image_view_ || child == vertical_separator_)
return width;
if (width)
width += kChildXPadding;
return width + child->GetPreferredSize().width();
};
const int width =
std::accumulate(children().cbegin(), children().cend(), 0, add_width);
// If there is no icon view it returns a height of 0 to indicate that
// we should use the title height instead.
const int height = icon_view_ ? icon_view_->GetPreferredSize().height() : 0;
return gfx::Size(width, height);
}
MenuItemView::MenuItemDimensions MenuItemView::CalculateDimensions() const {
gfx::Size child_size = GetChildPreferredSize();
MenuItemDimensions dimensions;
dimensions.children_width = child_size.width();
const MenuConfig& menu_config = MenuConfig::instance();
const gfx::FontList& font_list = GetFontList();
if (GetMenuController() && GetMenuController()->use_ash_system_ui_layout()) {
dimensions.height = menu_config.touchable_menu_height;
// For container MenuItemViews, the width components should only include the
// |children_width|. Setting a |standard_width| would result in additional
// width being added to the container because the total width used in layout
// is |children_width| + |standard_width|.
if (IsContainer())
return dimensions;
// Calculate total item width to make sure the current |title_|
// has enough room within the context menu.
int label_start = GetLabelStartForThisItem();
int string_width = gfx::GetStringWidth(title_, font_list);
int item_width = string_width + label_start + item_right_margin_;
item_width = std::max(item_width, menu_config.touchable_menu_min_width);
item_width = std::min(item_width, menu_config.touchable_menu_max_width);
dimensions.standard_width = item_width;
if (icon_view_) {
dimensions.height = icon_view_->GetPreferredSize().height() +
2 * menu_config.vertical_touchable_menu_item_padding;
}
return dimensions;
}
std::u16string minor_text = GetMinorText();
dimensions.height = child_size.height();
// Adjust item content height if menu has both items with and without icons.
// This way all menu items will have the same height.
if (!icon_view_ && GetRootMenuItem()->has_icons()) {
dimensions.height =
std::max(dimensions.height, MenuConfig::instance().check_height);
}
// In the container case, only the child size plus margins need to be
// considered.
if (IsContainer()) {
const gfx::Insets margins = GetContainerMargins();
dimensions.height += margins.height();
dimensions.children_width += margins.width();
ApplyMinimumDimensions(&dimensions);
return dimensions;
}
dimensions.height += GetBottomMargin() + GetTopMargin();
int string_width = gfx::GetStringWidth(title_, font_list);
int label_start = GetLabelStartForThisItem();
dimensions.standard_width = string_width + label_start + item_right_margin_;
// Determine the length of the right-side text.
dimensions.minor_text_width =
(minor_text.empty() ? 0 : gfx::GetStringWidth(minor_text, font_list));
if (ShouldShowNewBadge())
dimensions.minor_text_width +=
views::BadgePainter::GetBadgeSize(new_badge_text_, font_list).width() +
2 * BadgePainter::kBadgeHorizontalMargin;
// Determine the height to use.
int label_text_height = secondary_title().empty() ? font_list.GetHeight()
: font_list.GetHeight() * 2;
dimensions.height =
std::max(dimensions.height,
label_text_height + GetBottomMargin() + GetTopMargin());
dimensions.height =
std::max(dimensions.height, MenuConfig::instance().item_min_height);
ApplyMinimumDimensions(&dimensions);
return dimensions;
}
void MenuItemView::ApplyMinimumDimensions(MenuItemDimensions* dims) const {
// Don't apply minimums to menus without controllers or to comboboxes.
if (!GetMenuController() || GetMenuController()->IsCombobox())
return;
// TODO(nicolaso): PaintBackground() doesn't cover the whole area in footnotes
// when minimum height is set too high. For now, just ignore minimum height
// for kHighlighted elements.
if (type_ == Type::kHighlighted)
return;
int used =
dims->standard_width + dims->children_width + dims->minor_text_width;
const MenuConfig& config = MenuConfig::instance();
if (used < config.minimum_menu_width)
dims->standard_width += (config.minimum_menu_width - used);
dims->height = std::max(dims->height,
IsContainer() ? config.minimum_container_item_height
: config.minimum_text_item_height);
}
int MenuItemView::GetLabelStartForThisItem() const {
const MenuConfig& config = MenuConfig::instance();
// Touchable items with icons do not respect |label_start_|.
if (GetMenuController() && GetMenuController()->use_ash_system_ui_layout() &&
icon_view_) {
return 2 * config.touchable_item_horizontal_padding +
icon_view_->GetPreferredSize().width();
}
int label_start = label_start_;
if ((config.icons_in_label || type_ == Type::kCheckbox ||
type_ == Type::kRadio) &&
icon_view_) {
label_start += icon_view_->GetPreferredSize().width() +
LayoutProvider::Get()->GetDistanceMetric(
DISTANCE_RELATED_LABEL_HORIZONTAL);
}
return label_start;
}
std::u16string MenuItemView::GetMinorText() const {
if (GetID() == kEmptyMenuItemViewID) {
// Don't query the delegate for menus that represent no children.
return std::u16string();
}
std::u16string accel_text;
if (MenuConfig::instance().ShouldShowAcceleratorText(this, &accel_text))
return accel_text;
return minor_text_;
}
ui::ImageModel MenuItemView::GetMinorIcon() const {
return minor_icon_;
}
bool MenuItemView::IsContainer() const {
// Let the first child take over |this| when we only have one child and no
// title.
return (NonIconChildViewsCount() == 1) && title_.empty();
}
gfx::Insets MenuItemView::GetContainerMargins() const {
DCHECK(IsContainer());
// Use the child's preferred margins but take the standard top and bottom
// margins as minimums.
const gfx::Insets* margins_prop =
children().front()->GetProperty(views::kMarginsKey);
gfx::Insets margins = margins_prop ? *margins_prop : gfx::Insets();
margins.set_top(std::max(margins.top(), GetTopMargin()));
margins.set_bottom(std::max(margins.bottom(), GetBottomMargin()));
return margins;
}
int MenuItemView::NonIconChildViewsCount() const {
// WARNING: if adding a new field that is checked here you may need to
// set `update_selection_based_state_in_view_herarchy_changed_` to false
// when setting the field and explicitly call
// UpdateSelectionBasedStateIfChanged(). See comment in header
// for details.
return static_cast<int>(children().size()) - (icon_view_ ? 1 : 0) -
(radio_check_image_view_ ? 1 : 0) -
(submenu_arrow_image_view_ ? 1 : 0) - (vertical_separator_ ? 1 : 0);
}
int MenuItemView::GetMaxIconViewWidth() const {
DCHECK(submenu_);
const auto menu_items = submenu_->GetMenuItems();
if (menu_items.empty())
return 0;
std::vector<int> widths(menu_items.size());
base::ranges::transform(menu_items, widths.begin(), [](MenuItemView* item) {
if (item->type_ == Type::kCheckbox || item->type_ == Type::kRadio) {
// If this item has a radio or checkbox, the icon will not affect
// alignment of other items.
return 0;
}
if (item->HasSubmenu()) {
return item->GetMaxIconViewWidth();
}
return (item->icon_view_ && !MenuConfig::instance().icons_in_label)
? item->icon_view_->GetPreferredSize().width()
: 0;
});
return base::ranges::max(widths);
}
bool MenuItemView::HasChecksOrRadioButtons() const {
if (type_ == Type::kCheckbox || type_ == Type::kRadio)
return true;
if (!HasSubmenu())
return false;
return base::ranges::any_of(submenu_->GetMenuItems(), [](const auto* item) {
return item->HasChecksOrRadioButtons();
});
}
void MenuItemView::UpdateSelectionBasedStateIfChanged(PaintMode mode) {
// Selection state depends upon NativeTheme. Selection based state could also
// depend on the menu model so avoid the update if the item is scheduled to be
// deleted.
if (!GetWidget() || IsScheduledForDeletion())
return;
const bool paint_as_selected = ShouldPaintAsSelected(mode);
if (paint_as_selected != last_paint_as_selected_)
UpdateSelectionBasedState(paint_as_selected);
}
void MenuItemView::UpdateSelectionBasedState(bool paint_as_selected) {
// This code makes use of the NativeTheme, which should only be accessed
// when in a Widget.
DCHECK(GetWidget());
last_paint_as_selected_ = paint_as_selected;
const Colors colors = CalculateColors(paint_as_selected);
if (submenu_arrow_image_view_) {
submenu_arrow_image_view_->SetImage(
GetSubmenuArrowImage(colors.icon_color));
}
MenuDelegate* delegate = GetDelegate();
if (type_ == Type::kCheckbox && delegate &&
delegate->IsItemChecked(GetCommand())) {
radio_check_image_view_->SetImage(GetMenuCheckImage(colors.icon_color));
} else if (type_ == Type::kRadio) {
const bool toggled = delegate && delegate->IsItemChecked(GetCommand());
const gfx::VectorIcon& radio_icon =
toggled ? kMenuRadioSelectedIcon : kMenuRadioEmptyIcon;
const SkColor radio_icon_color = GetColorProvider()->GetColor(
toggled ? ui::kColorRadioButtonForegroundChecked
: ui::kColorRadioButtonForegroundUnchecked);
radio_check_image_view_->SetImage(ui::ImageModel::FromVectorIcon(
radio_icon, radio_icon_color, kMenuCheckSize));
}
// Update any vector icons if a custom color is used.
if (foreground_color_id_.has_value() && icon_view_) {
ui::ImageModel icon_model = icon_view_->GetImageModel();
if (!icon_model.IsEmpty() && icon_model.IsVectorIcon()) {
ui::VectorIconModel model = icon_model.GetVectorIcon();
const gfx::VectorIcon* icon = model.vector_icon();
const ui::ImageModel& image_model = ui::ImageModel::FromVectorIcon(
*icon, colors.fg_color, model.icon_size());
icon_view_->SetImage(image_model);
}
}
}
bool MenuItemView::ShouldPaintAsSelected(PaintMode mode) const {
if (forced_visual_selection_.has_value())
return true;
return (parent_menu_item_ && mode == PaintMode::kNormal && IsSelected() &&
parent_menu_item_->GetSubmenu()->GetShowSelection(this) &&
(NonIconChildViewsCount() == 0));
}
bool MenuItemView::IsScheduledForDeletion() const {
const MenuItemView* parent = GetParentMenuItem();
return parent && (base::Contains(parent->removed_items_, this) ||
parent->IsScheduledForDeletion());
}
BEGIN_METADATA(MenuItemView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_item_view.cc | C++ | unknown | 56,438 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/base/themed_vector_icon.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/view.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif
namespace gfx {
class FontList;
} // namespace gfx
namespace views {
namespace internal {
class MenuRunnerImpl;
}
namespace test {
class TestMenuItemViewShown;
class TestMenuItemViewNotShown;
} // namespace test
class ImageView;
class MenuController;
class MenuDelegate;
class Separator;
class TestMenuItemView;
class SubmenuView;
// MenuItemView --------------------------------------------------------------
// MenuItemView represents a single menu item with a label and optional icon.
// Each MenuItemView may also contain a submenu, which in turn may contain
// any number of child MenuItemViews.
//
// To use a menu create an initial MenuItemView using the constructor that
// takes a MenuDelegate, then create any number of child menu items by way
// of the various AddXXX methods.
//
// MenuItemView is itself a View, which means you can add Views to each
// MenuItemView. This is normally NOT want you want, rather add other child
// Views to the submenu of the MenuItemView. Any child views of the MenuItemView
// that are focusable can be navigated to by way of the up/down arrow and can be
// activated by way of space/return keys. Activating a focusable child results
// in |AcceleratorPressed| being invoked. Note, that as menus try not to steal
// focus from the hosting window child views do not actually get focus. Instead
// |SetHotTracked| is used as the user navigates around.
//
// To show the menu use MenuRunner. See MenuRunner for details on how to run
// (show) the menu as well as for details on the life time of the menu.
class VIEWS_EXPORT MenuItemView : public View {
public:
METADATA_HEADER(MenuItemView);
friend class MenuController;
// ID used to identify menu items.
static const int kMenuItemViewID;
// ID used to identify empty menu items.
static const int kEmptyMenuItemViewID;
// Different types of menu items.
enum class Type {
kNormal, // Performs an action when selected.
kSubMenu, // Presents a submenu within another menu.
kActionableSubMenu, // A SubMenu that is also a COMMAND.
kCheckbox, // Can be selected/checked to toggle a boolean state.
kRadio, // Can be selected/checked among a group of choices.
kSeparator, // Shows a horizontal line separator.
kHighlighted, // Performs an action when selected, and has a
// different colored background that merges with the
// menu's rounded corners when placed at the bottom.
kTitle, // Title text, does not perform any action.
kEmpty, // kEmpty is a special type for empty menus that is
// only used internally.
};
// Where the menu should be drawn, above or below the bounds (when
// the bounds is non-empty). MenuPosition::kBestFit (default) positions
// the menu below the bounds unless the menu does not fit on the
// screen and the re is more space above.
enum class MenuPosition { kBestFit, kAboveBounds, kBelowBounds };
// The data structure which is used for the menu size
struct MenuItemDimensions {
MenuItemDimensions() = default;
// Width of everything except the accelerator and children views.
int standard_width = 0;
// The width of all contained views of the item.
int children_width = 0;
// The amount of space needed to accommodate the subtext.
int minor_text_width = 0;
// The height of the menu item.
int height = 0;
};
// Constructor for use with the top level menu item. This menu is never
// shown to the user, rather its use as the parent for all menu items.
explicit MenuItemView(MenuDelegate* delegate = nullptr);
MenuItemView(const MenuItemView&) = delete;
MenuItemView& operator=(const MenuItemView&) = delete;
// Overridden from View:
std::u16string GetTooltipText(const gfx::Point& p) const override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
bool HandleAccessibleAction(const ui::AXActionData& action_data) override;
FocusBehavior GetFocusBehavior() const override;
// Returns the preferred height of menu items. This is only valid when the
// menu is about to be shown.
static int pref_menu_height() { return pref_menu_height_; }
// X-coordinate of where the label starts.
static int label_start() { return label_start_; }
// Returns if a given |anchor| is a bubble or not.
static bool IsBubble(MenuAnchorPosition anchor);
// Returns the default accessible name to be used with screen readers.
// Mnemonics are removed and the menu item accelerator text is appended.
static std::u16string GetAccessibleNameForMenuItem(
const std::u16string& item_text,
const std::u16string& accelerator_text,
bool is_new_feature);
// Hides and cancels the menu. This does nothing if the menu is not open.
void Cancel();
// Add an item to the menu at a specified index. ChildrenChanged() should
// called after adding menu items if the menu may be active.
MenuItemView* AddMenuItemAt(
size_t index,
int item_id,
const std::u16string& label,
const std::u16string& secondary_label,
const std::u16string& minor_text,
const ui::ImageModel& minor_icon,
const ui::ImageModel& icon,
Type type,
ui::MenuSeparatorType separator_style,
absl::optional<ui::ColorId> submenu_background_color = absl::nullopt,
absl::optional<ui::ColorId> foreground_color = absl::nullopt,
absl::optional<ui::ColorId> selected_color_id = absl::nullopt);
// Remove the specified item from the menu. |item| will be deleted when
// ChildrenChanged() is invoked.
void RemoveMenuItem(View* item);
// Removes all items from the menu. The removed MenuItemViews are deleted
// when ChildrenChanged() is invoked.
void RemoveAllMenuItems();
// Appends a normal item to this menu.
// item_id The id of the item, used to identify it in delegate callbacks
// or (if delegate is NULL) to identify the command associated
// with this item with the controller specified in the ctor. Note
// that this value should not be 0 as this has a special meaning
// ("NULL command, no item selected")
// label The text label shown.
// icon The icon.
MenuItemView* AppendMenuItem(int item_id,
const std::u16string& label = std::u16string(),
const ui::ImageModel& icon = ui::ImageModel());
// Append a submenu to this menu.
// The returned pointer is owned by this menu.
MenuItemView* AppendSubMenu(int item_id,
const std::u16string& label,
const ui::ImageModel& icon = ui::ImageModel());
// Adds a separator to this menu
void AppendSeparator();
// Adds a separator to this menu at the specified position.
void AddSeparatorAt(size_t index);
// All the AppendXXX methods funnel into this.
MenuItemView* AppendMenuItemImpl(int item_id,
const std::u16string& label,
const ui::ImageModel& icon,
Type type);
// Returns the view that contains child menu items. If the submenu has
// not been created, this creates it.
SubmenuView* CreateSubmenu();
// Returns true if this menu item has a submenu.
bool HasSubmenu() const;
// Returns the view containing child menu items.
SubmenuView* GetSubmenu() const;
// Returns true if this menu item has a submenu and it is showing
bool SubmenuIsShowing() const;
// Returns the parent menu item.
MenuItemView* GetParentMenuItem() { return parent_menu_item_; }
const MenuItemView* GetParentMenuItem() const { return parent_menu_item_; }
// Sets/Gets the title.
void SetTitle(const std::u16string& title);
const std::u16string& title() const { return title_; }
// Sets/Gets the secondary title. When not empty, they are shown in the line
// below the title.
void SetSecondaryTitle(const std::u16string& secondary_title);
const std::u16string& secondary_title() const { return secondary_title_; }
// Sets the minor text.
void SetMinorText(const std::u16string& minor_text);
// Sets the minor icon.
void SetMinorIcon(const ui::ImageModel& minor_icon);
// Returns the type of this menu.
const Type& GetType() const { return type_; }
// Sets whether this item is selected. This is invoked as the user moves
// the mouse around the menu while open.
void SetSelected(bool selected);
// Returns true if the item is selected.
bool IsSelected() const { return selected_; }
// Adds a callback subscription associated with the above selected property.
// The callback will be invoked whenever the selected property changes.
[[nodiscard]] base::CallbackListSubscription AddSelectedChangedCallback(
PropertyChangedCallback callback);
// Sets whether the submenu area of an ACTIONABLE_SUBMENU is selected.
void SetSelectionOfActionableSubmenu(
bool submenu_area_of_actionable_submenu_selected);
// Whether the submenu area of an ACTIONABLE_SUBMENU is selected.
bool IsSubmenuAreaOfActionableSubmenuSelected() const {
return submenu_area_of_actionable_submenu_selected_;
}
// Sets the |tooltip| for a menu item view with |item_id| identifier.
void SetTooltip(const std::u16string& tooltip, int item_id);
// Sets the icon of this menu item.
void SetIcon(const ui::ImageModel& icon);
// Sets the view used to render the icon. This clobbers any icon set via
// SetIcon(). MenuItemView takes ownership of |icon_view|.
void SetIconView(std::unique_ptr<ImageView> icon_view);
// Sets the command id of this menu item.
void SetCommand(int command) { command_ = command; }
// Returns the command id of this item.
int GetCommand() const { return command_; }
void set_is_new(bool is_new) { is_new_ = is_new; }
bool is_new() const { return is_new_; }
void set_may_have_mnemonics(bool may_have_mnemonics) {
may_have_mnemonics_ = may_have_mnemonics;
}
bool may_have_mnemonics() const { return may_have_mnemonics_; }
// Called when the drop or selection status (as determined by SubmenuView) may
// have changed.
void OnDropOrSelectionStatusMayHaveChanged();
// Paints the menu item.
void OnPaint(gfx::Canvas* canvas) override;
// Returns the preferred size of this item.
gfx::Size CalculatePreferredSize() const override;
// Gets the preferred height for the given |width|. This is only different
// from GetPreferredSize().width() if the item has a child view with flexible
// dimensions.
int GetHeightForWidth(int width) const override;
// Returns the bounds of the submenu part of the ACTIONABLE_SUBMENU.
gfx::Rect GetSubmenuAreaOfActionableSubmenu() const;
// Return the preferred dimensions of the item in pixel.
const MenuItemDimensions& GetDimensions() const;
// Returns the object responsible for controlling showing the menu.
MenuController* GetMenuController();
const MenuController* GetMenuController() const;
// Returns the delegate. This returns the delegate of the root menu item.
MenuDelegate* GetDelegate();
const MenuDelegate* GetDelegate() const;
void set_delegate(MenuDelegate* delegate) { delegate_ = delegate; }
// Returns the root parent, or this if this has no parent.
MenuItemView* GetRootMenuItem();
const MenuItemView* GetRootMenuItem() const;
// Returns the mnemonic for this MenuItemView, or 0 if this MenuItemView
// doesn't have a mnemonic.
char16_t GetMnemonic();
// Do we have icons? This only has effect on the top menu. Turning this on
// makes the menus slightly wider and taller.
void set_has_icons(bool has_icons) { has_icons_ = has_icons; }
bool has_icons() const { return has_icons_; }
// Returns the descendant with the specified command.
MenuItemView* GetMenuItemByID(int id);
// Invoke if you remove/add children to the menu while it's showing. This
// recalculates the bounds.
void ChildrenChanged();
// Sizes any child views.
void Layout() override;
// Returns true if the menu has mnemonics. This only useful on the root menu
// item.
bool has_mnemonics() const { return has_mnemonics_; }
// Set top and bottom margins in pixels. If no margin is set or a
// negative margin is specified then MenuConfig values are used.
void SetMargins(int top_margin, int bottom_margin);
// Suppress the right margin if this is set to false.
void set_use_right_margin(bool use_right_margin) {
use_right_margin_ = use_right_margin;
}
// Controls whether this menu has a forced visual selection state. This is
// used when animating item acceptance on Mac. Note that once this is set
// there's no way to unset it for this MenuItemView!
void SetForcedVisualSelection(bool selected);
// For items of type HIGHLIGHTED only: sets the radius of the item's
// background. This makes the menu item's background fit its container's
// border radius, if they are both the same value.
void SetCornerRadius(int radius);
// Shows an alert on this menu item. An alerted menu item is rendered
// differently to draw attention to it. This must be called before the menu is
// run.
void SetAlerted();
bool is_alerted() const { return is_alerted_; }
// Returns whether or not a "new" badge should be shown on this menu item.
bool ShouldShowNewBadge() const;
// Returns whether keyboard navigation through the menu should stop on this
// item.
bool IsTraversableByKeyboard() const;
bool last_paint_as_selected_for_testing() const {
return last_paint_as_selected_;
}
static std::u16string GetNewBadgeAccessibleDescription();
protected:
// Creates a MenuItemView. This is used by the various AddXXX methods.
MenuItemView(MenuItemView* parent, int command, Type type);
// MenuRunner owns MenuItemView and should be the only one deleting it.
~MenuItemView() override;
// View:
void ChildPreferredSizeChanged(View* child) override;
void OnThemeChanged() override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
// Returns the preferred size (and padding) of any children.
virtual gfx::Size GetChildPreferredSize() const;
// Returns the various margins.
int GetTopMargin() const;
int GetBottomMargin() const;
private:
friend class internal::MenuRunnerImpl; // For access to ~MenuItemView.
friend class test::TestMenuItemViewShown; // for access to |submenu_|;
friend class test::TestMenuItemViewNotShown; // for access to |submenu_|;
friend class TestMenuItemView; // For access to AddEmptyMenus();
enum class PaintMode { kNormal, kForDrag };
// The set of colors used in painting the MenuItemView.
struct Colors {
SkColor fg_color = SK_ColorTRANSPARENT;
SkColor icon_color = SK_ColorTRANSPARENT;
SkColor minor_fg_color = SK_ColorTRANSPARENT;
};
MenuItemView(MenuItemView* parent,
int command,
Type type,
MenuDelegate* delegate);
// Calculates all sizes that we can from the OS.
//
// This is invoked prior to Running a menu.
void UpdateMenuPartSizes();
// The RunXXX methods call into this to set up the necessary state before
// running. |is_first_menu| is true if no menus are currently showing.
void PrepareForRun(bool is_first_menu,
bool has_mnemonics,
bool show_mnemonics);
// Returns the flags passed to DrawStringRect.
int GetDrawStringFlags();
// Returns the font list and font color to use for menu text.
const gfx::FontList GetFontList() const;
const absl::optional<SkColor> GetMenuLabelColor() const;
// If this menu item has no children a child is added showing it has no
// children. Otherwise AddEmtpyMenus is recursively invoked on child menu
// items that have children.
void AddEmptyMenus();
// Undoes the work of AddEmptyMenus.
void RemoveEmptyMenus();
// Given bounds within our View, this helper routine mirrors the bounds if
// necessary.
void AdjustBoundsForRTLUI(gfx::Rect* rect) const;
// Paints the MenuItemView for a drag operation.
void PaintForDrag(gfx::Canvas* canvas);
// Actual paint implementation.
void OnPaintImpl(gfx::Canvas* canvas, PaintMode mode);
// Helper function for OnPaintImpl() that is responsible for drawing the
// background.
void PaintBackground(gfx::Canvas* canvas,
PaintMode mode,
bool paint_as_selected);
// Paints the right-side icon and text.
void PaintMinorIconAndText(gfx::Canvas* canvas, SkColor color);
// Destroys the window used to display this menu and recursively destroys
// the windows used to display all descendants.
void DestroyAllMenuHosts();
// Returns the text that should be displayed on the end (right) of the menu
// item. This will be the accelerator (if one exists).
std::u16string GetMinorText() const;
// Returns the icon that should be displayed to the left of the minor text.
ui::ImageModel GetMinorIcon() const;
// Returns the text color for the current state. |minor| specifies if the
// minor text or the normal text is desired.
SkColor GetTextColor(bool minor, bool paint_as_selected) const;
// Returns the colors used in painting.
Colors CalculateColors(bool paint_as_selected) const;
// Calculates and returns the accessible name for this menu item.
std::u16string CalculateAccessibleName() const;
// Calculates and returns the MenuItemDimensions.
MenuItemDimensions CalculateDimensions() const;
// Imposes MenuConfig's minimum sizes, if any, on the supplied
// dimensions and returns the new dimensions. It is guaranteed that:
// ApplyMinimumDimensions(x).standard_width >= x.standard_width
// ApplyMinimumDimensions(x).children_width == x.children_width
// ApplyMinimumDimensions(x).minor_text_width == x.minor_text_width
// ApplyMinimumDimensions(x).height >= x.height
void ApplyMinimumDimensions(MenuItemDimensions* dims) const;
// Get the horizontal position at which to draw the menu item's label.
int GetLabelStartForThisItem() const;
// Used by MenuController to cache the menu position in use by the
// active menu.
MenuPosition actual_menu_position() const { return actual_menu_position_; }
void set_actual_menu_position(MenuPosition actual_menu_position) {
actual_menu_position_ = actual_menu_position;
}
void set_controller(MenuController* controller) {
if (controller)
controller_ = controller->AsWeakPtr();
else
controller_.reset();
}
// Returns true if this MenuItemView contains a single child
// that is responsible for rendering the content.
bool IsContainer() const;
// Gets the child view margins. Should only be called when |IsContainer()| is
// true.
gfx::Insets GetContainerMargins() const;
// Returns number of child views excluding icon_view.
int NonIconChildViewsCount() const;
// Returns the max icon width; recurses over submenus.
int GetMaxIconViewWidth() const;
// Returns true if the menu has items with a checkbox or a radio button.
bool HasChecksOrRadioButtons() const;
void invalidate_dimensions() { dimensions_.height = 0; }
bool is_dimensions_valid() const { return dimensions_.height > 0; }
// Calls UpdateSelectionBasedState() if the the selection state changed.
void UpdateSelectionBasedStateIfChanged(PaintMode mode);
// Updates any state that may changed based on the selection state.
void UpdateSelectionBasedState(bool should_paint_as_selected);
// Returns true if the MenuItemView should be painted as selected.
bool ShouldPaintAsSelected(PaintMode mode) const;
// Returns true if this item or any anscestor menu items have been removed and
// are currently scheduled for deletion. Items can exist in this state after
// they have been removed from the menu but before ChildrenChanged() has been
// called.
// Menu items scheduled for deletion may not accurately reflect the state of
// the menu model and this should be checked when performing actions that
// could interact with model state.
bool IsScheduledForDeletion() const;
void SetForegroundColorId(absl::optional<ui::ColorId> foreground_color_id) {
foreground_color_id_ = foreground_color_id;
}
void SetSelectedColorId(absl::optional<ui::ColorId> selected_color_id) {
selected_color_id_ = selected_color_id;
}
// The delegate. This is only valid for the root menu item. You shouldn't
// use this directly, instead use GetDelegate() which walks the tree as
// as necessary.
raw_ptr<MenuDelegate, DanglingUntriaged> delegate_ = nullptr;
// The controller for the run operation, or NULL if the menu isn't showing.
base::WeakPtr<MenuController> controller_;
// Used to detect when Cancel was invoked.
bool canceled_ = false;
// Our parent.
raw_ptr<MenuItemView, DanglingUntriaged> parent_menu_item_ = nullptr;
// Type of menu. NOTE: MenuItemView doesn't itself represent SEPARATOR,
// that is handled by an entirely different view class.
const Type type_;
// Whether we're selected.
bool selected_ = false;
bool last_paint_as_selected_ = false;
// Whether the submenu area of an ACTIONABLE_SUBMENU is selected.
bool submenu_area_of_actionable_submenu_selected_ = false;
// Command id.
int command_ = 0;
// Whether the menu item should be badged as "New" as a way to highlight a new
// feature for users.
bool is_new_ = false;
// Whether the menu item contains user-created text.
bool may_have_mnemonics_ = true;
// Submenu, created via CreateSubmenu.
raw_ptr<SubmenuView, DanglingUntriaged> submenu_ = nullptr;
std::u16string title_;
std::u16string secondary_title_;
std::u16string minor_text_;
ui::ImageModel minor_icon_;
// Does the title have a mnemonic? Only useful on the root menu item.
bool has_mnemonics_ = false;
// Should we show the mnemonic? Mnemonics are shown if this is true or
// MenuConfig says mnemonics should be shown. Only used on the root menu item.
bool show_mnemonics_ = false;
// Set if menu has icons or icon_views (applies to root menu item only).
bool has_icons_ = false;
// Pointer to a view with a menu icon.
raw_ptr<ImageView, DanglingUntriaged> icon_view_ = nullptr;
// The tooltip to show on hover for this menu item.
std::u16string tooltip_;
// Width of a menu icon area.
static int icon_area_width_;
// X-coordinate of where the label starts.
static int label_start_;
// Margins between the right of the item and the label.
static int item_right_margin_;
// Preferred height of menu items. Reset every time a menu is run.
static int pref_menu_height_;
// Cached dimensions. This is cached as text sizing calculations are quite
// costly.
mutable MenuItemDimensions dimensions_;
// Removed items to be deleted in ChildrenChanged().
std::vector<View*> removed_items_;
// Margins in pixels.
int top_margin_ = -1;
int bottom_margin_ = -1;
// Corner radius in pixels, for HIGHLIGHTED items placed at the end of a menu.
int corner_radius_ = 0;
// |menu_position_| is the requested position with respect to the bounds.
// |actual_menu_position_| is used by the controller to cache the
// position of the menu being shown.
MenuPosition requested_menu_position_ = MenuPosition::kBestFit;
MenuPosition actual_menu_position_ = MenuPosition::kBestFit;
// If set to false, the right margin will be removed for menu lines
// containing other elements.
bool use_right_margin_ = true;
// Contains an image for the checkbox or radio icon.
raw_ptr<ImageView, DanglingUntriaged> radio_check_image_view_ = nullptr;
// The submenu indicator arrow icon in case the menu item has a Submenu.
raw_ptr<ImageView, DanglingUntriaged> submenu_arrow_image_view_ = nullptr;
// The forced visual selection state of this item, if any.
absl::optional<bool> forced_visual_selection_;
// The vertical separator that separates the actionable and submenu regions of
// an ACTIONABLE_SUBMENU.
raw_ptr<Separator, DanglingUntriaged> vertical_separator_ = nullptr;
// Whether this menu item is rendered differently to draw attention to it.
bool is_alerted_ = false;
// If true, ViewHierarchyChanged() will call
// UpdateSelectionBasedStateIfChanged().
// UpdateSelectionBasedStateIfChanged() calls to NonIconChildViewsCount().
// NonIconChildViewsCount() accesses fields of type View as part of the
// implementation. A common pattern for assigning a field is:
// icon_view_ = AddChildView(icon_view);
// The problem is ViewHierarchyChanged() is called during AddChildView() and
// before `icon_view_` is set. This means NonIconChildViewsCount() may return
// the wrong thing. In this case
// `update_selection_based_state_in_view_herarchy_changed_` is set to false
// and SetIconView() explicitly calls UpdateSelectionBasedStateIfChanged().
bool update_selection_based_state_in_view_herarchy_changed_ = true;
const std::u16string new_badge_text_ = l10n_util::GetStringUTF16(
features::IsChromeRefresh2023() ? IDS_NEW_BADGE_UPPERCASE
: IDS_NEW_BADGE);
absl::optional<ui::ColorId> foreground_color_id_;
absl::optional<ui::ColorId> selected_color_id_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_item_view.h | C++ | unknown | 26,543 |
// Copyright 2014 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/menu_item_view.h"
#include <memory>
#include <string>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/themed_vector_icon.h"
#include "ui/compositor/canvas_painter.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/controls/menu/test_menu_item_view.h"
#include "ui/views/test/menu_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/vector_icons.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_test_api.h"
namespace views {
using MenuItemViewUnitTest = ViewsTestBase;
TEST_F(MenuItemViewUnitTest, AddAndRemoveChildren) {
views::TestMenuItemView root_menu;
auto* item = root_menu.AppendMenuItem(0);
views::SubmenuView* submenu = root_menu.GetSubmenu();
ASSERT_TRUE(submenu);
const auto menu_items = submenu->GetMenuItems();
ASSERT_EQ(1u, menu_items.size());
EXPECT_EQ(item, menu_items.front());
root_menu.RemoveMenuItem(item);
EXPECT_TRUE(submenu->GetMenuItems().empty());
}
namespace {
// A simple View class that will match its height to the available width.
class SquareView : public views::View {
public:
SquareView() = default;
~SquareView() override = default;
private:
gfx::Size CalculatePreferredSize() const override { return gfx::Size(1, 1); }
int GetHeightForWidth(int width) const override { return width; }
};
} // namespace
TEST_F(MenuItemViewUnitTest, TestMenuItemViewWithFlexibleWidthChild) {
views::TestMenuItemView root_menu;
// Append a normal MenuItemView.
views::MenuItemView* label_view = root_menu.AppendMenuItem(1, u"item 1");
// Append a second MenuItemView that has a child SquareView.
views::MenuItemView* flexible_view = root_menu.AppendMenuItem(2);
flexible_view->AddChildView(new SquareView());
// Set margins to 0 so that we know width should match height.
flexible_view->SetMargins(0, 0);
views::SubmenuView* submenu = root_menu.GetSubmenu();
// The first item should be the label view.
ASSERT_EQ(label_view, submenu->GetMenuItemAt(0));
gfx::Size label_size = label_view->GetPreferredSize();
// The second item should be the flexible view.
ASSERT_EQ(flexible_view, submenu->GetMenuItemAt(1));
gfx::Size flexible_size = flexible_view->GetPreferredSize();
EXPECT_EQ(1, flexible_size.width());
// ...but it should use whatever space is available to make a square.
int flex_height = flexible_view->GetHeightForWidth(label_size.width());
EXPECT_EQ(label_size.width(), flex_height);
// The submenu should be tall enough to allow for both menu items at the
// given width.
EXPECT_EQ(label_size.height() + flex_height,
submenu->GetPreferredSize().height());
}
// Tests that the top-level menu item with hidden children should contain the
// "(empty)" menu item to display.
TEST_F(MenuItemViewUnitTest, TestEmptyTopLevelWhenAllItemsAreHidden) {
views::TestMenuItemView root_menu;
views::MenuItemView* item1 = root_menu.AppendMenuItem(1, u"item 1");
views::MenuItemView* item2 = root_menu.AppendMenuItem(2, u"item 2");
// Set menu items to hidden.
item1->SetVisible(false);
item2->SetVisible(false);
SubmenuView* submenu = root_menu.GetSubmenu();
ASSERT_TRUE(submenu);
EXPECT_EQ(2u, submenu->children().size());
// Adds any empty menu items to the menu, if needed.
root_menu.AddEmptyMenus();
// Because all of the submenu's children are hidden, an empty menu item should
// have been added.
ASSERT_EQ(3u, submenu->children().size());
auto* empty_item = static_cast<MenuItemView*>(submenu->children().front());
ASSERT_TRUE(empty_item);
ASSERT_EQ(MenuItemView::kEmptyMenuItemViewID, empty_item->GetID());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_APP_MENU_EMPTY_SUBMENU),
empty_item->title());
}
// Tests that submenu with hidden children should contain the "(empty)" menu
// item to display.
TEST_F(MenuItemViewUnitTest, TestEmptySubmenuWhenAllChildItemsAreHidden) {
views::TestMenuItemView root_menu;
MenuItemView* submenu_item = root_menu.AppendSubMenu(1, u"My Submenu");
MenuItemView* child1 = submenu_item->AppendMenuItem(1, u"submenu item 1");
MenuItemView* child2 = submenu_item->AppendMenuItem(2, u"submenu item 2");
// Set submenu children to hidden.
child1->SetVisible(false);
child2->SetVisible(false);
SubmenuView* submenu = submenu_item->GetSubmenu();
ASSERT_TRUE(submenu);
EXPECT_EQ(2u, submenu->children().size());
// Adds any empty menu items to the menu, if needed.
EXPECT_FALSE(submenu->HasEmptyMenuItemView());
root_menu.AddEmptyMenus();
EXPECT_TRUE(submenu->HasEmptyMenuItemView());
// Because all of the submenu's children are hidden, an empty menu item should
// have been added.
ASSERT_EQ(3u, submenu->children().size());
auto* empty_item = static_cast<MenuItemView*>(submenu->children().front());
ASSERT_TRUE(empty_item);
// Not allowed to add an duplicated empty menu item
// if it already has an empty menu item.
root_menu.AddEmptyMenus();
ASSERT_EQ(3u, submenu->children().size());
ASSERT_EQ(MenuItemView::kEmptyMenuItemViewID, empty_item->GetID());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_APP_MENU_EMPTY_SUBMENU),
empty_item->title());
}
TEST_F(MenuItemViewUnitTest, UseMnemonicOnPlatform) {
views::TestMenuItemView root_menu;
views::MenuItemView* item1 = root_menu.AppendMenuItem(1, u"&Item 1");
views::MenuItemView* item2 = root_menu.AppendMenuItem(2, u"I&tem 2");
root_menu.set_has_mnemonics(true);
if (MenuConfig::instance().use_mnemonics) {
EXPECT_EQ('i', item1->GetMnemonic());
EXPECT_EQ('t', item2->GetMnemonic());
} else {
EXPECT_EQ(0, item1->GetMnemonic());
EXPECT_EQ(0, item2->GetMnemonic());
}
}
TEST_F(MenuItemViewUnitTest, NotifiesSelectedChanged) {
views::TestMenuItemView root_menu;
// Append a MenuItemView.
views::MenuItemView* menu_item_view = root_menu.AppendMenuItem(1, u"item");
// Verify initial selected state.
bool is_selected = menu_item_view->IsSelected();
EXPECT_FALSE(is_selected);
// Subscribe to be notified of changes to selected state.
auto subscription =
menu_item_view->AddSelectedChangedCallback(base::BindLambdaForTesting(
[&]() { is_selected = menu_item_view->IsSelected(); }));
// Verify we are notified when the MenuItemView becomes selected.
menu_item_view->SetSelected(true);
EXPECT_TRUE(is_selected);
// Verify we are notified when the MenuItemView becomes deselected.
menu_item_view->SetSelected(false);
EXPECT_FALSE(is_selected);
}
class TouchableMenuItemViewTest : public ViewsTestBase {
public:
TouchableMenuItemViewTest() = default;
~TouchableMenuItemViewTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = CreateTestWidget();
widget_->Show();
menu_delegate_ = std::make_unique<test::TestMenuDelegate>();
menu_item_view_ = new TestMenuItemView(menu_delegate_.get());
menu_runner_ = std::make_unique<MenuRunner>(
menu_item_view_, MenuRunner::USE_ASH_SYS_UI_LAYOUT);
menu_runner_->RunMenuAt(widget_.get(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
}
void TearDown() override {
widget_->CloseNow();
ViewsTestBase::TearDown();
}
gfx::Size AppendItemAndGetSize(int i, const std::u16string& title) {
return menu_item_view_->AppendMenuItem(i, title)->GetPreferredSize();
}
private:
std::unique_ptr<test::TestMenuDelegate> menu_delegate_;
std::unique_ptr<MenuRunner> menu_runner_;
std::unique_ptr<Widget> widget_;
// Owned by MenuRunner.
raw_ptr<TestMenuItemView> menu_item_view_ = nullptr;
};
// Test that touchable menu items are sized to fit the menu item titles within
// the allowed minimum and maximum width.
TEST_F(TouchableMenuItemViewTest, MinAndMaxWidth) {
const int min_menu_width = MenuConfig::instance().touchable_menu_min_width;
const int max_menu_width = MenuConfig::instance().touchable_menu_max_width;
// Test a title shorter than the minimum width.
gfx::Size item1_size = AppendItemAndGetSize(1, u"Item1 Short title");
EXPECT_EQ(item1_size.width(), min_menu_width);
// Test a title which is between the min and max allowed widths.
gfx::Size item2_size =
AppendItemAndGetSize(2, u"Item2 bigger than min less than max");
EXPECT_GT(item2_size.width(), min_menu_width);
EXPECT_LT(item2_size.width(), max_menu_width);
// Test a title which is longer than the max touchable menu width.
gfx::Size item3_size =
AppendItemAndGetSize(3,
u"Item3 Title that is longer than the maximum "
u"allowed context menu width");
EXPECT_EQ(item3_size.width(), max_menu_width);
}
class MenuItemViewLayoutTest : public ViewsTestBase {
public:
MenuItemViewLayoutTest() = default;
~MenuItemViewLayoutTest() override = default;
protected:
MenuItemView* test_item() { return test_item_; }
void PerformLayout() {
// SubmenuView does not lay out its children unless it is contained in a
// view, so make a simple container for it.
SubmenuView* submenu = root_menu_->GetSubmenu();
ASSERT_TRUE(submenu->owned_by_client());
submenu_parent_ = std::make_unique<View>();
submenu_parent_->AddChildView(submenu);
submenu_parent_->SetPosition(gfx::Point(0, 0));
submenu_parent_->SetSize(submenu->GetPreferredSize());
}
void SetUp() override {
ViewsTestBase::SetUp();
root_menu_ = std::make_unique<TestMenuItemView>();
test_item_ = root_menu_->AppendMenuItem(1);
}
private:
std::unique_ptr<TestMenuItemView> root_menu_;
raw_ptr<MenuItemView> test_item_ = nullptr;
std::unique_ptr<View> submenu_parent_;
};
// Tests that MenuItemView takes into account the child's margins and preferred
// size when laying out in container mode.
TEST_F(MenuItemViewLayoutTest, ContainerLayoutRespectsMarginsAndPreferredSize) {
// We make our menu item a simple container for our view.
View* child_view = test_item()->AddChildView(std::make_unique<View>());
// We want to check that MenuItemView::Layout() respects the child's preferred
// size and margins.
const gfx::Size child_size(200, 50);
const auto child_margins = gfx::Insets::VH(5, 10);
child_view->SetPreferredSize(child_size);
child_view->SetProperty(kMarginsKey, child_margins);
PerformLayout();
// Get |child_view|'s bounds and check that they align with |child_view|'s
// margins and preferred size.
const gfx::Rect child_bounds = child_view->bounds();
const gfx::Insets actual_margins =
test_item()->GetContentsBounds().InsetsFrom(child_bounds);
EXPECT_GE(actual_margins.left(), child_margins.left());
EXPECT_GE(actual_margins.right(), child_margins.right());
EXPECT_GE(actual_margins.top(), child_margins.top());
EXPECT_GE(actual_margins.bottom(), child_margins.bottom());
EXPECT_EQ(child_bounds.width(), child_size.width());
EXPECT_EQ(child_bounds.height(), child_size.height());
}
namespace {
// A fake View to check if GetHeightForWidth() is called with the appropriate
// width value.
class FakeView : public View {
public:
explicit FakeView(int expected_width) : expected_width_(expected_width) {}
~FakeView() override = default;
int GetHeightForWidth(int width) const override {
// Simply return a height of 1 for the expected width, and 0 otherwise.
if (width == expected_width_)
return 1;
return 0;
}
private:
const int expected_width_;
};
} // namespace
// Tests that MenuItemView passes the child's true width to
// GetHeightForWidth. This is related to https://crbug.com/933706 which was
// partially caused by it passing the full menu width rather than the width of
// the child view.
TEST_F(MenuItemViewLayoutTest, ContainerLayoutPassesTrueWidth) {
const gfx::Size child_size(2, 3);
const gfx::Insets child_margins(1);
FakeView* child_view =
test_item()->AddChildView(std::make_unique<FakeView>(child_size.width()));
child_view->SetPreferredSize(child_size);
child_view->SetProperty(kMarginsKey, child_margins);
PerformLayout();
// |child_view| should get laid out with width child_size.width, at which
// point child_view->GetHeightForWidth() should be called with the correct
// width. FakeView::GetHeightForWidth() will return 1 in this case, and 0
// otherwise. Our preferred height is also set to 3 to check verify that
// GetHeightForWidth() is even used.
EXPECT_EQ(child_view->size().height(), 1);
}
class MenuItemViewPaintUnitTest : public ViewsTestBase {
public:
MenuItemViewPaintUnitTest() = default;
MenuItemViewPaintUnitTest(const MenuItemViewPaintUnitTest&) = delete;
MenuItemViewPaintUnitTest& operator=(const MenuItemViewPaintUnitTest&) =
delete;
~MenuItemViewPaintUnitTest() override = default;
MenuItemView* menu_item_view() { return menu_item_view_; }
MenuRunner* menu_runner() { return menu_runner_.get(); }
Widget* widget() { return widget_.get(); }
// ViewsTestBase implementation.
void SetUp() override {
ViewsTestBase::SetUp();
menu_delegate_ = CreateMenuDelegate();
menu_item_view_ = new MenuItemView(menu_delegate_.get());
widget_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_->Init(std::move(params));
widget_->Show();
menu_runner_ = std::make_unique<MenuRunner>(menu_item_view_, 0);
}
void TearDown() override {
widget_->CloseNow();
ViewsTestBase::TearDown();
}
protected:
virtual std::unique_ptr<test::TestMenuDelegate> CreateMenuDelegate() {
return std::make_unique<test::TestMenuDelegate>();
}
private:
// Owned by MenuRunner.
raw_ptr<MenuItemView> menu_item_view_;
std::unique_ptr<test::TestMenuDelegate> menu_delegate_;
std::unique_ptr<MenuRunner> menu_runner_;
std::unique_ptr<Widget> widget_;
};
// Provides assertion coverage for painting, secondary label, minor text and
// icons.
TEST_F(MenuItemViewPaintUnitTest, MinorTextAndIconAssertionCoverage) {
auto AddItem = [this](auto label, auto secondary_label, auto minor_label,
auto minor_icon) {
menu_item_view()->AddMenuItemAt(0, 1000, label, secondary_label,
minor_label, minor_icon, ui::ImageModel(),
views::MenuItemView::Type::kNormal,
ui::NORMAL_SEPARATOR);
};
AddItem(u"No secondary label, no minor content", std::u16string(),
std::u16string(), ui::ImageModel());
AddItem(u"No secondary label, minor text only", std::u16string(),
u"minor text", ui::ImageModel());
AddItem(u"No secondary label, minor icon only", std::u16string(),
std::u16string(),
ui::ImageModel::FromVectorIcon(views::kMenuCheckIcon));
AddItem(u"No secondary label, minor text and icon", std::u16string(),
u"minor text", ui::ImageModel::FromVectorIcon(views::kMenuCheckIcon));
AddItem(u"Secondary label, no minor content", u"secondary label",
std::u16string(), ui::ImageModel());
AddItem(u"Secondary label, minor text only", u"secondary label",
u"minor text", ui::ImageModel());
AddItem(u"Secondary label, minor icon only", u"secondary label",
std::u16string(),
ui::ImageModel::FromVectorIcon(views::kMenuCheckIcon));
AddItem(u"Secondary label, minor text and icon", u"secondary label",
u"minor text", ui::ImageModel::FromVectorIcon(views::kMenuCheckIcon));
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
SkBitmap bitmap;
gfx::Size size = menu_item_view()->GetMirroredBounds().size();
ui::CanvasPainter canvas_painter(&bitmap, size, 1.f, SK_ColorTRANSPARENT,
false);
menu_item_view()->GetSubmenu()->Paint(
PaintInfo::CreateRootPaintInfo(canvas_painter.context(), size));
}
// Provides assertion coverage for painting with custom colors.
// icons.
TEST_F(MenuItemViewPaintUnitTest, CustomColorAssertionCoverage) {
auto AddItem = [this](auto label, auto submenu_background_color,
auto foreground_color, auto selected_color) {
menu_item_view()->AddMenuItemAt(
0, 1000, label, std::u16string(), std::u16string(), ui::ImageModel(),
ui::ImageModel(), views::MenuItemView::Type::kNormal,
ui::NORMAL_SEPARATOR, submenu_background_color, foreground_color,
selected_color);
};
ui::ColorId background_color = ui::kColorComboboxBackground;
ui::ColorId foreground_color = ui::kColorDropdownForeground;
ui::ColorId selected_color = ui::kColorMenuItemForegroundHighlighted;
AddItem(u"No custom colors", absl::nullopt, absl::nullopt, absl::nullopt);
AddItem(u"No selected color", background_color, foreground_color,
absl::nullopt);
AddItem(u"No foreground color", background_color, absl::nullopt,
selected_color);
AddItem(u"No background color", absl::nullopt, foreground_color,
selected_color);
AddItem(u"No background or foreground", absl::nullopt, absl::nullopt,
selected_color);
AddItem(u"No background or selected", absl::nullopt, foreground_color,
absl::nullopt);
AddItem(u"No foreground or selected", background_color, absl::nullopt,
absl::nullopt);
AddItem(u"All colors", background_color, foreground_color, selected_color);
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
SkBitmap bitmap;
gfx::Size size = menu_item_view()->GetMirroredBounds().size();
ui::CanvasPainter canvas_painter(&bitmap, size, 1.f, SK_ColorTRANSPARENT,
false);
menu_item_view()->GetSubmenu()->Paint(
PaintInfo::CreateRootPaintInfo(canvas_painter.context(), size));
}
// Verifies a call to MenuItemView::OnPaint() doesn't trigger a call to
// MenuItemView::submenu_arrow_image_view_::SchedulePaint(). This is a
// regression test for https://crbug.com/1245854.
TEST_F(MenuItemViewPaintUnitTest, DontSchedulePaintFromOnPaint) {
MenuItemView* submenu_item =
menu_item_view()->AppendSubMenu(1, u"My Submenu");
submenu_item->AppendMenuItem(1, u"submenu item 1");
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
ImageView* submenu_arrow_image_view =
TestMenuItemView::submenu_arrow_image_view(submenu_item);
ASSERT_TRUE(submenu_arrow_image_view);
ViewTestApi(submenu_arrow_image_view).ClearNeedsPaint();
// Paint again. As no state has changed since the last paint, this should not
// call SchedulePaint() on the `submenu_arrow_image_view`
gfx::Canvas canvas(submenu_item->size(), 1.f, false /* opaque */);
submenu_item->OnPaint(&canvas);
EXPECT_FALSE(ViewTestApi(submenu_arrow_image_view).needs_paint());
}
// Tests to ensure that selection based state is not updated if a menu item or
// an anscestor item has been scheduled for deletion. This guards against
// removed but not-yet-deleted MenuItemViews using stale model data to update
// state.
TEST_F(MenuItemViewPaintUnitTest,
SelectionBasedStateNotUpdatedWhenScheduledForDeletion) {
MenuItemView* submenu_item =
menu_item_view()->AppendSubMenu(1, u"submenu_item");
MenuItemView* submenu_child =
submenu_item->AppendMenuItem(1, u"submenu_child");
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
// Show both the root and nested menus.
SubmenuView* submenu = submenu_item->GetSubmenu();
MenuHost::InitParams params;
params.parent = widget();
params.bounds = submenu_item->bounds();
submenu->ShowAt(params);
// The selected bit and selection based state should both update for all menu
// items while they and their anscestors remain part of the menu.
EXPECT_FALSE(submenu_item->IsSelected());
EXPECT_FALSE(submenu_item->last_paint_as_selected_for_testing());
submenu_item->SetSelected(true);
EXPECT_TRUE(submenu_item->IsSelected());
EXPECT_TRUE(submenu_item->last_paint_as_selected_for_testing());
submenu_item->SetSelected(false);
EXPECT_FALSE(submenu_item->IsSelected());
EXPECT_FALSE(submenu_item->last_paint_as_selected_for_testing());
EXPECT_FALSE(submenu_child->IsSelected());
EXPECT_FALSE(submenu_child->last_paint_as_selected_for_testing());
submenu_child->SetSelected(true);
EXPECT_TRUE(submenu_child->IsSelected());
EXPECT_TRUE(submenu_child->last_paint_as_selected_for_testing());
submenu_child->SetSelected(false);
EXPECT_FALSE(submenu_child->IsSelected());
EXPECT_FALSE(submenu_child->last_paint_as_selected_for_testing());
// Remove the child items from the root.
menu_item_view()->RemoveAllMenuItems();
// The selected bit should still update but selection based state, proxied by
// `last_paint_as_selected_`, should remain unchanged.
submenu_item->SetSelected(true);
EXPECT_TRUE(submenu_item->IsSelected());
EXPECT_FALSE(submenu_item->last_paint_as_selected_for_testing());
submenu_item->SetSelected(false);
EXPECT_FALSE(submenu_item->IsSelected());
EXPECT_FALSE(submenu_item->last_paint_as_selected_for_testing());
submenu_child->SetSelected(true);
EXPECT_TRUE(submenu_child->IsSelected());
EXPECT_FALSE(submenu_child->last_paint_as_selected_for_testing());
submenu_child->SetSelected(false);
EXPECT_FALSE(submenu_child->IsSelected());
EXPECT_FALSE(submenu_child->last_paint_as_selected_for_testing());
}
TEST_F(MenuItemViewPaintUnitTest, SelectionBasedStateUpdatedWhenIconChanges) {
MenuItemView* child_menu_item =
menu_item_view()->AppendMenuItem(1, u"menu item");
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
EXPECT_FALSE(child_menu_item->last_paint_as_selected_for_testing());
child_menu_item->SetSelected(true);
EXPECT_TRUE(child_menu_item->IsSelected());
EXPECT_TRUE(child_menu_item->last_paint_as_selected_for_testing());
child_menu_item->SetIconView(std::make_unique<ImageView>());
EXPECT_TRUE(child_menu_item->IsSelected());
EXPECT_TRUE(child_menu_item->last_paint_as_selected_for_testing());
}
TEST_F(MenuItemViewPaintUnitTest, SelectionBasedStateUpdatedDuringDragAndDrop) {
MenuItemView* submenu_item =
menu_item_view()->AppendSubMenu(1, u"submenu_item");
MenuItemView* submenu_child1 =
submenu_item->AppendMenuItem(1, u"submenu_child");
MenuItemView* submenu_child2 =
submenu_item->AppendMenuItem(1, u"submenu_child");
menu_runner()->RunMenuAt(widget(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_KEYBOARD);
// Show both the root and nested menus.
SubmenuView* submenu = submenu_item->GetSubmenu();
MenuHost::InitParams params;
params.parent = widget();
params.bounds = submenu_item->bounds();
submenu->ShowAt(params);
EXPECT_FALSE(submenu_child1->last_paint_as_selected_for_testing());
submenu_child1->SetSelected(true);
EXPECT_TRUE(submenu_child1->IsSelected());
EXPECT_TRUE(submenu_child1->last_paint_as_selected_for_testing());
// Setting the drop item to `submenu_child2` should force `submenu_child1` to
// no longer draw as selected.
submenu->SetDropMenuItem(submenu_child2, MenuDelegate::DropPosition::kOn);
EXPECT_FALSE(submenu_child1->last_paint_as_selected_for_testing());
EXPECT_FALSE(submenu_child2->last_paint_as_selected_for_testing());
// Clearing the drop item returns `submenu_child1` to drawing as selected.
submenu->SetDropMenuItem(nullptr, MenuDelegate::DropPosition::kOn);
EXPECT_TRUE(submenu_child1->last_paint_as_selected_for_testing());
EXPECT_FALSE(submenu_child2->last_paint_as_selected_for_testing());
}
// Sets up a custom MenuDelegate that expects functions aren't called. See
// DontAskForFontsWhenAddingSubmenu.
class MenuItemViewAccessTest : public MenuItemViewPaintUnitTest {
public:
protected:
std::unique_ptr<test::TestMenuDelegate> CreateMenuDelegate() override {
return std::make_unique<DisallowMenuDelegate>();
}
private:
class DisallowMenuDelegate : public test::TestMenuDelegate {
public:
const gfx::FontList* GetLabelFontList(int command_id) const override {
EXPECT_NE(1, command_id);
return nullptr;
}
absl::optional<SkColor> GetLabelColor(int command_id) const override {
EXPECT_NE(1, command_id);
return absl::nullopt;
}
};
};
// Verifies AppendSubMenu() doesn't trigger calls to the delegate with the
// command being supplied. The delegate can be called after AppendSubMenu(),
// but not before.
TEST_F(MenuItemViewAccessTest, DontAskForFontsWhenAddingSubmenu) {
menu_item_view()->AppendSubMenu(1, u"My Submenu");
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_item_view_unittest.cc | C++ | unknown | 25,778 |
// 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/menu_model_adapter.h"
#include <limits>
#include <list>
#include <memory>
#include <utility>
#include "base/check.h"
#include "base/notreached.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/models/menu_model.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/view_class_properties.h"
namespace views {
MenuModelAdapter::MenuModelAdapter(ui::MenuModel* menu_model)
: MenuModelAdapter(menu_model, base::RepeatingClosure() /*null callback*/) {
}
MenuModelAdapter::MenuModelAdapter(
ui::MenuModel* menu_model,
base::RepeatingClosure on_menu_closed_callback)
: menu_model_(menu_model),
triggerable_event_flags_(ui::EF_LEFT_MOUSE_BUTTON |
ui::EF_RIGHT_MOUSE_BUTTON),
on_menu_closed_callback_(std::move(on_menu_closed_callback)) {
DCHECK(menu_model);
menu_model_->SetMenuModelDelegate(nullptr);
menu_model_->SetMenuModelDelegate(this);
}
MenuModelAdapter::~MenuModelAdapter() {
if (menu_model_)
menu_model_->SetMenuModelDelegate(nullptr);
}
void MenuModelAdapter::BuildMenu(MenuItemView* menu) {
DCHECK(menu);
// Clear the menu.
if (menu->HasSubmenu())
menu->RemoveAllMenuItems();
// Leave entries in the map if the menu is being shown. This
// allows the map to find the menu model of submenus being closed
// so ui::MenuModel::MenuClosed() can be called.
if (!menu->GetMenuController())
menu_map_.clear();
menu_map_[menu] = menu_model_;
// Repopulate the menu.
BuildMenuImpl(menu, menu_model_);
menu->ChildrenChanged();
}
MenuItemView* MenuModelAdapter::CreateMenu() {
menu_ = new MenuItemView(this);
BuildMenu(menu_);
return menu_;
}
// Static.
MenuItemView* MenuModelAdapter::AddMenuItemFromModelAt(ui::MenuModel* model,
size_t model_index,
MenuItemView* menu,
size_t menu_index,
int item_id) {
absl::optional<MenuItemView::Type> type;
ui::MenuModel::ItemType menu_type = model->GetTypeAt(model_index);
switch (menu_type) {
case ui::MenuModel::TYPE_TITLE:
type = MenuItemView::Type::kTitle;
break;
case ui::MenuModel::TYPE_COMMAND:
case ui::MenuModel::TYPE_BUTTON_ITEM:
type = MenuItemView::Type::kNormal;
break;
case ui::MenuModel::TYPE_CHECK:
type = MenuItemView::Type::kCheckbox;
break;
case ui::MenuModel::TYPE_RADIO:
type = MenuItemView::Type::kRadio;
break;
case ui::MenuModel::TYPE_SEPARATOR:
type = MenuItemView::Type::kSeparator;
break;
case ui::MenuModel::TYPE_SUBMENU:
type = MenuItemView::Type::kSubMenu;
break;
case ui::MenuModel::TYPE_ACTIONABLE_SUBMENU:
type = MenuItemView::Type::kActionableSubMenu;
break;
case ui::MenuModel::TYPE_HIGHLIGHTED:
type = MenuItemView::Type::kHighlighted;
break;
}
if (*type == MenuItemView::Type::kSeparator) {
return menu->AddMenuItemAt(menu_index, item_id, std::u16string(),
std::u16string(), std::u16string(),
ui::ImageModel(), ui::ImageModel(), *type,
model->GetSeparatorTypeAt(model_index));
}
ui::ImageModel icon = model->GetIconAt(model_index);
ui::ImageModel minor_icon = model->GetMinorIconAt(model_index);
auto* menu_item_view = menu->AddMenuItemAt(
menu_index, item_id, model->GetLabelAt(model_index),
model->GetSecondaryLabelAt(model_index),
model->GetMinorTextAt(model_index), minor_icon, icon, *type,
ui::NORMAL_SEPARATOR, model->GetSubmenuBackgroundColorId(model_index),
model->GetForegroundColorId(model_index),
model->GetSelectedBackgroundColorId(model_index));
if (model->IsAlertedAt(model_index))
menu_item_view->SetAlerted();
menu_item_view->set_is_new(model->IsNewFeatureAt(model_index));
menu_item_view->set_may_have_mnemonics(
model->MayHaveMnemonicsAt(model_index));
menu_item_view->SetAccessibleName(model->GetAccessibleNameAt(model_index));
const ui::ElementIdentifier element_id =
model->GetElementIdentifierAt(model_index);
if (element_id)
menu_item_view->SetProperty(kElementIdentifierKey, element_id);
return menu_item_view;
}
// Static.
MenuItemView* MenuModelAdapter::AppendMenuItemFromModel(ui::MenuModel* model,
size_t model_index,
MenuItemView* menu,
int item_id) {
const size_t menu_index =
menu->HasSubmenu() ? menu->GetSubmenu()->children().size() : size_t{0};
return AddMenuItemFromModelAt(model, model_index, menu, menu_index, item_id);
}
MenuItemView* MenuModelAdapter::AppendMenuItem(MenuItemView* menu,
ui::MenuModel* model,
size_t index) {
return AppendMenuItemFromModel(model, index, menu,
model->GetCommandIdAt(index));
}
// MenuModelAdapter, MenuDelegate implementation:
void MenuModelAdapter::ExecuteCommand(int id) {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
model->ActivatedAt(index);
}
void MenuModelAdapter::ExecuteCommand(int id, int mouse_event_flags) {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
model->ActivatedAt(index, mouse_event_flags);
}
bool MenuModelAdapter::IsTriggerableEvent(MenuItemView* source,
const ui::Event& e) {
return e.type() == ui::ET_GESTURE_TAP ||
e.type() == ui::ET_GESTURE_TAP_DOWN ||
(e.IsMouseEvent() && (triggerable_event_flags_ & e.flags()) != 0);
}
bool MenuModelAdapter::GetAccelerator(int id,
ui::Accelerator* accelerator) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
return model->GetAcceleratorAt(index, accelerator);
}
std::u16string MenuModelAdapter::GetLabel(int id) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
return model->GetLabelAt(index);
}
const gfx::FontList* MenuModelAdapter::GetLabelFontList(int id) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) {
const gfx::FontList* font_list = model->GetLabelFontListAt(index);
if (font_list)
return font_list;
}
// This line may be reached for the empty menu item.
return MenuDelegate::GetLabelFontList(id);
}
bool MenuModelAdapter::IsCommandEnabled(int id) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
return model->IsEnabledAt(index);
}
bool MenuModelAdapter::IsCommandVisible(int id) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
return model->IsVisibleAt(index);
}
bool MenuModelAdapter::IsItemChecked(int id) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
CHECK(ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index));
return model->IsItemCheckedAt(index);
}
MenuItemView* MenuModelAdapter::GetSiblingMenu(MenuItemView* menu,
const gfx::Point& screen_point,
MenuAnchorPosition* anchor,
bool* has_mnemonics,
MenuButton** button) {
// Look up the menu model for this menu.
const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator =
menu_map_.find(menu);
if (map_iterator != menu_map_.end()) {
map_iterator->second->MouseOutsideMenu(screen_point);
return nullptr;
}
NOTREACHED();
return nullptr;
}
void MenuModelAdapter::OnUnhandledOpenSubmenu(MenuItemView* menu,
bool is_rtl) {
// Look up the menu model for this menu.
const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator =
menu_map_.find(menu);
if (map_iterator != menu_map_.end()) {
map_iterator->second->UnhandledOpenSubmenu(is_rtl);
return;
}
NOTREACHED();
}
void MenuModelAdapter::OnUnhandledCloseSubmenu(MenuItemView* menu,
bool is_rtl) {
// Look up the menu model for this menu.
const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator =
menu_map_.find(menu);
if (map_iterator != menu_map_.end()) {
map_iterator->second->UnhandledCloseSubmenu(is_rtl);
return;
}
NOTREACHED();
}
bool MenuModelAdapter::GetTextColor(int command_id,
bool is_minor,
bool is_hovered,
SkColor* override_color) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
if (ui::MenuModel::GetModelAndIndexForCommandId(command_id, &model, &index))
return model->GetTextColor(index, is_minor, is_hovered, override_color);
// Return the default color.
return menu_model_->GetBackgroundColor(std::numeric_limits<size_t>::max(),
is_hovered, override_color);
}
bool MenuModelAdapter::GetBackgroundColor(int command_id,
bool is_hovered,
SkColor* override_color) const {
ui::MenuModel* model = menu_model_;
size_t index = 0;
if (ui::MenuModel::GetModelAndIndexForCommandId(command_id, &model, &index))
return model->GetBackgroundColor(index, is_hovered, override_color);
// Return the default color.
return menu_model_->GetBackgroundColor(std::numeric_limits<size_t>::max(),
is_hovered, override_color);
}
void MenuModelAdapter::WillShowMenu(MenuItemView* menu) {
// Look up the menu model for this menu.
const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator =
menu_map_.find(menu);
CHECK(map_iterator != menu_map_.end());
map_iterator->second->MenuWillShow();
}
void MenuModelAdapter::WillHideMenu(MenuItemView* menu) {
// Look up the menu model for this menu.
const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator =
menu_map_.find(menu);
CHECK(map_iterator != menu_map_.end());
map_iterator->second->MenuWillClose();
}
void MenuModelAdapter::OnMenuClosed(MenuItemView* menu) {
if (!on_menu_closed_callback_.is_null())
on_menu_closed_callback_.Run();
}
// MenuModelDelegate overrides:
void MenuModelAdapter::OnMenuStructureChanged() {
if (menu_)
BuildMenu(menu_);
}
void MenuModelAdapter::OnMenuClearingDelegate() {
menu_model_ = nullptr;
}
// MenuModelAdapter, private:
void MenuModelAdapter::BuildMenuImpl(MenuItemView* menu, ui::MenuModel* model) {
DCHECK(menu);
DCHECK(model);
bool has_icons = model->HasIcons();
const size_t item_count = model->GetItemCount();
for (size_t i = 0; i < item_count; ++i) {
MenuItemView* item = AppendMenuItem(menu, model, i);
if (item) {
// Enabled state should be ignored for titles as they are non-interactive.
if (model->GetTypeAt(i) == ui::MenuModel::TYPE_TITLE)
item->SetEnabled(false);
else
item->SetEnabled(model->IsEnabledAt(i));
item->SetVisible(model->IsVisibleAt(i));
}
if (model->GetTypeAt(i) == ui::MenuModel::TYPE_SUBMENU ||
model->GetTypeAt(i) == ui::MenuModel::TYPE_ACTIONABLE_SUBMENU) {
DCHECK(item);
DCHECK(item->GetType() == MenuItemView::Type::kSubMenu ||
item->GetType() == MenuItemView::Type::kActionableSubMenu);
ui::MenuModel* submodel = model->GetSubmenuModelAt(i);
DCHECK(submodel);
BuildMenuImpl(item, submodel);
has_icons = has_icons || item->has_icons();
menu_map_[item] = submodel;
}
}
menu->set_has_icons(has_icons);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_model_adapter.cc | C++ | unknown | 12,819 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_
#include <map>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/models/menu_model_delegate.h"
#include "ui/views/controls/menu/menu_delegate.h"
namespace ui {
class MenuModel;
}
namespace views {
class MenuItemView;
// This class wraps an instance of ui::MenuModel with the views::MenuDelegate
// interface required by views::MenuItemView.
class VIEWS_EXPORT MenuModelAdapter : public MenuDelegate,
public ui::MenuModelDelegate {
public:
// The caller retains ownership of the ui::MenuModel instance and must ensure
// it exists for the lifetime of the adapter. |this| will become the new
// MenuModelDelegate of |menu_model| so that subsequent changes to it get
// reflected in the created MenuItemView.
explicit MenuModelAdapter(ui::MenuModel* menu_model);
MenuModelAdapter(ui::MenuModel* menu_model,
base::RepeatingClosure on_menu_closed_callback);
MenuModelAdapter(const MenuModelAdapter&) = delete;
MenuModelAdapter& operator=(const MenuModelAdapter&) = delete;
~MenuModelAdapter() override;
// Populate a MenuItemView menu with the ui::MenuModel items
// (including submenus).
virtual void BuildMenu(MenuItemView* menu);
// Convenience for creating and populating a menu. The caller owns the
// returned MenuItemView.
MenuItemView* CreateMenu();
void set_triggerable_event_flags(int triggerable_event_flags) {
triggerable_event_flags_ = triggerable_event_flags;
}
int triggerable_event_flags() const { return triggerable_event_flags_; }
// Creates a menu item for the specified entry in the model and adds it as
// a child to |menu| at the specified |menu_index|.
static MenuItemView* AddMenuItemFromModelAt(ui::MenuModel* model,
size_t model_index,
MenuItemView* menu,
size_t menu_index,
int item_id);
// Creates a menu item for the specified entry in the model and appends it as
// a child to |menu|.
static MenuItemView* AppendMenuItemFromModel(ui::MenuModel* model,
size_t model_index,
MenuItemView* menu,
int item_id);
// MenuModelDelegate:
void OnIconChanged(int command_id) override {}
void OnMenuStructureChanged() override;
void OnMenuClearingDelegate() override;
protected:
// Create and add a menu item to |menu| for the item at index |index| in
// |model|. Subclasses override this to allow custom items to be added to the
// menu.
virtual MenuItemView* AppendMenuItem(MenuItemView* menu,
ui::MenuModel* model,
size_t index);
// views::MenuDelegate implementation.
void ExecuteCommand(int id) override;
void ExecuteCommand(int id, int mouse_event_flags) override;
bool IsTriggerableEvent(MenuItemView* source, const ui::Event& e) override;
bool GetAccelerator(int id, ui::Accelerator* accelerator) const override;
std::u16string GetLabel(int id) const override;
const gfx::FontList* GetLabelFontList(int id) const override;
bool IsCommandEnabled(int id) const override;
bool IsCommandVisible(int id) const override;
bool IsItemChecked(int id) const override;
MenuItemView* GetSiblingMenu(MenuItemView* menu,
const gfx::Point& screen_point,
MenuAnchorPosition* anchor,
bool* has_mnemonics,
MenuButton** button) override;
void OnUnhandledOpenSubmenu(MenuItemView* menu, bool is_rtl) override;
void OnUnhandledCloseSubmenu(MenuItemView* menu, bool is_rtl) override;
bool GetTextColor(int command_id,
bool is_minor,
bool is_hovered,
SkColor* override_color) const override;
bool GetBackgroundColor(int command_id,
bool is_hovered,
SkColor* override_color) const override;
void WillShowMenu(MenuItemView* menu) override;
void WillHideMenu(MenuItemView* menu) override;
void OnMenuClosed(MenuItemView* menu) override;
private:
// Implementation of BuildMenu().
void BuildMenuImpl(MenuItemView* menu, ui::MenuModel* model);
// Container of ui::MenuModel pointers as encountered by preorder
// traversal. The first element is always the top-level model
// passed to the constructor.
raw_ptr<ui::MenuModel, DanglingUntriaged> menu_model_;
// Pointer to the MenuItemView created and updated by |this|, but not owned by
// |this|.
raw_ptr<MenuItemView, DanglingUntriaged> menu_;
// Mouse event flags which can trigger menu actions.
int triggerable_event_flags_;
// Map MenuItems to MenuModels. Used to implement WillShowMenu().
std::map<MenuItemView*, ui::MenuModel*> menu_map_;
// Optional callback triggered during OnMenuClosed().
base::RepeatingClosure on_menu_closed_callback_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_model_adapter.h | C++ | unknown | 5,518 |
// 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/menu_model_adapter.h"
#include <memory>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/models/menu_model_delegate.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/test/views_test_base.h"
namespace {
// Base command id for test menu and its submenu.
constexpr int kRootIdBase = 100;
constexpr int kSubmenuIdBase = 200;
constexpr int kActionableSubmenuIdBase = 300;
class MenuModelBase : public ui::MenuModel {
public:
explicit MenuModelBase(int command_id_base)
: command_id_base_(command_id_base) {}
MenuModelBase(const MenuModelBase&) = delete;
MenuModelBase& operator=(const MenuModelBase&) = delete;
~MenuModelBase() override = default;
// ui::MenuModel implementation:
bool HasIcons() const override { return false; }
size_t GetItemCount() const override { return items_.size(); }
ItemType GetTypeAt(size_t index) const override { return items_[index].type; }
ui::MenuSeparatorType GetSeparatorTypeAt(size_t index) const override {
return ui::NORMAL_SEPARATOR;
}
int GetCommandIdAt(size_t index) const override {
return static_cast<int>(index) + command_id_base_;
}
std::u16string GetLabelAt(size_t index) const override {
return items_[index].label;
}
bool IsItemDynamicAt(size_t index) const override { return false; }
const gfx::FontList* GetLabelFontListAt(size_t index) const override {
return nullptr;
}
bool GetAcceleratorAt(size_t index,
ui::Accelerator* accelerator) const override {
return false;
}
bool IsItemCheckedAt(size_t index) const override { return false; }
int GetGroupIdAt(size_t index) const override { return 0; }
ui::ImageModel GetIconAt(size_t index) const override {
return ui::ImageModel();
}
ui::ButtonMenuItemModel* GetButtonMenuItemAt(size_t index) const override {
return nullptr;
}
bool IsEnabledAt(size_t index) const override {
return items_[index].enabled;
}
bool IsVisibleAt(size_t index) const override {
return items_[index].visible;
}
bool IsAlertedAt(size_t index) const override {
return items_[index].alerted;
}
bool IsNewFeatureAt(size_t index) const override {
return items_[index].new_feature;
}
MenuModel* GetSubmenuModelAt(size_t index) const override {
return items_[index].submenu;
}
void ActivatedAt(size_t index) override { set_last_activation(index); }
void ActivatedAt(size_t index, int event_flags) override {
ActivatedAt(index);
}
void MenuWillShow() override {}
void MenuWillClose() override {}
// Item definition.
struct Item {
Item(ItemType item_type,
const std::string& item_label,
ui::MenuModel* item_submenu)
: type(item_type),
label(base::ASCIIToUTF16(item_label)),
submenu(item_submenu),
enabled(true),
visible(true) {}
Item(ItemType item_type,
const std::string& item_label,
ui::MenuModel* item_submenu,
bool enabled,
bool visible)
: type(item_type),
label(base::ASCIIToUTF16(item_label)),
submenu(item_submenu),
enabled(enabled),
visible(visible) {}
ItemType type;
std::u16string label;
raw_ptr<ui::MenuModel> submenu;
bool enabled;
bool visible;
bool alerted = false;
bool new_feature = false;
};
const Item& GetItemDefinition(size_t index) { return items_[index]; }
// Access index argument to ActivatedAt().
absl::optional<size_t> last_activation() const { return last_activation_; }
void set_last_activation(absl::optional<size_t> last_activation) {
last_activation_ = last_activation;
}
protected:
std::vector<Item> items_;
private:
int command_id_base_;
absl::optional<size_t> last_activation_;
};
class SubmenuModel : public MenuModelBase {
public:
SubmenuModel() : MenuModelBase(kSubmenuIdBase) {
items_.emplace_back(TYPE_COMMAND, "submenu item 0", nullptr, false, true);
items_.emplace_back(TYPE_COMMAND, "submenu item 1", nullptr);
items_[1].alerted = true;
}
SubmenuModel(const SubmenuModel&) = delete;
SubmenuModel& operator=(const SubmenuModel&) = delete;
~SubmenuModel() override = default;
};
class ActionableSubmenuModel : public MenuModelBase {
public:
ActionableSubmenuModel() : MenuModelBase(kActionableSubmenuIdBase) {
items_.emplace_back(TYPE_COMMAND, "actionable submenu item 0", nullptr);
items_.emplace_back(TYPE_COMMAND, "actionable submenu item 1", nullptr);
items_[1].new_feature = true;
}
ActionableSubmenuModel(const ActionableSubmenuModel&) = delete;
ActionableSubmenuModel& operator=(const ActionableSubmenuModel&) = delete;
~ActionableSubmenuModel() override = default;
};
class RootModel : public MenuModelBase {
public:
RootModel() : MenuModelBase(kRootIdBase) {
submenu_model_ = std::make_unique<SubmenuModel>();
actionable_submenu_model_ = std::make_unique<ActionableSubmenuModel>();
items_.emplace_back(TYPE_COMMAND, "command 0", nullptr, false, false);
items_.emplace_back(TYPE_CHECK, "check 1", nullptr);
items_.emplace_back(TYPE_SEPARATOR, "", nullptr);
items_.emplace_back(TYPE_SUBMENU, "submenu 3", submenu_model_.get());
items_.emplace_back(TYPE_RADIO, "radio 4", nullptr);
items_.emplace_back(TYPE_ACTIONABLE_SUBMENU, "actionable 5",
actionable_submenu_model_.get());
}
RootModel(const RootModel&) = delete;
RootModel& operator=(const RootModel&) = delete;
~RootModel() override = default;
private:
std::unique_ptr<MenuModel> submenu_model_;
std::unique_ptr<MenuModel> actionable_submenu_model_;
};
void CheckSubmenu(const RootModel& model,
views::MenuItemView* menu,
views::MenuModelAdapter* delegate,
int submenu_id,
size_t expected_children,
size_t submenu_model_index,
int id) {
views::MenuItemView* submenu = menu->GetMenuItemByID(submenu_id);
views::SubmenuView* subitem_container = submenu->GetSubmenu();
EXPECT_EQ(expected_children, subitem_container->children().size());
MenuModelBase* submodel =
static_cast<MenuModelBase*>(model.GetSubmenuModelAt(submenu_model_index));
EXPECT_TRUE(submodel);
for (size_t i = 0; i < subitem_container->children().size(); ++i, ++id) {
const MenuModelBase::Item& model_item = submodel->GetItemDefinition(i);
views::MenuItemView* item = menu->GetMenuItemByID(id);
if (!item) {
EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, model_item.type);
continue;
}
// Check placement.
EXPECT_EQ(i, submenu->GetSubmenu()->GetIndexOf(item));
// Check type.
switch (model_item.type) {
case ui::MenuModel::TYPE_TITLE:
EXPECT_EQ(views::MenuItemView::Type::kTitle, item->GetType());
break;
case ui::MenuModel::TYPE_COMMAND:
EXPECT_EQ(views::MenuItemView::Type::kNormal, item->GetType());
break;
case ui::MenuModel::TYPE_CHECK:
EXPECT_EQ(views::MenuItemView::Type::kCheckbox, item->GetType());
break;
case ui::MenuModel::TYPE_RADIO:
EXPECT_EQ(views::MenuItemView::Type::kRadio, item->GetType());
break;
case ui::MenuModel::TYPE_SEPARATOR:
case ui::MenuModel::TYPE_BUTTON_ITEM:
break;
case ui::MenuModel::TYPE_SUBMENU:
EXPECT_EQ(views::MenuItemView::Type::kSubMenu, item->GetType());
break;
case ui::MenuModel::TYPE_ACTIONABLE_SUBMENU:
EXPECT_EQ(views::MenuItemView::Type::kActionableSubMenu,
item->GetType());
break;
case ui::MenuModel::TYPE_HIGHLIGHTED:
EXPECT_EQ(views::MenuItemView::Type::kHighlighted, item->GetType());
break;
}
// Check enabled state.
EXPECT_EQ(model_item.enabled, item->GetEnabled());
// Check visibility.
EXPECT_EQ(model_item.visible, item->GetVisible());
// Check alert state.
EXPECT_EQ(model_item.alerted, item->is_alerted());
// Check new feature flag.
EXPECT_EQ(model_item.new_feature, item->is_new());
// Check activation.
static_cast<views::MenuDelegate*>(delegate)->ExecuteCommand(id);
EXPECT_EQ(i, submodel->last_activation());
submodel->set_last_activation(absl::nullopt);
}
}
} // namespace
namespace views {
using MenuModelAdapterTest = ViewsTestBase;
TEST_F(MenuModelAdapterTest, BasicTest) {
// Build model and adapter.
RootModel model;
views::MenuModelAdapter delegate(&model);
// Create menu. Build menu twice to check that rebuilding works properly.
MenuItemView* menu = new views::MenuItemView(&delegate);
// MenuRunner takes ownership of menu.
std::unique_ptr<MenuRunner> menu_runner(new MenuRunner(menu, 0));
delegate.BuildMenu(menu);
delegate.BuildMenu(menu);
EXPECT_TRUE(menu->HasSubmenu());
// Check top level menu items.
views::SubmenuView* item_container = menu->GetSubmenu();
EXPECT_EQ(6u, item_container->children().size());
int id = kRootIdBase;
for (size_t i = 0; i < item_container->children().size(); ++i, ++id) {
const MenuModelBase::Item& model_item = model.GetItemDefinition(i);
MenuItemView* item = menu->GetMenuItemByID(id);
if (!item) {
EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, model_item.type);
continue;
}
// Check placement.
EXPECT_EQ(i, menu->GetSubmenu()->GetIndexOf(item));
// Check type.
switch (model_item.type) {
case ui::MenuModel::TYPE_TITLE:
EXPECT_EQ(views::MenuItemView::Type::kTitle, item->GetType());
break;
case ui::MenuModel::TYPE_COMMAND:
EXPECT_EQ(views::MenuItemView::Type::kNormal, item->GetType());
break;
case ui::MenuModel::TYPE_CHECK:
EXPECT_EQ(views::MenuItemView::Type::kCheckbox, item->GetType());
break;
case ui::MenuModel::TYPE_RADIO:
EXPECT_EQ(views::MenuItemView::Type::kRadio, item->GetType());
break;
case ui::MenuModel::TYPE_SEPARATOR:
case ui::MenuModel::TYPE_BUTTON_ITEM:
break;
case ui::MenuModel::TYPE_SUBMENU:
EXPECT_EQ(views::MenuItemView::Type::kSubMenu, item->GetType());
break;
case ui::MenuModel::TYPE_ACTIONABLE_SUBMENU:
EXPECT_EQ(views::MenuItemView::Type::kActionableSubMenu,
item->GetType());
break;
case ui::MenuModel::TYPE_HIGHLIGHTED:
EXPECT_EQ(views::MenuItemView::Type::kHighlighted, item->GetType());
break;
}
// Check enabled state.
EXPECT_EQ(model_item.enabled, item->GetEnabled());
// Check visibility.
EXPECT_EQ(model_item.visible, item->GetVisible());
// Check alert state.
EXPECT_EQ(model_item.alerted, item->is_alerted());
// Check new feature flag.
EXPECT_EQ(model_item.new_feature, item->is_new());
// Check activation.
static_cast<views::MenuDelegate*>(&delegate)->ExecuteCommand(id);
EXPECT_EQ(i, model.last_activation());
model.set_last_activation(absl::nullopt);
}
// Check the submenu.
const int submenu_index = 3;
CheckSubmenu(model, menu, &delegate, kRootIdBase + submenu_index, 2,
submenu_index, kSubmenuIdBase);
// Check the actionable submenu.
const int actionable_submenu_index = 5;
CheckSubmenu(model, menu, &delegate, kRootIdBase + actionable_submenu_index,
2, actionable_submenu_index, kActionableSubmenuIdBase);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_model_adapter_unittest.cc | C++ | unknown | 11,882 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_H_
#include <memory>
namespace views {
class MenuController;
class Widget;
// A MenuPreTargetHandler is responsible for intercepting events destined for
// another widget (the menu's owning widget) and letting the menu's controller
// try dispatching them first.
class MenuPreTargetHandler {
public:
MenuPreTargetHandler(const MenuPreTargetHandler&) = delete;
MenuPreTargetHandler& operator=(const MenuPreTargetHandler&) = delete;
virtual ~MenuPreTargetHandler() = default;
// There are separate implementations of this method for Aura platforms and
// for Mac.
static std::unique_ptr<MenuPreTargetHandler> Create(
MenuController* controller,
Widget* owner);
protected:
MenuPreTargetHandler() = default;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_pre_target_handler.h | C++ | unknown | 1,085 |
// Copyright 2016 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/menu_pre_target_handler_aura.h"
#include <memory>
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/public/activation_client.h"
namespace views {
namespace {
aura::Window* GetOwnerRootWindow(views::Widget* owner) {
return owner ? owner->GetNativeWindow()->GetRootWindow() : nullptr;
}
} // namespace
MenuPreTargetHandlerAura::MenuPreTargetHandlerAura(MenuController* controller,
Widget* owner)
: controller_(controller), root_(GetOwnerRootWindow(owner)) {
if (root_) {
wm::GetActivationClient(root_)->AddObserver(this);
root_->AddObserver(this);
} else {
// This should only happen in cases like when context menus are shown for
// Windows OS system tray items and there is no parent window.
}
aura::Env::GetInstance()->AddPreTargetHandler(
this, ui::EventTarget::Priority::kSystem);
}
MenuPreTargetHandlerAura::~MenuPreTargetHandlerAura() {
aura::Env::GetInstance()->RemovePreTargetHandler(this);
Cleanup();
}
void MenuPreTargetHandlerAura::OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
if (!controller_->drag_in_progress())
controller_->Cancel(MenuController::ExitType::kAll);
}
void MenuPreTargetHandlerAura::OnWindowDestroying(aura::Window* window) {
Cleanup();
}
void MenuPreTargetHandlerAura::OnCancelMode(ui::CancelModeEvent* event) {
controller_->Cancel(MenuController::ExitType::kAll);
}
void MenuPreTargetHandlerAura::OnKeyEvent(ui::KeyEvent* event) {
controller_->OnWillDispatchKeyEvent(event);
}
void MenuPreTargetHandlerAura::Cleanup() {
if (!root_)
return;
// The ActivationClient may have been destroyed by the time we get here.
wm::ActivationClient* client = wm::GetActivationClient(root_);
if (client)
client->RemoveObserver(this);
root_->RemoveObserver(this);
root_ = nullptr;
}
// static
std::unique_ptr<MenuPreTargetHandler> MenuPreTargetHandler::Create(
MenuController* controller,
Widget* owner) {
return std::make_unique<MenuPreTargetHandlerAura>(controller, owner);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_pre_target_handler_aura.cc | C++ | unknown | 2,445 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_AURA_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_AURA_H_
#include "base/memory/raw_ptr.h"
#include "ui/aura/window_observer.h"
#include "ui/events/event_handler.h"
#include "ui/views/controls/menu/menu_pre_target_handler.h"
#include "ui/views/views_export.h"
#include "ui/wm/public/activation_change_observer.h"
namespace aura {
class Window;
} // namespace aura
namespace views {
class MenuController;
class Widget;
// MenuPreTargetHandlerAura is used to observe activation changes, cancel
// events, and root window destruction, to shutdown the menu.
//
// Additionally handles key events to provide accelerator support to menus.
class VIEWS_EXPORT MenuPreTargetHandlerAura
: public wm::ActivationChangeObserver,
public aura::WindowObserver,
public ui::EventHandler,
public MenuPreTargetHandler {
public:
MenuPreTargetHandlerAura(MenuController* controller, Widget* owner);
MenuPreTargetHandlerAura(const MenuPreTargetHandlerAura&) = delete;
MenuPreTargetHandlerAura& operator=(const MenuPreTargetHandlerAura&) = delete;
~MenuPreTargetHandlerAura() override;
// aura::client:ActivationChangeObserver:
void OnWindowActivated(wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) override;
// aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override;
// ui::EventHandler:
void OnCancelMode(ui::CancelModeEvent* event) override;
void OnKeyEvent(ui::KeyEvent* event) override;
private:
void Cleanup();
raw_ptr<MenuController> controller_;
raw_ptr<aura::Window> root_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_pre_target_handler_aura.h | C++ | unknown | 1,964 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_MAC_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_MAC_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/controls/menu/menu_pre_target_handler.h"
namespace ui {
class Event;
} // namespace ui
namespace views {
// Stops dispatch of key events when they are handled by MenuController.
// While similar to EventMonitorMac, that class does not allow dispatch changes.
class MenuPreTargetHandlerMac : public MenuPreTargetHandler,
public NativeWidgetMacEventMonitor::Client {
public:
MenuPreTargetHandlerMac(MenuController* controller, Widget* widget);
MenuPreTargetHandlerMac(const MenuPreTargetHandlerMac&) = delete;
MenuPreTargetHandlerMac& operator=(const MenuPreTargetHandlerMac&) = delete;
~MenuPreTargetHandlerMac() override;
private:
// public:
void NativeWidgetMacEventMonitorOnEvent(ui::Event* event,
bool* was_handled) final;
std::unique_ptr<NativeWidgetMacEventMonitor> monitor_;
const raw_ptr<MenuController> controller_; // Weak. Owns |this|.
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_PRE_TARGET_HANDLER_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_pre_target_handler_mac.h | C++ | unknown | 1,440 |
// Copyright 2018 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/menu_pre_target_handler_mac.h"
#import <Cocoa/Cocoa.h>
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/widget/widget.h"
namespace views {
MenuPreTargetHandlerMac::MenuPreTargetHandlerMac(MenuController* controller,
Widget* widget)
: controller_(controller) {
gfx::NativeWindow target_window = widget->GetNativeWindow();
auto* host =
views::NativeWidgetMacNSWindowHost::GetFromNativeWindow(target_window);
CHECK(host);
monitor_ = host->AddEventMonitor(this);
}
MenuPreTargetHandlerMac::~MenuPreTargetHandlerMac() = default;
void MenuPreTargetHandlerMac::NativeWidgetMacEventMonitorOnEvent(
ui::Event* ui_event,
bool* was_handled) {
if (*was_handled)
return;
if (!ui_event->IsKeyEvent())
return;
*was_handled = controller_->OnWillDispatchKeyEvent(ui_event->AsKeyEvent()) !=
ui::POST_DISPATCH_PERFORM_DEFAULT;
}
// static
std::unique_ptr<MenuPreTargetHandler> MenuPreTargetHandler::Create(
MenuController* controller,
Widget* widget) {
return std::make_unique<MenuPreTargetHandlerMac>(controller, widget);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_pre_target_handler_mac.mm | Objective-C++ | unknown | 1,476 |
// 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/menu_runner.h"
#include <utility>
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/controls/menu/menu_runner_handler.h"
#include "ui/views/controls/menu/menu_runner_impl.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget.h"
namespace views {
MenuRunner::MenuRunner(ui::MenuModel* menu_model,
int32_t run_types,
base::RepeatingClosure on_menu_closed_callback)
: run_types_(run_types),
impl_(internal::MenuRunnerImplInterface::Create(
menu_model,
run_types,
std::move(on_menu_closed_callback))) {}
MenuRunner::MenuRunner(MenuItemView* menu_view, int32_t run_types)
: run_types_(run_types), impl_(new internal::MenuRunnerImpl(menu_view)) {}
MenuRunner::~MenuRunner() {
impl_->Release();
}
void MenuRunner::RunMenuAt(Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
ui::MenuSourceType source_type,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners) {
// Do not attempt to show the menu if the application is currently shutting
// down. MenuDelegate::OnMenuClosed would not be called.
if (ViewsDelegate::GetInstance() &&
ViewsDelegate::GetInstance()->IsShuttingDown()) {
return;
}
// If we are shown on mouse press, we will eat the subsequent mouse down and
// the parent widget will not be able to reset its state (it might have mouse
// capture from the mouse down). So we clear its state here.
if (parent && parent->GetRootView()) {
auto* root_view = parent->GetRootView();
if (run_types_ & MenuRunner::SEND_GESTURE_EVENTS_TO_OWNER) {
// In this case, the menu owner instead of the menu should handle the
// incoming gesture events. Therefore we do not need to reset the gesture
// handler of `root_view`.
root_view->SetMouseHandler(nullptr);
} else {
root_view->SetMouseAndGestureHandler(nullptr);
}
}
if (runner_handler_.get()) {
runner_handler_->RunMenuAt(parent, button_controller, bounds, anchor,
source_type, run_types_);
return;
}
if ((run_types_ & CONTEXT_MENU) && !(run_types_ & FIXED_ANCHOR)) {
switch (source_type) {
case ui::MENU_SOURCE_NONE:
case ui::MENU_SOURCE_KEYBOARD:
case ui::MENU_SOURCE_MOUSE:
anchor = MenuAnchorPosition::kTopLeft;
break;
case ui::MENU_SOURCE_TOUCH:
case ui::MENU_SOURCE_TOUCH_EDIT_MENU:
anchor = MenuAnchorPosition::kBottomCenter;
break;
default:
break;
}
}
impl_->RunMenuAt(parent, button_controller, bounds, anchor, run_types_,
native_view_for_gestures, parent_widget, corners);
}
bool MenuRunner::IsRunning() const {
return impl_->IsRunning();
}
void MenuRunner::Cancel() {
impl_->Cancel();
}
base::TimeTicks MenuRunner::closing_event_time() const {
return impl_->GetClosingEventTime();
}
void MenuRunner::SetRunnerHandler(
std::unique_ptr<MenuRunnerHandler> runner_handler) {
runner_handler_ = std::move(runner_handler);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner.cc | C++ | unknown | 3,572 |
// 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.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
#include <stdint.h>
#include <memory>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/views_export.h"
namespace base {
class TimeTicks;
}
namespace gfx {
class Rect;
} // namespace gfx
namespace ui {
class MenuModel;
}
namespace views {
class MenuButtonController;
class MenuItemView;
class MenuRunnerHandler;
class Widget;
namespace internal {
class MenuRunnerImplInterface;
}
namespace test {
class MenuRunnerTestAPI;
}
// MenuRunner is responsible for showing (running) the menu and additionally
// owning the MenuItemView. It is safe to delete MenuRunner at any point, but
// MenuRunner will not notify you of the closure caused by a deletion.
// If MenuRunner is deleted while the menu is showing the delegate of the menu
// is reset. This is done to ensure delegates aren't notified after they may
// have been deleted.
//
// Similarly you should avoid creating MenuRunner on the stack. Doing so means
// MenuRunner may not be immediately destroyed if your object is destroyed,
// resulting in possible callbacks to your now deleted object. Instead you
// should define MenuRunner as a scoped_ptr in your class so that when your
// object is destroyed MenuRunner initiates the proper cleanup and ensures your
// object isn't accessed again.
class VIEWS_EXPORT MenuRunner {
public:
enum RunTypes {
NO_FLAGS = 0,
// The menu has mnemonics.
HAS_MNEMONICS = 1 << 0,
// The menu is a nested context menu. For example, click a folder on the
// bookmark bar, then right click an entry to get its context menu.
IS_NESTED = 1 << 1,
// Used for showing a menu during a drop operation. This does NOT block the
// caller, instead the delegate is notified when the menu closes via the
// DropMenuClosed method.
FOR_DROP = 1 << 2,
// The menu is a context menu (not necessarily nested), for example right
// click on a link on a website in the browser.
CONTEXT_MENU = 1 << 3,
// The menu should behave like a Windows native Combobox dropdow menu.
// This behavior includes accepting the pending item and closing on F4.
COMBOBOX = 1 << 4,
// A child view is performing a drag-and-drop operation, so the menu should
// stay open (even if it doesn't receive drag updated events). In this case,
// the caller is responsible for closing the menu upon completion of the
// drag-and-drop.
NESTED_DRAG = 1 << 5,
// Menu with fixed anchor position, so |MenuRunner| will not attempt to
// adjust the anchor point. For example the context menu of shelf item.
FIXED_ANCHOR = 1 << 6,
// The menu's owner could be in the middle of a gesture when the menu opens
// and can use this flag to continue the gesture. For example, Chrome OS's
// shelf uses the flag to continue dragging an item without lifting the
// finger after the context menu of the item is opened.
SEND_GESTURE_EVENTS_TO_OWNER = 1 << 7,
// Applying the system UI specific layout to the context menu. This should
// be set for the context menu inside system UI only (e.g, the context menu
// while right clicking the wallpaper of a ChromeBook). Thus, this can be
// used to differentiate the context menu inside system UI from others. It
// is useful if we want to customize some attributes of the context menu
// inside system UI, e.g, colors.
USE_ASH_SYS_UI_LAYOUT = 1 << 8,
// Similar to COMBOBOX, but does not capture the mouse and lets some keys
// propagate back to the parent so the combobox content can be edited even
// while the menu is open.
EDITABLE_COMBOBOX = 1 << 9,
// Indicates that the menu should show mnemonics.
SHOULD_SHOW_MNEMONICS = 1 << 10,
};
// Creates a new MenuRunner, which may use a native menu if available.
// |run_types| is a bitmask of RunTypes. If provided,
// |on_menu_closed_callback| is invoked when the menu is closed.
// The MenuModelDelegate of |menu_model| will be overwritten by this call.
MenuRunner(ui::MenuModel* menu_model,
int32_t run_types,
base::RepeatingClosure on_menu_closed_callback =
base::RepeatingClosure());
// Creates a runner for a custom-created toolkit-views menu.
MenuRunner(MenuItemView* menu, int32_t run_types);
MenuRunner(const MenuRunner&) = delete;
MenuRunner& operator=(const MenuRunner&) = delete;
~MenuRunner();
// Runs the menu. MenuDelegate::OnMenuClosed will be notified of the results.
// If `anchor` uses a `BUBBLE_..` type, the bounds will get determined by
// using `bounds` as the thing to point at in screen coordinates.
// `native_view_for_gestures` is a NativeView that is used for cases where the
// surface hosting the menu has a different gfx::NativeView than the `parent`.
// This is required to correctly route gesture events to the correct
// NativeView in the cases where the surface hosting the menu is a
// WebContents.
// `corners` assigns the customized `RoundedCornersF` to the context menu. If
// it's set, the passed in corner will be used to render each corner radius of
// the context menu. This only works when using `USE_ASH_SYS_UI_LAYOUT`.
// Note that this is a blocking call for a native menu on Mac. See
// http://crbug.com/682544.
void RunMenuAt(Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
ui::MenuSourceType source_type,
gfx::NativeView native_view_for_gestures = nullptr,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget,
absl::optional<gfx::RoundedCornersF> corners = absl::nullopt);
// Returns true if we're in a nested run loop running the menu.
bool IsRunning() const;
// Hides and cancels the menu. This does nothing if the menu is not open.
void Cancel();
// Returns the time from the event which closed the menu - or 0.
base::TimeTicks closing_event_time() const;
private:
friend class test::MenuRunnerTestAPI;
// Sets an implementation of RunMenuAt. This is intended to be used at test.
void SetRunnerHandler(std::unique_ptr<MenuRunnerHandler> runner_handler);
const int32_t run_types_;
// We own this. No scoped_ptr because it is destroyed by calling Release().
raw_ptr<internal::MenuRunnerImplInterface, DanglingUntriaged> impl_;
// An implementation of RunMenuAt. This is usually NULL and ignored. If this
// is not NULL, this implementation will be used.
std::unique_ptr<MenuRunnerHandler> runner_handler_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner.h | C++ | unknown | 7,202 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#import "base/task/single_thread_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#import "ui/views/controls/menu/menu_runner_impl_cocoa.h"
#import <Cocoa/Cocoa.h>
#include "base/functional/bind.h"
#include "base/i18n/rtl.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/test_timeouts.h"
#import "testing/gtest_mac.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/events/event_utils.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/views/controls/menu/menu_cocoa_watcher_mac.h"
#include "ui/views/controls/menu/menu_runner_impl_adapter.h"
#include "ui/views/test/views_test_base.h"
namespace views::test {
namespace {
constexpr int kTestCommandId = 0;
class TestModel : public ui::SimpleMenuModel {
public:
TestModel() : ui::SimpleMenuModel(&delegate_), delegate_(this) {}
TestModel(const TestModel&) = delete;
TestModel& operator=(const TestModel&) = delete;
void set_checked_command(int command) { checked_command_ = command; }
void set_menu_open_callback(base::OnceClosure callback) {
menu_open_callback_ = std::move(callback);
}
private:
class Delegate : public ui::SimpleMenuModel::Delegate {
public:
explicit Delegate(TestModel* model) : model_(model) {}
bool IsCommandIdChecked(int command_id) const override {
return command_id == model_->checked_command_;
}
Delegate(const Delegate&) = delete;
Delegate& operator=(const Delegate&) = delete;
bool IsCommandIdEnabled(int command_id) const override { return true; }
void ExecuteCommand(int command_id, int event_flags) override {}
void OnMenuWillShow(SimpleMenuModel* source) override {
if (!model_->menu_open_callback_.is_null())
std::move(model_->menu_open_callback_).Run();
}
bool GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) const override {
if (command_id == kTestCommandId) {
*accelerator = ui::Accelerator(ui::VKEY_E, ui::EF_CONTROL_DOWN);
return true;
}
return false;
}
private:
raw_ptr<TestModel> model_;
};
private:
int checked_command_ = -1;
Delegate delegate_;
base::OnceClosure menu_open_callback_;
};
enum class MenuType { NATIVE, VIEWS };
std::string MenuTypeToString(::testing::TestParamInfo<MenuType> info) {
return info.param == MenuType::VIEWS ? "VIEWS_MenuItemView" : "NATIVE_NSMenu";
}
} // namespace
class MenuRunnerCocoaTest : public ViewsTestBase,
public ::testing::WithParamInterface<MenuType> {
public:
static constexpr int kWindowHeight = 200;
static constexpr int kWindowOffset = 100;
MenuRunnerCocoaTest() = default;
MenuRunnerCocoaTest(const MenuRunnerCocoaTest&) = delete;
MenuRunnerCocoaTest& operator=(const MenuRunnerCocoaTest&) = delete;
~MenuRunnerCocoaTest() override = default;
void SetUp() override {
const int kWindowWidth = 300;
ViewsTestBase::SetUp();
menu_ = std::make_unique<TestModel>();
menu_->AddCheckItem(kTestCommandId, u"Menu Item");
parent_ = new views::Widget();
parent_->Init(CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS));
parent_->SetBounds(
gfx::Rect(kWindowOffset, kWindowOffset, kWindowWidth, kWindowHeight));
parent_->Show();
native_view_subview_count_ =
[[parent_->GetNativeView().GetNativeNSView() subviews] count];
base::RepeatingClosure on_close = base::BindRepeating(
&MenuRunnerCocoaTest::MenuCloseCallback, base::Unretained(this));
if (GetParam() == MenuType::NATIVE)
runner_ = new internal::MenuRunnerImplCocoa(menu_.get(), on_close);
else
runner_ = new internal::MenuRunnerImplAdapter(menu_.get(), on_close);
EXPECT_FALSE(runner_->IsRunning());
}
void TearDown() override {
EXPECT_EQ(native_view_subview_count_,
[[parent_->GetNativeView().GetNativeNSView() subviews] count]);
if (runner_) {
runner_->Release();
runner_ = nullptr;
}
// Clean up for tests that set the notification filter.
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::DontIgnoreNotifications);
parent_->CloseNow();
ViewsTestBase::TearDown();
}
int IsAsync() const { return GetParam() == MenuType::VIEWS; }
// Runs the menu after registering |callback| as the menu open callback.
void RunMenu(base::OnceClosure callback) {
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::IgnoreAllNotifications);
base::OnceClosure wrapped_callback = base::BindOnce(
[](base::OnceClosure cb) {
// Ignore app activation notifications while the test is running (all
// others are OK).
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::IgnoreWorkspaceNotifications);
std::move(cb).Run();
},
std::move(callback));
if (IsAsync()) {
// Cancelling an async menu under MenuControllerCocoa::OpenMenuImpl()
// (which invokes WillShowMenu()) will cause a UAF when that same function
// tries to show the menu. So post a task instead.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(wrapped_callback));
} else {
menu_->set_menu_open_callback(
base::BindOnce(&MenuRunnerCocoaTest::RunMenuWrapperCallback,
base::Unretained(this), std::move(wrapped_callback)));
}
runner_->RunMenuAt(parent_, nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, MenuRunner::CONTEXT_MENU,
nullptr);
MaybeRunAsync();
}
// Runs then cancels a combobox menu and captures the frame of the anchoring
// view.
void RunMenuAt(const gfx::Rect& anchor) {
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::IgnoreAllNotifications);
last_anchor_frame_ = NSZeroRect;
base::OnceClosure callback = base::BindOnce(
[](MenuRunnerCocoaTest* test) {
// Ignore app activation notifications while the test is running (all
// others are OK).
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::IgnoreWorkspaceNotifications);
test->ComboboxRunMenuAtCallback();
},
base::Unretained(this));
if (IsAsync()) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(callback));
} else {
menu_->set_menu_open_callback(std::move(callback));
}
runner_->RunMenuAt(parent_, nullptr, anchor, MenuAnchorPosition::kTopLeft,
MenuRunner::COMBOBOX, nullptr);
MaybeRunAsync();
}
void MenuCancelCallback() {
runner_->Cancel();
if (IsAsync()) {
// Async menus report their cancellation immediately.
EXPECT_FALSE(runner_->IsRunning());
} else {
// For a synchronous menu, MenuRunner::IsRunning() should return true
// immediately after MenuRunner::Cancel() since the menu message loop has
// not yet terminated. It has only been marked for termination.
EXPECT_TRUE(runner_->IsRunning());
}
}
void MenuDeleteCallback() {
runner_->Release();
runner_ = nullptr;
// Deleting an async menu intentionally does not invoke MenuCloseCallback().
// (The callback is typically a method on something in the process of being
// destroyed). So invoke QuitAsyncRunLoop() here as well.
QuitAsyncRunLoop();
}
NSMenu* GetNativeNSMenu() {
if (GetParam() == MenuType::VIEWS)
return nil;
internal::MenuRunnerImplCocoa* cocoa_runner =
static_cast<internal::MenuRunnerImplCocoa*>(runner_);
return [cocoa_runner->menu_controller_ menu];
}
void ModelDeleteThenSelectItemCallback() {
// AppKit may retain a reference to the NSMenu.
base::scoped_nsobject<NSMenu> native_menu(GetNativeNSMenu(),
base::scoped_policy::RETAIN);
// A View showing a menu typically owns a MenuRunner unique_ptr, which will
// will be destroyed (releasing the MenuRunnerImpl) alongside the MenuModel.
runner_->Release();
runner_ = nullptr;
menu_ = nullptr;
// The menu is closing (yet "alive"), but the model is destroyed. The user
// may have already made an event to select an item in the menu. This
// doesn't bother views menus (see MenuRunnerImpl::empty_delegate_) but
// Cocoa menu items are refcounted and have access to a raw weak pointer in
// the MenuController.
if (GetParam() == MenuType::VIEWS) {
QuitAsyncRunLoop();
return;
}
EXPECT_TRUE(native_menu.get());
// Simulate clicking the item using its accelerator.
NSEvent* accelerator = cocoa_test_event_utils::KeyEventWithKeyCode(
'e', 'e', NSEventTypeKeyDown, NSEventModifierFlagCommand);
[native_menu performKeyEquivalent:accelerator];
}
void MenuCancelAndDeleteCallback() {
runner_->Cancel();
runner_->Release();
runner_ = nullptr;
}
protected:
std::unique_ptr<TestModel> menu_;
raw_ptr<internal::MenuRunnerImplInterface> runner_ = nullptr;
raw_ptr<views::Widget> parent_ = nullptr;
NSRect last_anchor_frame_ = NSZeroRect;
NSUInteger native_view_subview_count_ = 0;
int menu_close_count_ = 0;
private:
void RunMenuWrapperCallback(base::OnceClosure callback) {
EXPECT_TRUE(runner_->IsRunning());
std::move(callback).Run();
}
void ComboboxRunMenuAtCallback() {
NSArray* subviews = [parent_->GetNativeView().GetNativeNSView() subviews];
// An anchor view should only be added for Native menus.
if (GetParam() == MenuType::NATIVE) {
ASSERT_EQ(native_view_subview_count_ + 1, [subviews count]);
last_anchor_frame_ = [subviews[native_view_subview_count_] frame];
} else {
EXPECT_EQ(native_view_subview_count_, [subviews count]);
}
runner_->Cancel();
}
// Run a nested run loop so that async and sync menus can be tested the
// same way.
void MaybeRunAsync() {
if (!IsAsync())
return;
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, quit_closure_, TestTimeouts::action_timeout());
run_loop.Run();
// |quit_closure_| should be run by QuitAsyncRunLoop(), not the timeout.
EXPECT_TRUE(quit_closure_.is_null());
}
void QuitAsyncRunLoop() {
if (!IsAsync()) {
EXPECT_TRUE(quit_closure_.is_null());
return;
}
ASSERT_FALSE(quit_closure_.is_null());
quit_closure_.Run();
quit_closure_.Reset();
}
void MenuCloseCallback() {
++menu_close_count_;
QuitAsyncRunLoop();
}
base::RepeatingClosure quit_closure_;
};
TEST_P(MenuRunnerCocoaTest, RunMenuAndCancel) {
base::TimeTicks min_time = ui::EventTimeForNow();
RunMenu(base::BindOnce(&MenuRunnerCocoaTest::MenuCancelCallback,
base::Unretained(this)));
EXPECT_EQ(1, menu_close_count_);
EXPECT_FALSE(runner_->IsRunning());
if (GetParam() == MenuType::VIEWS) {
// MenuItemView's MenuRunnerImpl gets the closing time from
// MenuControllerCocoa:: closing_event_time(). This is is reset on show, but
// only updated when an event closes the menu -- not a cancellation.
EXPECT_EQ(runner_->GetClosingEventTime(), base::TimeTicks());
} else {
EXPECT_GE(runner_->GetClosingEventTime(), min_time);
}
EXPECT_LE(runner_->GetClosingEventTime(), ui::EventTimeForNow());
// Cancel again.
runner_->Cancel();
EXPECT_FALSE(runner_->IsRunning());
EXPECT_EQ(1, menu_close_count_);
}
TEST_P(MenuRunnerCocoaTest, RunMenuAndDelete) {
RunMenu(base::BindOnce(&MenuRunnerCocoaTest::MenuDeleteCallback,
base::Unretained(this)));
// Note the close callback is NOT invoked for deleted menus.
EXPECT_EQ(0, menu_close_count_);
}
// Tests a potential lifetime issue using the Cocoa MenuController, which has a
// weak reference to the model.
TEST_P(MenuRunnerCocoaTest, RunMenuAndDeleteThenSelectItem) {
RunMenu(
base::BindOnce(&MenuRunnerCocoaTest::ModelDeleteThenSelectItemCallback,
base::Unretained(this)));
EXPECT_EQ(0, menu_close_count_);
}
// Ensure a menu can be safely released immediately after a call to Cancel() in
// the same run loop iteration.
TEST_P(MenuRunnerCocoaTest, DestroyAfterCanceling) {
RunMenu(base::BindOnce(&MenuRunnerCocoaTest::MenuCancelAndDeleteCallback,
base::Unretained(this)));
if (IsAsync()) {
EXPECT_EQ(1, menu_close_count_);
} else {
// For a synchronous menu, the deletion happens before the cancel can be
// processed, so the close callback will not be invoked.
EXPECT_EQ(0, menu_close_count_);
}
}
TEST_P(MenuRunnerCocoaTest, RunMenuTwice) {
for (int i = 0; i < 2; ++i) {
RunMenu(base::BindOnce(&MenuRunnerCocoaTest::MenuCancelCallback,
base::Unretained(this)));
EXPECT_FALSE(runner_->IsRunning());
EXPECT_EQ(i + 1, menu_close_count_);
}
}
TEST_P(MenuRunnerCocoaTest, CancelWithoutRunning) {
runner_->Cancel();
EXPECT_FALSE(runner_->IsRunning());
EXPECT_EQ(base::TimeTicks(), runner_->GetClosingEventTime());
EXPECT_EQ(0, menu_close_count_);
}
TEST_P(MenuRunnerCocoaTest, DeleteWithoutRunning) {
runner_->Release();
runner_ = nullptr;
EXPECT_EQ(0, menu_close_count_);
}
// Tests anchoring of the menus used for toolkit-views Comboboxes.
TEST_P(MenuRunnerCocoaTest, ComboboxAnchoring) {
// Combobox at 20,10 in the Widget.
const gfx::Rect combobox_rect(20, 10, 80, 50);
// Menu anchor rects are always in screen coordinates. The window is frameless
// so offset by the bounds.
gfx::Rect anchor_rect = combobox_rect;
anchor_rect.Offset(kWindowOffset, kWindowOffset);
RunMenuAt(anchor_rect);
if (GetParam() != MenuType::NATIVE) {
// Combobox anchoring is only implemented for native menus.
EXPECT_NSEQ(NSZeroRect, last_anchor_frame_);
return;
}
// Nothing is checked, so the anchor view should have no height, to ensure the
// menu goes below the anchor rect. There should also be no x-offset since the
// there is no need to line-up text.
EXPECT_NSEQ(
NSMakeRect(combobox_rect.x(), kWindowHeight - combobox_rect.bottom(),
combobox_rect.width(), 0),
last_anchor_frame_);
menu_->set_checked_command(kTestCommandId);
RunMenuAt(anchor_rect);
// Native constant used by MenuRunnerImplCocoa.
const CGFloat kNativeCheckmarkWidth = 18;
// There is now a checked item, so the anchor should be vertically centered
// inside the combobox, and offset by the width of the checkmark column.
EXPECT_EQ(combobox_rect.x() - kNativeCheckmarkWidth,
last_anchor_frame_.origin.x);
EXPECT_EQ(kWindowHeight - combobox_rect.CenterPoint().y(),
NSMidY(last_anchor_frame_));
EXPECT_EQ(combobox_rect.width(), NSWidth(last_anchor_frame_));
EXPECT_NE(0, NSHeight(last_anchor_frame_));
// In RTL, Cocoa messes up the positioning unless the anchor rectangle is
// offset to the right of the view. The offset for the checkmark is also
// skipped, to give a better match to native behavior.
base::i18n::SetRTLForTesting(true);
RunMenuAt(anchor_rect);
EXPECT_EQ(combobox_rect.right(), last_anchor_frame_.origin.x);
base::i18n::SetRTLForTesting(false);
}
INSTANTIATE_TEST_SUITE_P(,
MenuRunnerCocoaTest,
::testing::Values(MenuType::NATIVE, MenuType::VIEWS),
&MenuTypeToString);
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_cocoa_unittest.mm | Objective-C++ | unknown | 15,994 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_
#include <stdint.h>
#include "ui/base/ui_base_types.h"
namespace gfx {
class Rect;
}
namespace views {
enum class MenuAnchorPosition;
class MenuButtonController;
class Widget;
// Used internally by MenuRunner to show the menu. Can be set in tests (see
// MenuRunnerTestApi) for mocking running of the menu.
class VIEWS_EXPORT MenuRunnerHandler {
public:
virtual ~MenuRunnerHandler() = default;
virtual void RunMenuAt(Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
ui::MenuSourceType source_type,
int32_t types) = 0;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_handler.h | C++ | unknown | 1,050 |
// Copyright 2014 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/menu_runner_impl.h"
#include <memory>
#include <utility>
#include "build/build_config.h"
#include "ui/accessibility/platform/ax_platform_node_base.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/menu_button_controller.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_runner_impl_adapter.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/events/win/system_event_state_lookup.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/events/event_constants.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_menu_utils.h"
#endif
namespace views {
namespace {
// This should be called after the menu has closed, to fire a focus event on
// the previously focused node in the parent widget, if one exists.
void FireFocusAfterMenuClose(base::WeakPtr<Widget> widget) {
if (widget) {
FocusManager* focus_manager = widget->GetFocusManager();
if (focus_manager && focus_manager->GetFocusedView()) {
focus_manager->GetFocusedView()
->GetViewAccessibility()
.FireFocusAfterMenuClose();
}
}
}
#if BUILDFLAG(IS_OZONE)
bool IsAltPressed() {
if (const auto* const platorm_menu_utils =
ui::OzonePlatform::GetInstance()->GetPlatformMenuUtils()) {
return (platorm_menu_utils->GetCurrentKeyModifiers() & ui::EF_ALT_DOWN) !=
0;
}
return false;
}
#endif // BUILDFLAG(IS_OZONE)
} // namespace
namespace internal {
#if !BUILDFLAG(IS_MAC)
MenuRunnerImplInterface* MenuRunnerImplInterface::Create(
ui::MenuModel* menu_model,
int32_t run_types,
base::RepeatingClosure on_menu_closed_callback) {
return new MenuRunnerImplAdapter(menu_model,
std::move(on_menu_closed_callback));
}
#endif
MenuRunnerImpl::MenuRunnerImpl(MenuItemView* menu)
: menu_(menu),
controller_(nullptr) {}
bool MenuRunnerImpl::IsRunning() const {
return running_;
}
void MenuRunnerImpl::Release() {
if (running_) {
if (delete_after_run_)
return; // We already canceled.
// The menu is running a nested run loop, we can't delete it now
// otherwise the stack would be in a really bad state (many frames would
// have deleted objects on them). Instead cancel the menu, when it returns
// Holder will delete itself.
delete_after_run_ = true;
// Swap in a different delegate. That way we know the original MenuDelegate
// won't be notified later on (when it's likely already been deleted).
if (!empty_delegate_.get())
empty_delegate_ = std::make_unique<MenuDelegate>();
menu_->set_delegate(empty_delegate_.get());
// Verify that the MenuController is still active. It may have been
// destroyed out of order.
if (controller_) {
// Release is invoked when MenuRunner is destroyed. Assume this is
// happening because the object referencing the menu has been destroyed
// and the menu button is no longer valid.
controller_->Cancel(MenuController::ExitType::kDestroyed);
return;
}
}
delete this;
}
void MenuRunnerImpl::RunMenuAt(Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t run_types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners) {
closing_event_time_ = base::TimeTicks();
if (running_) {
// Ignore requests to show the menu while it's already showing. MenuItemView
// doesn't handle this very well (meaning it crashes).
return;
}
MenuController* controller = MenuController::GetActiveInstance();
if (controller) {
controller->SetMenuRoundedCorners(corners);
if ((run_types & MenuRunner::IS_NESTED) != 0) {
if (controller->for_drop()) {
controller->Cancel(MenuController::ExitType::kAll);
controller = nullptr;
} else {
// Only nest the delegate when not cancelling drag-and-drop. When
// cancelling this will become the root delegate of the new
// MenuController
controller->AddNestedDelegate(this);
}
} else {
// There's some other menu open and we're not nested. Cancel the menu.
controller->Cancel(MenuController::ExitType::kAll);
if ((run_types & MenuRunner::FOR_DROP) == 0) {
// We can't open another menu, otherwise the message loop would become
// twice nested. This isn't necessarily a problem, but generally isn't
// expected.
return;
}
// Drop menus don't block the message loop, so it's ok to create a new
// MenuController.
controller = nullptr;
}
}
running_ = true;
for_drop_ = (run_types & MenuRunner::FOR_DROP) != 0;
bool has_mnemonics = (run_types & MenuRunner::HAS_MNEMONICS) != 0;
owns_controller_ = false;
if (!controller) {
// No menus are showing, show one.
controller = new MenuController(for_drop_, this);
owns_controller_ = true;
controller->SetMenuRoundedCorners(corners);
}
DCHECK((run_types & MenuRunner::COMBOBOX) == 0 ||
(run_types & MenuRunner::EDITABLE_COMBOBOX) == 0);
using ComboboxType = MenuController::ComboboxType;
if (run_types & MenuRunner::COMBOBOX)
controller->set_combobox_type(ComboboxType::kReadonly);
else if (run_types & MenuRunner::EDITABLE_COMBOBOX)
controller->set_combobox_type(ComboboxType::kEditable);
else
controller->set_combobox_type(ComboboxType::kNone);
controller->set_send_gesture_events_to_owner(
(run_types & MenuRunner::SEND_GESTURE_EVENTS_TO_OWNER) != 0);
controller->set_use_ash_system_ui_layout(
(run_types & MenuRunner::USE_ASH_SYS_UI_LAYOUT) != 0);
controller_ = controller->AsWeakPtr();
menu_->set_controller(controller_.get());
menu_->PrepareForRun(owns_controller_, has_mnemonics,
!for_drop_ && ShouldShowMnemonics(run_types));
controller->Run(parent, button_controller, menu_, bounds, anchor,
(run_types & MenuRunner::CONTEXT_MENU) != 0,
(run_types & MenuRunner::NESTED_DRAG) != 0,
native_view_for_gestures, parent_widget);
}
void MenuRunnerImpl::Cancel() {
if (running_)
controller_->Cancel(MenuController::ExitType::kAll);
}
base::TimeTicks MenuRunnerImpl::GetClosingEventTime() const {
return closing_event_time_;
}
void MenuRunnerImpl::OnMenuClosed(NotifyType type,
MenuItemView* menu,
int mouse_event_flags) {
base::WeakPtr<Widget> parent_widget;
if (controller_) {
closing_event_time_ = controller_->closing_event_time();
// Get a pointer to the parent widget before destroying the menu.
if (controller_->owner())
parent_widget = controller_->owner()->GetWeakPtr();
}
menu_->RemoveEmptyMenus();
menu_->set_controller(nullptr);
if (owns_controller_ && controller_) {
// We created the controller and need to delete it.
delete controller_.get();
owns_controller_ = false;
}
controller_ = nullptr;
// Make sure all the windows we created to show the menus have been
// destroyed.
menu_->DestroyAllMenuHosts();
if (delete_after_run_) {
FireFocusAfterMenuClose(parent_widget);
delete this;
return;
}
running_ = false;
if (menu_->GetDelegate()) {
// Executing the command may also delete this.
base::WeakPtr<MenuRunnerImpl> ref(weak_factory_.GetWeakPtr());
if (menu && !for_drop_) {
// Do not execute the menu that was dragged/dropped.
menu_->GetDelegate()->ExecuteCommand(menu->GetCommand(),
mouse_event_flags);
}
// Only notify the delegate if it did not delete this.
if (ref && type == NOTIFY_DELEGATE)
menu_->GetDelegate()->OnMenuClosed(menu);
}
FireFocusAfterMenuClose(parent_widget);
}
void MenuRunnerImpl::SiblingMenuCreated(MenuItemView* menu) {
if (menu != menu_ && sibling_menus_.count(menu) == 0)
sibling_menus_.insert(menu);
}
MenuRunnerImpl::~MenuRunnerImpl() {
delete menu_;
for (auto* sibling_menu : sibling_menus_)
delete sibling_menu;
}
bool MenuRunnerImpl::ShouldShowMnemonics(int32_t run_types) {
bool show_mnemonics = run_types & MenuRunner::SHOULD_SHOW_MNEMONICS;
// Show mnemonics if the button has focus or alt is pressed.
#if BUILDFLAG(IS_WIN)
show_mnemonics |= ui::win::IsAltPressed();
#elif BUILDFLAG(IS_OZONE)
show_mnemonics |= IsAltPressed();
#elif BUILDFLAG(IS_MAC)
show_mnemonics = false;
#endif
return show_mnemonics;
}
} // namespace internal
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl.cc | C++ | unknown | 9,245 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_
#include <stdint.h>
#include <memory>
#include <set>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "ui/views/controls/menu/menu_controller_delegate.h"
#include "ui/views/controls/menu/menu_runner_impl_interface.h"
#include "ui/views/views_export.h"
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace views {
class MenuController;
class MenuDelegate;
class MenuItemView;
namespace test {
class MenuRunnerDestructionTest;
} // namespace test
namespace internal {
// A menu runner implementation that uses views::MenuItemView to show a menu.
class VIEWS_EXPORT MenuRunnerImpl : public MenuRunnerImplInterface,
public MenuControllerDelegate {
public:
explicit MenuRunnerImpl(MenuItemView* menu);
MenuRunnerImpl(const MenuRunnerImpl&) = delete;
MenuRunnerImpl& operator=(const MenuRunnerImpl&) = delete;
bool IsRunning() const override;
void Release() override;
void RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t run_types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners = absl::nullopt) override;
void Cancel() override;
base::TimeTicks GetClosingEventTime() const override;
// MenuControllerDelegate:
void OnMenuClosed(NotifyType type,
MenuItemView* menu,
int mouse_event_flags) override;
void SiblingMenuCreated(MenuItemView* menu) override;
private:
friend class ::views::test::MenuRunnerDestructionTest;
~MenuRunnerImpl() override;
// Returns true if mnemonics should be shown in the menu.
bool ShouldShowMnemonics(int32_t run_types);
// The menu. We own this. We don't use scoped_ptr as the destructor is
// protected and we're a friend.
raw_ptr<MenuItemView, DanglingUntriaged> menu_;
// Any sibling menus. Does not include |menu_|. We own these too.
std::set<MenuItemView*> sibling_menus_;
// Created and set as the delegate of the MenuItemView if Release() is
// invoked. This is done to make sure the delegate isn't notified after
// Release() is invoked. We do this as we assume the delegate is no longer
// valid if MenuRunner has been deleted.
std::unique_ptr<MenuDelegate> empty_delegate_;
// Are we in run waiting for it to return?
bool running_ = false;
// Set if |running_| and Release() has been invoked.
bool delete_after_run_ = false;
// Are we running for a drop?
bool for_drop_ = false;
// The controller.
base::WeakPtr<MenuController> controller_;
// Do we own the controller?
bool owns_controller_ = false;
// The timestamp of the event which closed the menu - or 0.
base::TimeTicks closing_event_time_;
// Used to detect deletion of |this| when notifying delegate of success.
base::WeakPtrFactory<MenuRunnerImpl> weak_factory_{this};
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl.h | C++ | unknown | 3,375 |
// Copyright 2014 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/menu_runner_impl_adapter.h"
#include <utility>
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner_impl.h"
namespace views::internal {
MenuRunnerImplAdapter::MenuRunnerImplAdapter(
ui::MenuModel* menu_model,
base::RepeatingClosure on_menu_done_callback)
: menu_model_adapter_(
new MenuModelAdapter(menu_model, std::move(on_menu_done_callback))),
impl_(new MenuRunnerImpl(menu_model_adapter_->CreateMenu())) {}
bool MenuRunnerImplAdapter::IsRunning() const {
return impl_->IsRunning();
}
void MenuRunnerImplAdapter::Release() {
impl_->Release();
delete this;
}
void MenuRunnerImplAdapter::RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners) {
impl_->RunMenuAt(parent, button_controller, bounds, anchor, types,
native_view_for_gestures, parent_widget);
}
void MenuRunnerImplAdapter::Cancel() {
impl_->Cancel();
}
base::TimeTicks MenuRunnerImplAdapter::GetClosingEventTime() const {
return impl_->GetClosingEventTime();
}
MenuRunnerImplAdapter::~MenuRunnerImplAdapter() = default;
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl_adapter.cc | C++ | unknown | 1,546 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_
#include <stdint.h>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/views/controls/menu/menu_runner_impl_interface.h"
#include "ui/views/views_export.h"
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace views {
class MenuModelAdapter;
namespace internal {
class MenuRunnerImpl;
// Given a MenuModel, adapts MenuRunnerImpl which expects a MenuItemView.
class VIEWS_EXPORT MenuRunnerImplAdapter : public MenuRunnerImplInterface {
public:
MenuRunnerImplAdapter(ui::MenuModel* menu_model,
base::RepeatingClosure on_menu_closed_callback);
MenuRunnerImplAdapter(const MenuRunnerImplAdapter&) = delete;
MenuRunnerImplAdapter& operator=(const MenuRunnerImplAdapter&) = delete;
// MenuRunnerImplInterface:
bool IsRunning() const override;
void Release() override;
void RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners = absl::nullopt) override;
void Cancel() override;
base::TimeTicks GetClosingEventTime() const override;
private:
~MenuRunnerImplAdapter() override;
std::unique_ptr<MenuModelAdapter> menu_model_adapter_;
raw_ptr<MenuRunnerImpl, DanglingUntriaged> impl_;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl_adapter.h | C++ | unknown | 1,796 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_COCOA_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_COCOA_H_
#include <stdint.h>
#include "base/functional/callback.h"
#import "base/mac/scoped_nsobject.h"
#include "base/time/time.h"
#include "ui/views/controls/menu/menu_runner_impl_interface.h"
@class MenuControllerCocoa;
@class MenuControllerCocoaDelegateImpl;
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace views {
namespace test {
class MenuRunnerCocoaTest;
}
namespace internal {
// A menu runner implementation that uses NSMenu to show a context menu.
class VIEWS_EXPORT MenuRunnerImplCocoa : public MenuRunnerImplInterface {
public:
MenuRunnerImplCocoa(ui::MenuModel* menu,
base::RepeatingClosure on_menu_closed_callback);
MenuRunnerImplCocoa(const MenuRunnerImplCocoa&) = delete;
MenuRunnerImplCocoa& operator=(const MenuRunnerImplCocoa&) = delete;
bool IsRunning() const override;
void Release() override;
void RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t run_types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget,
absl::optional<gfx::RoundedCornersF> corners = absl::nullopt) override;
void Cancel() override;
base::TimeTicks GetClosingEventTime() const override;
private:
friend class views::test::MenuRunnerCocoaTest;
~MenuRunnerImplCocoa() override;
// The Cocoa menu controller that this instance is bridging.
base::scoped_nsobject<MenuControllerCocoa> menu_controller_;
// The delegate for the |menu_controller_|.
base::scoped_nsobject<MenuControllerCocoaDelegateImpl> menu_delegate_;
// Are we in run waiting for it to return?
bool running_ = false;
// Set if |running_| and Release() has been invoked.
bool delete_after_run_ = false;
// The timestamp of the event which closed the menu - or 0.
base::TimeTicks closing_event_time_;
// Invoked before RunMenuAt() returns, except upon a Release().
base::RepeatingClosure on_menu_closed_callback_;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_COCOA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl_cocoa.h | Objective-C | unknown | 2,391 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "ui/views/controls/menu/menu_runner_impl_cocoa.h"
#include <dispatch/dispatch.h>
#include "base/i18n/rtl.h"
#include "base/mac/mac_util.h"
#import "base/message_loop/message_pump_mac.h"
#include "base/numerics/safe_conversions.h"
#import "skia/ext/skia_utils_mac.h"
#import "ui/base/cocoa/menu_controller.h"
#include "ui/base/interaction/element_tracker_mac.h"
#include "ui/base/l10n/l10n_util_mac.h"
#include "ui/base/models/menu_model.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/mac/coordinate_conversion.h"
#include "ui/gfx/platform_font_mac.h"
#include "ui/native_theme/native_theme.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/menu/menu_config.h"
#import "ui/views/controls/menu/menu_controller_cocoa_delegate_impl.h"
#include "ui/views/controls/menu/menu_runner_impl_adapter.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/widget.h"
namespace {
constexpr CGFloat kNativeCheckmarkWidth = 18;
constexpr CGFloat kNativeMenuItemHeight = 18;
} // namespace
namespace views::internal {
namespace {
// Returns the first item in |menu_controller|'s menu that will be checked.
NSMenuItem* FirstCheckedItem(MenuControllerCocoa* menu_controller) {
for (NSMenuItem* item in [[menu_controller menu] itemArray]) {
if ([menu_controller model]->IsItemCheckedAt(
base::checked_cast<size_t>([item tag]))) {
return item;
}
}
return nil;
}
// Places a temporary, hidden NSView at |screen_bounds| within |window|. Used
// with -[NSMenu popUpMenuPositioningItem:atLocation:inView:] to position the
// menu for a combobox. The caller must remove the returned NSView from its
// superview when the menu is closed.
base::scoped_nsobject<NSView> CreateMenuAnchorView(
NSWindow* window,
const gfx::Rect& screen_bounds,
NSMenuItem* checked_item,
CGFloat actual_menu_width,
MenuAnchorPosition position) {
NSRect rect = gfx::ScreenRectToNSRect(screen_bounds);
rect = [window convertRectFromScreen:rect];
rect = [[window contentView] convertRect:rect fromView:nil];
// If there's no checked item (e.g. Combobox::STYLE_ACTION), NSMenu will
// anchor at the top left of the frame. Action buttons should anchor below.
if (!checked_item) {
rect.size.height = 0;
if (base::i18n::IsRTL())
rect.origin.x += rect.size.width;
} else {
// To ensure a consistent anchoring that's vertically centered in the
// bounds, fix the height to be the same as a menu item.
rect.origin.y = NSMidY(rect) - kNativeMenuItemHeight / 2;
rect.size.height = kNativeMenuItemHeight;
if (base::i18n::IsRTL()) {
// The Views menu controller flips the MenuAnchorPosition value from left
// to right in RTL. NSMenu does this automatically: the menu opens to the
// left of the anchor, but AppKit doesn't account for the anchor width.
// So the width needs to be added to anchor at the right of the view.
// Note the checkmark width is not also added - it doesn't quite line up
// the text. A Yosemite NSComboBox doesn't line up in RTL either: just
// adding the width is a good match for the native behavior.
rect.origin.x += rect.size.width;
} else {
rect.origin.x -= kNativeCheckmarkWidth;
}
}
// When the actual menu width is larger than the anchor, right alignment
// should be respected.
if (actual_menu_width > rect.size.width &&
position == views::MenuAnchorPosition::kTopRight &&
!base::i18n::IsRTL()) {
int width_diff = actual_menu_width - rect.size.width;
rect.origin.x -= width_diff;
}
// A plain NSView will anchor below rather than "over", so use an NSButton.
base::scoped_nsobject<NSView> anchor_view(
[[NSButton alloc] initWithFrame:rect]);
[anchor_view setHidden:YES];
[[window contentView] addSubview:anchor_view];
return anchor_view;
}
// Returns an appropriate event (with a location) suitable for showing a context
// menu. Uses [NSApp currentEvent] if it's a non-nil mouse click event,
// otherwise creates an autoreleased dummy event located at |anchor|.
NSEvent* EventForPositioningContextMenu(const gfx::Rect& anchor,
NSWindow* window) {
NSEvent* event = [NSApp currentEvent];
switch ([event type]) {
case NSEventTypeLeftMouseDown:
case NSEventTypeLeftMouseUp:
case NSEventTypeRightMouseDown:
case NSEventTypeRightMouseUp:
case NSEventTypeOtherMouseDown:
case NSEventTypeOtherMouseUp:
return event;
default:
break;
}
NSPoint location_in_window = [window
convertPointFromScreen:gfx::ScreenPointToNSPoint(anchor.CenterPoint())];
return [NSEvent mouseEventWithType:NSEventTypeRightMouseDown
location:location_in_window
modifierFlags:0
timestamp:0
windowNumber:[window windowNumber]
context:nil
eventNumber:0
clickCount:1
pressure:0];
}
} // namespace
// static
MenuRunnerImplInterface* MenuRunnerImplInterface::Create(
ui::MenuModel* menu_model,
int32_t run_types,
base::RepeatingClosure on_menu_closed_callback) {
if ((run_types & MenuRunner::CONTEXT_MENU) &&
!(run_types & (MenuRunner::IS_NESTED))) {
return new MenuRunnerImplCocoa(menu_model,
std::move(on_menu_closed_callback));
}
return new MenuRunnerImplAdapter(menu_model,
std::move(on_menu_closed_callback));
}
MenuRunnerImplCocoa::MenuRunnerImplCocoa(
ui::MenuModel* menu,
base::RepeatingClosure on_menu_closed_callback)
: on_menu_closed_callback_(std::move(on_menu_closed_callback)) {
menu_delegate_.reset([[MenuControllerCocoaDelegateImpl alloc] init]);
menu_controller_.reset([[MenuControllerCocoa alloc]
initWithModel:menu
delegate:menu_delegate_.get()
useWithPopUpButtonCell:NO]);
}
bool MenuRunnerImplCocoa::IsRunning() const {
return running_;
}
void MenuRunnerImplCocoa::Release() {
if (IsRunning()) {
if (delete_after_run_)
return; // We already canceled.
delete_after_run_ = true;
// Reset |menu_controller_| to ensure it clears itself as a delegate to
// prevent NSMenu attempting to access the weak pointer to the ui::MenuModel
// it holds (which is not owned by |this|). Toolkit-views menus use
// MenuRunnerImpl::empty_delegate_ to handle this case.
[menu_controller_ cancel];
menu_controller_.reset();
} else {
delete this;
}
}
void MenuRunnerImplCocoa::RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t run_types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget /*parent_widget*/,
absl::optional<gfx::RoundedCornersF> corners) {
DCHECK(!IsRunning());
DCHECK(parent);
closing_event_time_ = base::TimeTicks();
running_ = true;
[menu_delegate_ setAnchorRect:bounds];
// Ensure the UI can update while the menu is fading out.
base::ScopedPumpMessagesInPrivateModes pump_private;
NSWindow* window = parent->GetNativeWindow().GetNativeNSWindow();
NSView* view = parent->GetNativeView().GetNativeNSView();
[menu_controller_ maybeBuildWithColorProvider:parent->GetColorProvider()];
NSMenu* const menu = [menu_controller_ menu];
if (run_types & MenuRunner::CONTEXT_MENU) {
ui::ElementTrackerMac::GetInstance()->NotifyMenuWillShow(
menu, views::ElementTrackerViews::GetContextForWidget(parent));
[NSMenu popUpContextMenu:menu
withEvent:EventForPositioningContextMenu(bounds, window)
forView:view];
ui::ElementTrackerMac::GetInstance()->NotifyMenuDoneShowing(menu);
} else {
CHECK(run_types & MenuRunner::COMBOBOX);
NSMenuItem* const checked_item = FirstCheckedItem(menu_controller_);
base::scoped_nsobject<NSView> anchor_view(CreateMenuAnchorView(
window, bounds, checked_item, menu.size.width, anchor));
[menu setMinimumWidth:bounds.width() + kNativeCheckmarkWidth];
[menu popUpMenuPositioningItem:checked_item
atLocation:NSZeroPoint
inView:anchor_view];
[anchor_view removeFromSuperview];
}
closing_event_time_ = ui::EventTimeForNow();
running_ = false;
if (delete_after_run_) {
delete this;
return;
}
// Don't invoke the callback if Release() was called, since that usually means
// the owning instance is being destroyed.
if (!on_menu_closed_callback_.is_null())
on_menu_closed_callback_.Run();
}
void MenuRunnerImplCocoa::Cancel() {
[menu_controller_ cancel];
}
base::TimeTicks MenuRunnerImplCocoa::GetClosingEventTime() const {
return closing_event_time_;
}
MenuRunnerImplCocoa::~MenuRunnerImplCocoa() = default;
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl_cocoa.mm | Objective-C++ | unknown | 9,366 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_
#include <stdint.h>
#include "base/functional/callback_forward.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace views {
class MenuButtonController;
namespace internal {
// An abstract interface for menu runner implementations.
// Invoke Release() to destroy. Release() deletes immediately if the menu isn't
// showing. If the menu is showing Release() cancels the menu and when the
// nested RunMenuAt() call returns deletes itself and the menu.
class MenuRunnerImplInterface {
public:
// Creates a concrete instance for running |menu_model|.
// |run_types| is a bitmask of MenuRunner::RunTypes.
static MenuRunnerImplInterface* Create(
ui::MenuModel* menu_model,
int32_t run_types,
base::RepeatingClosure on_menu_closed_callback);
// Returns true if we're in a nested run loop running the menu.
virtual bool IsRunning() const = 0;
// See description above class for details.
virtual void Release() = 0;
// Runs the menu. See MenuRunner::RunMenuAt for more details.
virtual void RunMenuAt(
Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
int32_t run_types,
gfx::NativeView native_view_for_gestures,
gfx::AcceleratedWidget parent_widget =
gfx::kNullAcceleratedWidget,
absl::optional<gfx::RoundedCornersF> corners = absl::nullopt) = 0;
// Hides and cancels the menu.
virtual void Cancel() = 0;
// Returns the time from the event which closed the menu - or 0.
virtual base::TimeTicks GetClosingEventTime() const = 0;
protected:
// Call Release() to delete.
virtual ~MenuRunnerImplInterface() = default;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_impl_interface.h | C++ | unknown | 2,133 |
// Copyright 2015 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/menu_runner.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/simple_test_tick_clock.h"
#include "build/build_config.h"
#include "ui/base/ui_base_types.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_runner_impl.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/controls/menu/test_menu_item_view.h"
#include "ui/views/test/menu_test_utils.h"
#include "ui/views/test/test_views.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_utils.h"
#if BUILDFLAG(IS_MAC)
#include "ui/views/controls/menu/menu_cocoa_watcher_mac.h"
#endif
namespace views::test {
class MenuRunnerTest : public ViewsTestBase {
public:
MenuRunnerTest() = default;
MenuRunnerTest(const MenuRunnerTest&) = delete;
MenuRunnerTest& operator=(const MenuRunnerTest&) = delete;
~MenuRunnerTest() override = default;
// Initializes the delegates and views needed for a menu. It does not create
// the MenuRunner.
void InitMenuViews() {
menu_delegate_ = std::make_unique<TestMenuDelegate>();
menu_item_view_ = new views::TestMenuItemView(menu_delegate_.get());
menu_item_view_->AppendMenuItem(1, u"One");
menu_item_view_->AppendMenuItem(2, u"\x062f\x0648");
owner_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
owner_->Init(std::move(params));
owner_->Show();
}
// Initializes all delegates and views needed for a menu. A MenuRunner is also
// created with |run_types|, it takes ownership of |menu_item_view_|.
void InitMenuRunner(int32_t run_types) {
InitMenuViews();
menu_runner_ = std::make_unique<MenuRunner>(menu_item_view_, run_types);
}
views::TestMenuItemView* menu_item_view() { return menu_item_view_; }
TestMenuDelegate* menu_delegate() { return menu_delegate_.get(); }
MenuRunner* menu_runner() { return menu_runner_.get(); }
Widget* owner() { return owner_.get(); }
#if BUILDFLAG(IS_MAC)
void SetUp() override {
ViewsTestBase::SetUp();
// Ignore app activation notifications during tests (they make the tests
// flaky).
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::IgnoreWorkspaceNotifications);
}
#endif
// ViewsTestBase:
void TearDown() override {
if (owner_)
owner_->CloseNow();
#if BUILDFLAG(IS_MAC)
MenuCocoaWatcherMac::SetNotificationFilterForTesting(
MacNotificationFilter::DontIgnoreNotifications);
#endif
ViewsTestBase::TearDown();
}
bool IsItemSelected(int command_id) {
MenuItemView* item = menu_item_view()->GetMenuItemByID(command_id);
return item ? item->IsSelected() : false;
}
// Menus that use prefix selection don't support mnemonics - the input is
// always part of the prefix.
bool MenuSupportsMnemonics() {
return !MenuConfig::instance().all_menus_use_prefix_selection;
}
private:
// Owned by menu_runner_.
raw_ptr<views::TestMenuItemView> menu_item_view_ = nullptr;
std::unique_ptr<TestMenuDelegate> menu_delegate_;
std::unique_ptr<MenuRunner> menu_runner_;
std::unique_ptr<Widget> owner_;
};
// Tests that MenuRunner is still running after the call to RunMenuAt when
// initialized with , and that MenuDelegate is notified upon
// the closing of the menu.
TEST_F(MenuRunnerTest, AsynchronousRun) {
InitMenuRunner(0);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
runner->Cancel();
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, delegate->on_menu_closed_menu());
}
// Tests that when a menu is run asynchronously, key events are handled properly
// by testing that Escape key closes the menu.
TEST_F(MenuRunnerTest, AsynchronousKeyEventHandling) {
InitMenuRunner(0);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
ui::test::EventGenerator generator(GetContext(), owner()->GetNativeWindow());
generator.PressKey(ui::VKEY_ESCAPE, 0);
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_EQ(nullptr, delegate->on_menu_closed_menu());
}
// Tests that a key press on a US keyboard layout activates the correct menu
// item.
// This test is flaky on ozone (https://crbug.com/1197217).
#if BUILDFLAG(IS_OZONE)
#define MAYBE_LatinMnemonic DISABLED_LatinMnemonic
#else
#define MAYBE_LatinMnemonic LatinMnemonic
#endif
TEST_F(MenuRunnerTest, MAYBE_LatinMnemonic) {
if (!MenuSupportsMnemonics())
return;
views::test::DisableMenuClosureAnimations();
InitMenuRunner(0);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
ui::test::EventGenerator generator(GetContext(), owner()->GetNativeWindow());
generator.PressKey(ui::VKEY_O, 0);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(1, delegate->execute_command_id());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_NE(nullptr, delegate->on_menu_closed_menu());
}
#if !BUILDFLAG(IS_WIN)
// Tests that a key press on a non-US keyboard layout activates the correct menu
// item. Disabled on Windows because a WM_CHAR event does not activate an item.
TEST_F(MenuRunnerTest, NonLatinMnemonic) {
if (!MenuSupportsMnemonics())
return;
views::test::DisableMenuClosureAnimations();
InitMenuRunner(0);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
ui::test::EventGenerator generator(GetContext(), owner()->GetNativeWindow());
ui::KeyEvent key_press(0x062f, ui::VKEY_N, ui::DomCode::NONE, 0);
generator.Dispatch(&key_press);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(2, delegate->execute_command_id());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_NE(nullptr, delegate->on_menu_closed_menu());
}
#endif // !BUILDFLAG(IS_WIN)
TEST_F(MenuRunnerTest, MenuItemViewShowsMnemonics) {
if (!MenuSupportsMnemonics())
return;
InitMenuRunner(MenuRunner::HAS_MNEMONICS | MenuRunner::SHOULD_SHOW_MNEMONICS);
menu_runner()->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE,
nullptr);
EXPECT_TRUE(menu_item_view()->show_mnemonics());
}
TEST_F(MenuRunnerTest, MenuItemViewDoesNotShowMnemonics) {
if (!MenuSupportsMnemonics())
return;
InitMenuRunner(MenuRunner::HAS_MNEMONICS);
menu_runner()->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE,
nullptr);
EXPECT_FALSE(menu_item_view()->show_mnemonics());
}
TEST_F(MenuRunnerTest, PrefixSelect) {
if (!MenuConfig::instance().all_menus_use_prefix_selection)
return;
base::SimpleTestTickClock clock;
// This test has a menu with three items:
// { 1, "One" }
// { 2, "\x062f\x0648" }
// { 3, "One Two" }
// It progressively prefix searches for "One " (note the space) and ensures
// that the right item is found.
views::test::DisableMenuClosureAnimations();
InitMenuRunner(0);
menu_item_view()->AppendMenuItem(3, u"One Two");
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
menu_item_view()
->GetSubmenu()
->GetPrefixSelector()
->set_tick_clock_for_testing(&clock);
ui::test::EventGenerator generator(GetContext(), owner()->GetNativeWindow());
generator.PressKey(ui::VKEY_O, 0);
EXPECT_TRUE(IsItemSelected(1));
generator.PressKey(ui::VKEY_N, 0);
generator.PressKey(ui::VKEY_E, 0);
EXPECT_TRUE(IsItemSelected(1));
generator.PressKey(ui::VKEY_SPACE, 0);
EXPECT_TRUE(IsItemSelected(3));
// Wait out the PrefixSelector's timeout.
clock.Advance(base::Seconds(10));
// Send Space to activate the selected menu item.
generator.PressKey(ui::VKEY_SPACE, 0);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(3, delegate->execute_command_id());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_NE(nullptr, delegate->on_menu_closed_menu());
}
// This test is Mac-specific: Mac is the only platform where VKEY_SPACE
// activates menu items.
#if BUILDFLAG(IS_MAC)
TEST_F(MenuRunnerTest, SpaceActivatesItem) {
if (!MenuConfig::instance().all_menus_use_prefix_selection)
return;
views::test::DisableMenuClosureAnimations();
InitMenuRunner(0);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
ui::test::EventGenerator generator(GetContext(), owner()->GetNativeWindow());
generator.PressKey(ui::VKEY_DOWN, 0);
EXPECT_TRUE(IsItemSelected(1));
generator.PressKey(ui::VKEY_SPACE, 0);
views::test::WaitForMenuClosureAnimation();
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(1, delegate->execute_command_id());
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_NE(nullptr, delegate->on_menu_closed_menu());
}
#endif // BUILDFLAG(IS_MAC)
// Tests that attempting to nest a menu within a drag-and-drop menu does not
// cause a crash. Instead the drag and drop action should be canceled, and the
// new menu should be openned.
TEST_F(MenuRunnerTest, NestingDuringDrag) {
InitMenuRunner(MenuRunner::FOR_DROP);
MenuRunner* runner = menu_runner();
runner->RunMenuAt(owner(), nullptr, gfx::Rect(), MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE, nullptr);
EXPECT_TRUE(runner->IsRunning());
std::unique_ptr<TestMenuDelegate> nested_delegate(new TestMenuDelegate);
MenuItemView* nested_menu = new MenuItemView(nested_delegate.get());
std::unique_ptr<MenuRunner> nested_runner(
new MenuRunner(nested_menu, MenuRunner::IS_NESTED));
nested_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE,
nullptr);
EXPECT_TRUE(nested_runner->IsRunning());
EXPECT_FALSE(runner->IsRunning());
TestMenuDelegate* delegate = menu_delegate();
EXPECT_EQ(1, delegate->on_menu_closed_called());
EXPECT_NE(nullptr, delegate->on_menu_closed_menu());
}
namespace {
// An EventHandler that launches a menu in response to a mouse press.
class MenuLauncherEventHandler : public ui::EventHandler {
public:
MenuLauncherEventHandler(MenuRunner* runner, Widget* owner)
: runner_(runner), owner_(owner) {}
MenuLauncherEventHandler(const MenuLauncherEventHandler&) = delete;
MenuLauncherEventHandler& operator=(const MenuLauncherEventHandler&) = delete;
~MenuLauncherEventHandler() override = default;
private:
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override {
if (event->type() == ui::ET_MOUSE_PRESSED) {
runner_->RunMenuAt(owner_, nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE,
nullptr);
event->SetHandled();
}
}
raw_ptr<MenuRunner> runner_;
raw_ptr<Widget> owner_;
};
} // namespace
// Test harness that includes a parent Widget and View invoking the menu.
class MenuRunnerWidgetTest : public MenuRunnerTest {
public:
MenuRunnerWidgetTest() = default;
MenuRunnerWidgetTest(const MenuRunnerWidgetTest&) = delete;
MenuRunnerWidgetTest& operator=(const MenuRunnerWidgetTest&) = delete;
Widget* widget() { return widget_; }
EventCountView* event_count_view() { return event_count_view_; }
std::unique_ptr<ui::test::EventGenerator> EventGeneratorForWidget(
Widget* widget) {
return std::make_unique<ui::test::EventGenerator>(
GetContext(), widget->GetNativeWindow());
}
void AddMenuLauncherEventHandler(Widget* widget) {
consumer_ =
std::make_unique<MenuLauncherEventHandler>(menu_runner(), widget);
event_count_view_->AddPostTargetHandler(consumer_.get());
}
// ViewsTestBase:
void SetUp() override {
MenuRunnerTest::SetUp();
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget_->Init(std::move(params));
widget_->Show();
widget_->SetSize(gfx::Size(300, 300));
event_count_view_ = new EventCountView();
event_count_view_->SetBounds(0, 0, 300, 300);
widget_->GetRootView()->AddChildView(event_count_view_.get());
InitMenuRunner(0);
}
void TearDown() override {
widget_->CloseNow();
MenuRunnerTest::TearDown();
}
private:
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<EventCountView> event_count_view_ = nullptr;
std::unique_ptr<MenuLauncherEventHandler> consumer_;
};
// Tests that when a mouse press launches a menu, that the target widget does
// not take explicit capture, nor closes the menu.
TEST_F(MenuRunnerWidgetTest, WidgetDoesntTakeCapture) {
AddMenuLauncherEventHandler(owner());
EXPECT_EQ(gfx::kNullNativeView,
internal::NativeWidgetPrivate::GetGlobalCapture(
widget()->GetNativeView()));
auto generator(EventGeneratorForWidget(widget()));
generator->MoveMouseTo(widget()->GetClientAreaBoundsInScreen().CenterPoint());
// Implicit capture should not be held by |widget|.
generator->PressLeftButton();
EXPECT_EQ(1, event_count_view()->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_NE(widget()->GetNativeView(),
internal::NativeWidgetPrivate::GetGlobalCapture(
widget()->GetNativeView()));
// The menu should still be open.
TestMenuDelegate* delegate = menu_delegate();
EXPECT_TRUE(menu_runner()->IsRunning());
EXPECT_EQ(0, delegate->on_menu_closed_called());
}
// Tests that after showing a menu on mouse press, that the subsequent mouse
// will be delivered to the correct view, and not to the one that showed the
// menu.
//
// The original bug is reproducible only when showing the menu on mouse press,
// as RootView::OnMouseReleased() doesn't have the same behavior.
TEST_F(MenuRunnerWidgetTest, ClearsMouseHandlerOnRun) {
AddMenuLauncherEventHandler(widget());
// Create a second view that's supposed to get the second mouse press.
EventCountView* second_event_count_view = new EventCountView();
widget()->GetRootView()->AddChildView(second_event_count_view);
widget()->SetBounds(gfx::Rect(0, 0, 200, 100));
event_count_view()->SetBounds(0, 0, 100, 100);
second_event_count_view->SetBounds(100, 0, 100, 100);
// Click on the first view to show the menu.
auto generator(EventGeneratorForWidget(widget()));
generator->MoveMouseTo(event_count_view()->GetBoundsInScreen().CenterPoint());
generator->PressLeftButton();
// Pretend we dismissed the menu using normal means, as it doesn't matter.
EXPECT_TRUE(menu_runner()->IsRunning());
menu_runner()->Cancel();
// EventGenerator won't allow us to re-send the left button press without
// releasing it first. We can't send the release event using the same
// generator as it would be handled by the RootView in the main Widget.
// In actual application the RootView doesn't see the release event.
generator.reset();
generator = EventGeneratorForWidget(widget());
generator->MoveMouseTo(
second_event_count_view->GetBoundsInScreen().CenterPoint());
generator->PressLeftButton();
EXPECT_EQ(1, second_event_count_view->GetEventCount(ui::ET_MOUSE_PRESSED));
}
class MenuRunnerImplTest : public MenuRunnerTest {
public:
MenuRunnerImplTest() = default;
MenuRunnerImplTest(const MenuRunnerImplTest&) = delete;
MenuRunnerImplTest& operator=(const MenuRunnerImplTest&) = delete;
~MenuRunnerImplTest() override = default;
void SetUp() override;
};
void MenuRunnerImplTest::SetUp() {
MenuRunnerTest::SetUp();
InitMenuViews();
}
// Tests that when nested menu runners are destroyed out of order, that
// MenuController is not accessed after it has been destroyed. This should not
// crash on ASAN bots.
TEST_F(MenuRunnerImplTest, NestedMenuRunnersDestroyedOutOfOrder) {
internal::MenuRunnerImpl* menu_runner =
new internal::MenuRunnerImpl(menu_item_view());
menu_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, 0, nullptr);
std::unique_ptr<TestMenuDelegate> menu_delegate2(new TestMenuDelegate);
MenuItemView* menu_item_view2 = new MenuItemView(menu_delegate2.get());
menu_item_view2->AppendMenuItem(1, u"One");
internal::MenuRunnerImpl* menu_runner2 =
new internal::MenuRunnerImpl(menu_item_view2);
menu_runner2->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, MenuRunner::IS_NESTED,
nullptr);
// Hide the controller so we can test out of order destruction.
MenuControllerTestApi menu_controller;
menu_controller.SetShowing(false);
// This destroyed MenuController
menu_runner->OnMenuClosed(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
nullptr, 0);
// This should not access the destroyed MenuController
menu_runner2->Release();
menu_runner->Release();
}
// Tests that when there are two separate MenuControllers, and the active one is
// deleted first, that shutting down the MenuRunner of the original
// MenuController properly closes its controller. This should not crash on ASAN
// bots.
TEST_F(MenuRunnerImplTest, MenuRunnerDestroyedWithNoActiveController) {
internal::MenuRunnerImpl* menu_runner =
new internal::MenuRunnerImpl(menu_item_view());
menu_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, 0, nullptr);
// Hide the menu, and clear its item selection state.
MenuControllerTestApi menu_controller;
menu_controller.SetShowing(false);
menu_controller.ClearState();
std::unique_ptr<TestMenuDelegate> menu_delegate2(new TestMenuDelegate);
MenuItemView* menu_item_view2 = new MenuItemView(menu_delegate2.get());
menu_item_view2->AppendMenuItem(1, u"One");
internal::MenuRunnerImpl* menu_runner2 =
new internal::MenuRunnerImpl(menu_item_view2);
menu_runner2->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, MenuRunner::FOR_DROP,
nullptr);
EXPECT_NE(menu_controller.controller(), MenuController::GetActiveInstance());
menu_controller.SetShowing(true);
// Close the runner with the active menu first.
menu_runner2->Release();
// Even though there is no active menu, this should still cleanup the
// controller that it created.
menu_runner->Release();
// This is not expected to run, however this is from the origin ASAN stack
// traces. So regressions will be caught with the same stack trace.
if (menu_controller.controller())
menu_controller.controller()->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(nullptr, menu_controller.controller());
}
// Test class which overrides the ViewsDelegate. Allowing to simulate shutdown
// during its release.
class MenuRunnerDestructionTest : public MenuRunnerTest {
public:
MenuRunnerDestructionTest() = default;
MenuRunnerDestructionTest(const MenuRunnerDestructionTest&) = delete;
MenuRunnerDestructionTest& operator=(const MenuRunnerDestructionTest&) =
delete;
~MenuRunnerDestructionTest() override = default;
ReleaseRefTestViewsDelegate* test_views_delegate() {
return test_views_delegate_;
}
base::WeakPtr<internal::MenuRunnerImpl> MenuRunnerAsWeakPtr(
internal::MenuRunnerImpl* menu_runner);
// ViewsTestBase:
void SetUp() override;
private:
// Not owned
raw_ptr<ReleaseRefTestViewsDelegate> test_views_delegate_ = nullptr;
};
base::WeakPtr<internal::MenuRunnerImpl>
MenuRunnerDestructionTest::MenuRunnerAsWeakPtr(
internal::MenuRunnerImpl* menu_runner) {
return menu_runner->weak_factory_.GetWeakPtr();
}
void MenuRunnerDestructionTest::SetUp() {
auto test_views_delegate = std::make_unique<ReleaseRefTestViewsDelegate>();
test_views_delegate_ = test_views_delegate.get();
set_views_delegate(std::move(test_views_delegate));
MenuRunnerTest::SetUp();
InitMenuViews();
}
// Tests that when ViewsDelegate is released that a nested Cancel of the
// MenuRunner does not occur.
TEST_F(MenuRunnerDestructionTest, MenuRunnerDestroyedDuringReleaseRef) {
internal::MenuRunnerImpl* menu_runner =
new internal::MenuRunnerImpl(menu_item_view());
menu_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, 0, nullptr);
base::RunLoop run_loop;
test_views_delegate()->set_release_ref_callback(
base::BindLambdaForTesting([&]() {
run_loop.Quit();
menu_runner->Release();
}));
base::WeakPtr<internal::MenuRunnerImpl> ref(MenuRunnerAsWeakPtr(menu_runner));
MenuControllerTestApi menu_controller;
// This will release the ref on ViewsDelegate. The test version will release
// |menu_runner| simulating device shutdown.
menu_controller.controller()->Cancel(MenuController::ExitType::kAll);
// Both the |menu_runner| and |menu_controller| should have been deleted.
EXPECT_EQ(nullptr, menu_controller.controller());
run_loop.Run();
EXPECT_EQ(nullptr, ref);
}
TEST_F(MenuRunnerImplTest, FocusOnMenuClose) {
internal::MenuRunnerImpl* menu_runner =
new internal::MenuRunnerImpl(menu_item_view());
// Create test button that has focus.
auto button_managed = std::make_unique<LabelButton>();
button_managed->SetID(1);
button_managed->SetSize(gfx::Size(20, 20));
LabelButton* button =
owner()->GetRootView()->AddChildView(std::move(button_managed));
button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button->GetWidget()->widget_delegate()->SetCanActivate(true);
button->GetWidget()->Activate();
button->RequestFocus();
// Open the menu.
menu_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, 0, nullptr);
MenuControllerTestApi menu_controller;
menu_controller.SetShowing(false);
// Test that closing the menu sends the kFocusAfterMenuClose event.
bool focus_after_menu_close_sent = false;
ViewAccessibility::AccessibilityEventsCallback accessibility_events_callback =
base::BindRepeating(
[](bool* focus_after_menu_close_sent,
const ui::AXPlatformNodeDelegate* delegate,
const ax::mojom::Event event_type) {
if (event_type == ax::mojom::Event::kFocusAfterMenuClose)
*focus_after_menu_close_sent = true;
},
&focus_after_menu_close_sent);
button->GetViewAccessibility().set_accessibility_events_callback(
std::move(accessibility_events_callback));
menu_runner->OnMenuClosed(internal::MenuControllerDelegate::NOTIFY_DELEGATE,
nullptr, 0);
EXPECT_TRUE(focus_after_menu_close_sent);
// Set the callback to a no-op to avoid accessing
// "focus_after_menu_close_sent" after this test has completed.
button->GetViewAccessibility().set_accessibility_events_callback(
base::DoNothing());
menu_runner->Release();
}
TEST_F(MenuRunnerImplTest, FocusOnMenuCloseDeleteAfterRun) {
// Create test button that has focus.
LabelButton* button = new LabelButton(
Button::PressedCallback(), std::u16string(), style::CONTEXT_BUTTON);
button->SetID(1);
button->SetSize(gfx::Size(20, 20));
owner()->GetRootView()->AddChildView(button);
button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button->GetWidget()->widget_delegate()->SetCanActivate(true);
button->GetWidget()->Activate();
button->RequestFocus();
internal::MenuRunnerImpl* menu_runner =
new internal::MenuRunnerImpl(menu_item_view());
menu_runner->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, 0, nullptr);
// Hide the menu, and clear its item selection state.
MenuControllerTestApi menu_controller;
menu_controller.SetShowing(false);
menu_controller.ClearState();
std::unique_ptr<TestMenuDelegate> menu_delegate2(new TestMenuDelegate);
MenuItemView* menu_item_view2 = new MenuItemView(menu_delegate2.get());
menu_item_view2->AppendMenuItem(1, u"One");
internal::MenuRunnerImpl* menu_runner2 =
new internal::MenuRunnerImpl(menu_item_view2);
menu_runner2->RunMenuAt(owner(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft, MenuRunner::FOR_DROP,
nullptr);
EXPECT_NE(menu_controller.controller(), MenuController::GetActiveInstance());
menu_controller.SetShowing(true);
// Test that closing the menu sends the kFocusAfterMenuClose event.
bool focus_after_menu_close_sent = false;
ViewAccessibility::AccessibilityEventsCallback accessibility_events_callback =
base::BindRepeating(
[](bool* focus_after_menu_close_sent,
const ui::AXPlatformNodeDelegate* delegate,
const ax::mojom::Event event_type) {
if (event_type == ax::mojom::Event::kFocusAfterMenuClose)
*focus_after_menu_close_sent = true;
},
&focus_after_menu_close_sent);
button->GetViewAccessibility().set_accessibility_events_callback(
std::move(accessibility_events_callback));
menu_runner2->Release();
EXPECT_TRUE(focus_after_menu_close_sent);
focus_after_menu_close_sent = false;
menu_runner->Release();
EXPECT_TRUE(focus_after_menu_close_sent);
// Set the callback to a no-op to avoid accessing
// "focus_after_menu_close_sent" after this test has completed.
button->GetViewAccessibility().set_accessibility_events_callback(
base::DoNothing());
// This is not expected to run, however this is from the origin ASAN stack
// traces. So regressions will be caught with the same stack trace.
if (menu_controller.controller())
menu_controller.controller()->Cancel(MenuController::ExitType::kAll);
EXPECT_EQ(nullptr, menu_controller.controller());
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_runner_unittest.cc | C++ | unknown | 27,852 |
// 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/menu_scroll_view_container.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "cc/paint/paint_flags.h"
#include "chromeos/constants/chromeos_features.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/highlight_border.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/round_rect_painter.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
namespace views {
namespace {
static constexpr int kBorderPaddingDueToRoundedCorners = 1;
static constexpr float kBackgroundBlurSigma = 30.f;
static constexpr float kBackgroundBlurQuality = 0.33f;
// MenuScrollButton ------------------------------------------------------------
// MenuScrollButton is used for the scroll buttons when not all menu items fit
// on screen. MenuScrollButton forwards appropriate events to the
// MenuController.
class MenuScrollButton : public View {
public:
METADATA_HEADER(MenuScrollButton);
MenuScrollButton(SubmenuView* host, bool is_up)
: host_(host),
is_up_(is_up),
// Make our height the same as that of other MenuItemViews.
pref_height_(MenuItemView::pref_menu_height()) {}
MenuScrollButton(const MenuScrollButton&) = delete;
MenuScrollButton& operator=(const MenuScrollButton&) = delete;
gfx::Size CalculatePreferredSize() const override {
return gfx::Size(MenuConfig::instance().scroll_arrow_height * 2 - 1,
pref_height_);
}
void OnThemeChanged() override {
View::OnThemeChanged();
arrow_color_ = GetColorProvider()->GetColor(ui::kColorMenuItemForeground);
}
bool CanDrop(const OSExchangeData& data) override {
DCHECK(host_->GetMenuItem()->GetMenuController());
return true; // Always return true so that drop events are targeted to us.
}
void OnDragEntered(const ui::DropTargetEvent& event) override {
DCHECK(host_->GetMenuItem()->GetMenuController());
host_->GetMenuItem()->GetMenuController()->OnDragEnteredScrollButton(
host_, is_up_);
}
int OnDragUpdated(const ui::DropTargetEvent& event) override {
return ui::DragDropTypes::DRAG_NONE;
}
void OnDragExited() override {
DCHECK(host_->GetMenuItem()->GetMenuController());
host_->GetMenuItem()->GetMenuController()->OnDragExitedScrollButton(host_);
}
DropCallback GetDropCallback(const ui::DropTargetEvent& event) override {
return base::DoNothing();
}
void OnPaint(gfx::Canvas* canvas) override {
const MenuConfig& config = MenuConfig::instance();
// The background.
gfx::Rect item_bounds(0, 0, width(), height());
ui::NativeTheme::ExtraParams extra;
GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(),
ui::NativeTheme::kMenuItemBackground,
ui::NativeTheme::kNormal, item_bounds, extra);
// Then the arrow.
int x = width() / 2;
int y = (height() - config.scroll_arrow_height) / 2;
int x_left = x - config.scroll_arrow_height;
int x_right = x + config.scroll_arrow_height;
int y_bottom;
if (!is_up_) {
y_bottom = y;
y = y_bottom + config.scroll_arrow_height;
} else {
y_bottom = y + config.scroll_arrow_height;
}
SkPath path;
path.setFillType(SkPathFillType::kWinding);
path.moveTo(SkIntToScalar(x), SkIntToScalar(y));
path.lineTo(SkIntToScalar(x_left), SkIntToScalar(y_bottom));
path.lineTo(SkIntToScalar(x_right), SkIntToScalar(y_bottom));
path.lineTo(SkIntToScalar(x), SkIntToScalar(y));
cc::PaintFlags flags;
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setAntiAlias(true);
flags.setColor(arrow_color_);
canvas->DrawPath(path, flags);
}
private:
// SubmenuView we were created for.
raw_ptr<SubmenuView> host_;
// Direction of the button.
bool is_up_;
// Preferred height.
int pref_height_;
// Color for the arrow to scroll.
SkColor arrow_color_;
};
BEGIN_METADATA(MenuScrollButton, View)
END_METADATA
} // namespace
// MenuScrollView --------------------------------------------------------------
// MenuScrollView is a viewport for the SubmenuView. It's reason to exist is so
// that ScrollRectToVisible works.
//
// NOTE: It is possible to use ScrollView directly (after making it deal with
// null scrollbars), but clicking on a child of ScrollView forces the window to
// become active, which we don't want. As we really only need a fraction of
// what ScrollView does, so we use a one off variant.
class MenuScrollViewContainer::MenuScrollView : public View {
public:
METADATA_HEADER(MenuScrollView);
MenuScrollView(View* child, MenuScrollViewContainer* owner) : owner_(owner) {
AddChildView(child);
}
MenuScrollView(const MenuScrollView&) = delete;
MenuScrollView& operator=(const MenuScrollView&) = delete;
void ScrollRectToVisible(const gfx::Rect& rect) override {
// NOTE: this assumes we only want to scroll in the y direction.
// If the rect is already visible, do not scroll.
if (GetLocalBounds().Contains(rect))
return;
// Scroll just enough so that the rect is visible.
int dy = 0;
if (rect.bottom() > GetLocalBounds().bottom())
dy = rect.bottom() - GetLocalBounds().bottom();
else
dy = rect.y();
// Convert rect.y() to view's coordinates and make sure we don't show past
// the bottom of the view.
View* child = GetContents();
int old_y = child->y();
int y = -std::max(
0, std::min(child->GetPreferredSize().height() - this->height(),
dy - child->y()));
child->SetY(y);
const int min_y = 0;
const int max_y = -(child->GetPreferredSize().height() - this->height());
if (old_y == min_y && old_y != y)
owner_->DidScrollAwayFromTop();
if (old_y == max_y && old_y != y)
owner_->DidScrollAwayFromBottom();
if (y == min_y)
owner_->DidScrollToTop();
if (y == max_y)
owner_->DidScrollToBottom();
}
// Returns the contents, which is the SubmenuView.
View* GetContents() { return children().front(); }
const View* GetContents() const { return children().front(); }
private:
raw_ptr<MenuScrollViewContainer> owner_;
};
BEGIN_METADATA(MenuScrollViewContainer, MenuScrollView, View)
END_METADATA
// MenuScrollViewContainer ----------------------------------------------------
MenuScrollViewContainer::MenuScrollViewContainer(SubmenuView* content_view)
: content_view_(content_view),
use_ash_system_ui_layout_(content_view->GetMenuItem()
->GetMenuController()
->use_ash_system_ui_layout()) {
background_view_ = AddChildView(std::make_unique<View>());
if (use_ash_system_ui_layout_) {
// Enable background blur for ChromeOS system context menu.
background_view_->SetPaintToLayer();
auto* background_layer = background_view_->layer();
background_layer->SetFillsBoundsOpaquely(false);
background_layer->SetBackgroundBlur(kBackgroundBlurSigma);
background_layer->SetBackdropFilterQuality(kBackgroundBlurQuality);
}
auto* layout =
background_view_->SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kVertical);
scroll_up_button_ = background_view_->AddChildView(
std::make_unique<MenuScrollButton>(content_view, true));
scroll_view_ = background_view_->AddChildView(
std::make_unique<MenuScrollView>(content_view, this));
scroll_view_->SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToMinimum,
views::MaximumFlexSizeRule::kUnbounded));
scroll_down_button_ = background_view_->AddChildView(
std::make_unique<MenuScrollButton>(content_view, false));
SkColor override_color;
MenuDelegate* delegate = content_view_->GetMenuItem()->GetDelegate();
if (delegate && delegate->GetBackgroundColor(-1, false, &override_color))
SetBackground(views::CreateSolidBackground(override_color));
arrow_ = BubbleBorderTypeFromAnchor(
content_view_->GetMenuItem()->GetMenuController()->GetAnchorPosition());
// The correct insets must be set before returning, since the menu creation
// code needs to know the final size of the menu. Calling CreateBorder() is
// the easiest way to do that.
CreateBorder();
}
bool MenuScrollViewContainer::HasBubbleBorder() const {
return arrow_ != BubbleBorder::NONE;
}
MenuItemView* MenuScrollViewContainer::GetFootnote() const {
MenuItemView* const footnote = content_view_->GetLastItem();
return (footnote && footnote->GetType() == MenuItemView::Type::kHighlighted)
? footnote
: nullptr;
}
gfx::RoundedCornersF MenuScrollViewContainer::GetRoundedCorners() const {
// The controller could be null during context menu being closed.
auto* menu_controller = content_view_->GetMenuItem()->GetMenuController();
if (!menu_controller)
return gfx::RoundedCornersF(corner_radius_);
absl::optional<gfx::RoundedCornersF> rounded_corners =
menu_controller->rounded_corners();
if (rounded_corners.has_value())
return rounded_corners.value();
return gfx::RoundedCornersF(corner_radius_);
}
gfx::Size MenuScrollViewContainer::CalculatePreferredSize() const {
gfx::Size prefsize = scroll_view_->GetContents()->GetPreferredSize();
gfx::Insets insets = GetInsets();
prefsize.Enlarge(insets.width(), insets.height());
const MenuConfig& config = MenuConfig::instance();
// Leave space for the menu border, below the footnote.
if (GetFootnote() && config.use_outer_border && !HasBubbleBorder() &&
!config.use_bubble_border) {
prefsize.Enlarge(0, 1);
}
return prefsize;
}
void MenuScrollViewContainer::OnThemeChanged() {
View::OnThemeChanged();
CreateBorder();
}
void MenuScrollViewContainer::OnPaintBackground(gfx::Canvas* canvas) {
if (background()) {
View::OnPaintBackground(canvas);
return;
}
// ChromeOS system UI menu uses 'background_view_' to paint background.
if (use_ash_system_ui_layout_ && background_view_->background())
return;
gfx::Rect bounds(0, 0, width(), height());
ui::NativeTheme::ExtraParams extra;
const MenuConfig& menu_config = MenuConfig::instance();
extra.menu_background.corner_radius = menu_config.CornerRadiusForMenu(
content_view_->GetMenuItem()->GetMenuController());
if (border_color_id_.has_value()) {
ui::ColorProvider* color_provider = GetColorProvider();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setColor(color_provider->GetColor(border_color_id_.value()));
canvas->DrawRoundRect(GetLocalBounds(), extra.menu_background.corner_radius,
flags);
return;
}
GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(),
ui::NativeTheme::kMenuPopupBackground,
ui::NativeTheme::kNormal, bounds, extra);
}
void MenuScrollViewContainer::GetAccessibleNodeData(ui::AXNodeData* node_data) {
// Get the name from the submenu view.
content_view_->GetAccessibleNodeData(node_data);
// On macOS, NSMenus are not supposed to have anything wrapped around them. To
// allow VoiceOver to recognize this as a menu and to read aloud the total
// number of items inside it, we ignore the MenuScrollViewContainer (which
// holds the menu itself: the SubmenuView).
#if BUILDFLAG(IS_MAC)
node_data->role = ax::mojom::Role::kNone;
#else
node_data->role = ax::mojom::Role::kMenuBar;
#endif
}
void MenuScrollViewContainer::OnBoundsChanged(
const gfx::Rect& previous_bounds) {
// When the bounds on the MenuScrollViewContainer itself change, the scroll
// offset is always reset to 0, so always hide the scroll-up control, and only
// show the scroll-down control if it's going to be useful.
scroll_up_button_->SetVisible(false);
scroll_down_button_->SetVisible(
scroll_view_->GetContents()->GetPreferredSize().height() > height());
const bool any_scroll_button_visible =
scroll_up_button_->GetVisible() || scroll_down_button_->GetVisible();
MenuItemView* const footnote = GetFootnote();
if (footnote)
footnote->SetCornerRadius(any_scroll_button_visible ? 0 : corner_radius_);
InvalidateLayout();
background_view_->SetBoundsRect(GetContentsBounds());
}
void MenuScrollViewContainer::DidScrollToTop() {
scroll_up_button_->SetVisible(false);
}
void MenuScrollViewContainer::DidScrollToBottom() {
scroll_down_button_->SetVisible(false);
}
void MenuScrollViewContainer::DidScrollAwayFromTop() {
scroll_up_button_->SetVisible(true);
}
void MenuScrollViewContainer::DidScrollAwayFromBottom() {
scroll_down_button_->SetVisible(true);
}
void MenuScrollViewContainer::CreateBorder() {
if (HasBubbleBorder())
CreateBubbleBorder();
else
CreateDefaultBorder();
}
void MenuScrollViewContainer::CreateDefaultBorder() {
DCHECK_EQ(arrow_, BubbleBorder::NONE);
MenuController* menu_controller =
content_view_->GetMenuItem()->GetMenuController();
const MenuConfig& menu_config = MenuConfig::instance();
corner_radius_ = menu_config.CornerRadiusForMenu(
content_view_->GetMenuItem()->GetMenuController());
int padding = menu_config.use_outer_border && corner_radius_ > 0
? kBorderPaddingDueToRoundedCorners
: 0;
const int vertical_inset =
(corner_radius_ ? corner_radius_
: menu_config.menu_vertical_border_size) +
padding;
const int horizontal_inset =
menu_config.menu_horizontal_border_size + padding;
int bottom_inset = GetFootnote() ? 0 : vertical_inset;
if (menu_config.use_outer_border) {
if (menu_config.use_bubble_border && (corner_radius_ > 0) &&
!menu_controller->IsCombobox()) {
CreateBubbleBorder();
} else {
gfx::Insets insets = gfx::Insets::TLBR(vertical_inset, horizontal_inset,
bottom_inset, horizontal_inset);
// When a custom background color is used, ensure that the border uses
// the custom background color for its insets.
if (border_color_id_.has_value()) {
SetBorder(views::CreateThemedSolidSidedBorder(
insets, border_color_id_.value()));
return;
}
SetBackground(CreateThemedRoundedRectBackground(ui::kColorMenuBackground,
corner_radius_));
SkColor color = GetWidget()
? GetColorProvider()->GetColor(ui::kColorMenuBorder)
: gfx::kPlaceholderColor;
SetBorder(views::CreateBorderPainter(
std::make_unique<views::RoundRectPainter>(color, corner_radius_),
insets));
}
} else {
SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(
vertical_inset, horizontal_inset, bottom_inset, horizontal_inset)));
}
}
void MenuScrollViewContainer::CreateBubbleBorder() {
const MenuConfig& menu_config = MenuConfig::instance();
auto* menu_controller = content_view_->GetMenuItem()->GetMenuController();
const int border_radius = menu_config.CornerRadiusForMenu(menu_controller);
ui::ColorId id = ui::kColorMenuBackground;
BubbleBorder::Shadow shadow_type = BubbleBorder::STANDARD_SHADOW;
#if BUILDFLAG(IS_CHROMEOS_ASH)
id = ui::kColorAshSystemUIMenuBackground;
// For ash system ui, we use chromeos system ui shadow.
if (use_ash_system_ui_layout_)
shadow_type = BubbleBorder::CHROMEOS_SYSTEM_UI_SHADOW;
#endif
if (border_color_id_.has_value()) {
// If there's a custom border color, use this for the bubble border color.
id = border_color_id_.value();
}
auto bubble_border = std::make_unique<BubbleBorder>(arrow_, shadow_type, id);
bool has_customized_corner = use_ash_system_ui_layout_ && menu_controller &&
menu_controller->rounded_corners().has_value();
if (use_ash_system_ui_layout_ || border_radius > 0 || has_customized_corner) {
if (has_customized_corner) {
bubble_border->SetRoundedCorners(
GetRoundedCorners().upper_left(), GetRoundedCorners().upper_right(),
GetRoundedCorners().lower_right(), GetRoundedCorners().lower_left());
} else {
bubble_border->SetCornerRadius(border_radius);
}
const bool is_top_menu = !content_view_->GetMenuItem()->GetParentMenuItem();
bubble_border->set_md_shadow_elevation(
is_top_menu ? menu_config.touchable_menu_shadow_elevation
: menu_config.touchable_submenu_shadow_elevation);
auto insets =
gfx::Insets::VH(menu_config.vertical_touchable_menu_item_padding, 0);
if (GetFootnote())
insets.set_bottom(0);
scroll_view_->GetContents()->SetBorder(CreateEmptyBorder(insets));
}
corner_radius_ = bubble_border->corner_radius();
// If the menu uses Ash system UI layout, use `background_view` to build a
// blurry background with highlight border. Otherwise, use default
// BubbleBackground.
if (use_ash_system_ui_layout_) {
background_view_->SetBackground(
CreateThemedRoundedRectBackground(id, corner_radius_));
background_view_->layer()->SetRoundedCornerRadius(GetRoundedCorners());
#if BUILDFLAG(IS_CHROMEOS_ASH)
background_view_->SetBorder(std::make_unique<HighlightBorder>(
GetRoundedCorners(),
chromeos::features::IsJellyrollEnabled()
? HighlightBorder::Type::kHighlightBorderOnShadow
: HighlightBorder::Type::kHighlightBorder1));
#endif
} else {
SetBackground(std::make_unique<BubbleBackground>(bubble_border.get()));
}
SetBorder(std::move(bubble_border));
}
BubbleBorder::Arrow MenuScrollViewContainer::BubbleBorderTypeFromAnchor(
MenuAnchorPosition anchor) {
switch (anchor) {
case MenuAnchorPosition::kTopLeft:
case MenuAnchorPosition::kTopRight:
case MenuAnchorPosition::kBottomCenter:
return BubbleBorder::NONE;
case MenuAnchorPosition::kBubbleTopLeft:
case MenuAnchorPosition::kBubbleTopRight:
case MenuAnchorPosition::kBubbleLeft:
case MenuAnchorPosition::kBubbleRight:
case MenuAnchorPosition::kBubbleBottomLeft:
case MenuAnchorPosition::kBubbleBottomRight:
return BubbleBorder::FLOAT;
}
}
BEGIN_METADATA(MenuScrollViewContainer, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_scroll_view_container.cc | C++ | unknown | 19,611 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/menu/menu_types.h"
#include "ui/views/view.h"
namespace gfx {
class RoundedCornersF;
} // namespace gfx
namespace views {
class MenuItemView;
class SubmenuView;
// MenuScrollViewContainer contains the SubmenuView (through a MenuScrollView)
// and two scroll buttons. The scroll buttons are only visible and enabled if
// the preferred height of the SubmenuView is bigger than our bounds.
class MenuScrollViewContainer : public View {
public:
METADATA_HEADER(MenuScrollViewContainer);
explicit MenuScrollViewContainer(SubmenuView* content_view);
MenuScrollViewContainer(const MenuScrollViewContainer&) = delete;
MenuScrollViewContainer& operator=(const MenuScrollViewContainer&) = delete;
// Returns the buttons for scrolling up/down.
View* scroll_down_button() const { return scroll_down_button_; }
View* scroll_up_button() const { return scroll_up_button_; }
// External function to check if the bubble border is used.
bool HasBubbleBorder() const;
// View overrides.
gfx::Size CalculatePreferredSize() const override;
void OnPaintBackground(gfx::Canvas* canvas) override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnThemeChanged() override;
void SetBorderColorId(absl::optional<ui::ColorId> border_color_id) {
border_color_id_ = border_color_id;
}
protected:
// View override.
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
private:
friend class MenuScrollView;
void DidScrollToTop();
void DidScrollToBottom();
void DidScrollAwayFromTop();
void DidScrollAwayFromBottom();
// Create a default border or bubble border, as appropriate.
void CreateBorder();
// Create the default border.
void CreateDefaultBorder();
// Create the bubble border.
void CreateBubbleBorder();
BubbleBorder::Arrow BubbleBorderTypeFromAnchor(MenuAnchorPosition anchor);
// Returns the last item in the menu if it is of type HIGHLIGHTED.
MenuItemView* GetFootnote() const;
// Calcultes the rounded corners of the view based on: either the
// `rounded_corners()` if it's set in `MenuController`, or the
// `CornerRadiusForMenu` in the `MenuConfig` if `rounded_corners()` is not
// set.
gfx::RoundedCornersF GetRoundedCorners() const;
class MenuScrollView;
// The background view.
raw_ptr<View> background_view_ = nullptr;
// The scroll buttons.
raw_ptr<View> scroll_up_button_;
raw_ptr<View> scroll_down_button_;
// The scroll view.
raw_ptr<MenuScrollView> scroll_view_;
// The content view.
raw_ptr<SubmenuView> content_view_;
// If set the currently set border is a bubble border.
BubbleBorder::Arrow arrow_ = BubbleBorder::NONE;
// Corner radius of the background.
int corner_radius_ = 0;
// Whether the menu uses ash system UI layout.
const bool use_ash_system_ui_layout_;
absl::optional<ui::ColorId> border_color_id_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_scroll_view_container.h | C++ | unknown | 3,347 |
// 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/menu_separator.h"
#include "build/build_config.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/canvas.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/menu/menu_config.h"
#if BUILDFLAG(IS_WIN)
#include "ui/display/win/dpi.h"
#endif
namespace views {
MenuSeparator::MenuSeparator(ui::MenuSeparatorType type) : type_(type) {
SetAccessibilityProperties(ax::mojom::Role::kSplitter);
}
void MenuSeparator::OnPaint(gfx::Canvas* canvas) {
if (type_ == ui::SPACING_SEPARATOR)
return;
const MenuConfig& menu_config = MenuConfig::instance();
int pos = 0;
int separator_thickness = menu_config.separator_thickness;
if (type_ == ui::DOUBLE_SEPARATOR)
separator_thickness = menu_config.double_separator_thickness;
switch (type_) {
case ui::LOWER_SEPARATOR:
pos = height() - separator_thickness;
break;
case ui::UPPER_SEPARATOR:
break;
default:
pos = (height() - separator_thickness) / 2;
break;
}
gfx::Rect paint_rect(0, pos, width(), separator_thickness);
if (type_ == ui::PADDED_SEPARATOR) {
paint_rect.Inset(
gfx::Insets::TLBR(0, menu_config.padded_separator_left_margin, 0,
menu_config.padded_separator_right_margin));
} else {
paint_rect.Inset(gfx::Insets::TLBR(0, menu_config.separator_left_margin, 0,
menu_config.separator_right_margin));
}
if (menu_config.use_outer_border && type_ != ui::PADDED_SEPARATOR) {
paint_rect.Inset(gfx::Insets::VH(0, 1));
}
#if BUILDFLAG(IS_WIN)
// Hack to get the separator to display correctly on Windows where we may
// have fractional scales. We move the separator 1 pixel down to ensure that
// it falls within the clipping rect which is scaled up.
float device_scale = display::win::GetDPIScale();
bool is_fractional_scale =
(device_scale - static_cast<int>(device_scale) != 0);
if (is_fractional_scale && paint_rect.y() == 0)
paint_rect.set_y(1);
#endif
ui::NativeTheme::ExtraParams params;
params.menu_separator.paint_rect = &paint_rect;
params.menu_separator.type = type_;
GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(),
ui::NativeTheme::kMenuPopupSeparator,
ui::NativeTheme::kNormal, GetLocalBounds(), params);
}
gfx::Size MenuSeparator::CalculatePreferredSize() const {
const MenuConfig& menu_config = MenuConfig::instance();
int height = menu_config.separator_height;
switch (type_) {
case ui::SPACING_SEPARATOR:
height = menu_config.separator_spacing_height;
break;
case ui::LOWER_SEPARATOR:
height = menu_config.separator_lower_height;
break;
case ui::UPPER_SEPARATOR:
height = menu_config.separator_upper_height;
break;
case ui::DOUBLE_SEPARATOR:
height = menu_config.double_separator_height;
break;
case ui::PADDED_SEPARATOR:
height = menu_config.separator_thickness;
break;
default:
height = menu_config.separator_height;
break;
}
return gfx::Size(10, // Just in case we're the only item in a menu.
height);
}
ui::MenuSeparatorType MenuSeparator::GetType() const {
return type_;
}
void MenuSeparator::SetType(ui::MenuSeparatorType type) {
if (type_ == type)
return;
type_ = type;
OnPropertyChanged(&type_, kPropertyEffectsPreferredSizeChanged);
}
BEGIN_METADATA(MenuSeparator, View)
ADD_PROPERTY_METADATA(ui::MenuSeparatorType, Type)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_separator.cc | C++ | unknown | 3,845 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT MenuSeparator : public View {
public:
METADATA_HEADER(MenuSeparator);
explicit MenuSeparator(
ui::MenuSeparatorType type = ui::MenuSeparatorType::NORMAL_SEPARATOR);
MenuSeparator(const MenuSeparator&) = delete;
MenuSeparator& operator=(const MenuSeparator&) = delete;
// View overrides.
void OnPaint(gfx::Canvas* canvas) override;
gfx::Size CalculatePreferredSize() const override;
ui::MenuSeparatorType GetType() const;
void SetType(ui::MenuSeparatorType type);
private:
// The type of the separator.
ui::MenuSeparatorType type_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_separator.h | C++ | unknown | 1,090 |
// 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 "ui/views/controls/menu/menu_separator.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/views_test_base.h"
namespace views {
using MenuSeparatorTest = ViewsTestBase;
TEST_F(MenuSeparatorTest, Metadata) {
auto separator = std::make_unique<MenuSeparator>();
test::TestViewMetadata(separator.get());
}
TEST_F(MenuSeparatorTest, TypeChangeEffect) {
auto separator = std::make_unique<MenuSeparator>();
separator->SizeToPreferredSize();
const MenuConfig& config = MenuConfig::instance();
EXPECT_EQ(config.separator_height, separator->height());
separator->SetType(ui::MenuSeparatorType::DOUBLE_SEPARATOR);
separator->SizeToPreferredSize();
EXPECT_EQ(config.double_separator_height, separator->height());
}
TEST_F(MenuSeparatorTest, AccessibleRole) {
auto separator = std::make_unique<MenuSeparator>();
ui::AXNodeData data;
separator->GetAccessibleNodeData(&data);
EXPECT_EQ(data.role, ax::mojom::Role::kSplitter);
EXPECT_EQ(separator->GetAccessibleRole(), ax::mojom::Role::kSplitter);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_separator_unittest.cc | C++ | unknown | 1,473 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_
namespace views {
// Where a popup menu should be anchored to for non-RTL languages. The opposite
// position will be used if base::i18n::IsRTL() is true. The Bubble flags are
// used when the menu should get enclosed by a bubble.
enum class MenuAnchorPosition {
kTopLeft,
kTopRight,
kBottomCenter,
kBubbleTopLeft,
kBubbleTopRight,
kBubbleLeft,
kBubbleRight,
kBubbleBottomLeft,
kBubbleBottomRight,
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/menu/menu_types.h | C++ | unknown | 727 |