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 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/animation/widget_fade_animator.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/views/widget/widget.h" namespace views { WidgetFadeAnimator::WidgetFadeAnimator(Widget* widget) : AnimationDelegateViews(widget->GetRootView()), widget_(widget) { widget_observation_.Observe(widget); } WidgetFadeAnimator::~WidgetFadeAnimator() = default; void WidgetFadeAnimator::FadeIn() { if (IsFadingIn()) return; DCHECK(widget_); animation_type_ = FadeType::kFadeIn; fade_animation_.SetDuration(fade_in_duration_); // Widgets cannot be shown when visible and fully transparent. widget_->SetOpacity(0.01f); widget_->Show(); fade_animation_.Start(); } void WidgetFadeAnimator::CancelFadeIn() { if (!IsFadingIn()) return; fade_animation_.Stop(); animation_type_ = FadeType::kNone; } void WidgetFadeAnimator::FadeOut() { if (IsFadingOut() || !widget_) return; // If the widget is already hidden, then there is no current animation and // nothing to do. If the animation is close-on-hide, however, we should still // close the widget. if (!widget_->IsVisible()) { DCHECK(!IsFadingIn()); if (close_on_hide_) widget_->Close(); fade_complete_callbacks_.Notify(this, FadeType::kFadeOut); return; } animation_type_ = FadeType::kFadeOut; fade_animation_.SetDuration(fade_out_duration_); fade_animation_.Start(); } void WidgetFadeAnimator::CancelFadeOut() { if (!IsFadingOut()) return; fade_animation_.Stop(); animation_type_ = FadeType::kNone; widget_->SetOpacity(1.0f); } base::CallbackListSubscription WidgetFadeAnimator::AddFadeCompleteCallback( FadeCompleteCallback callback) { return fade_complete_callbacks_.Add(callback); } void WidgetFadeAnimator::AnimationProgressed(const gfx::Animation* animation) { // Get the value of the animation with a material ease applied. double value = gfx::Tween::CalculateValue(tween_type_, animation->GetCurrentValue()); float opacity = 0.0f; if (IsFadingOut()) opacity = gfx::Tween::FloatValueBetween(value, 1.0f, 0.0f); else if (IsFadingIn()) opacity = gfx::Tween::FloatValueBetween(value, 0.0f, 1.0f); if (IsFadingOut() && opacity == 0.0f) { if (close_on_hide_) widget_->Close(); else widget_->Hide(); } else { widget_->SetOpacity(opacity); } } void WidgetFadeAnimator::AnimationEnded(const gfx::Animation* animation) { const FadeType animation_type = animation_type_; AnimationProgressed(animation); animation_type_ = FadeType::kNone; fade_complete_callbacks_.Notify(this, animation_type); } void WidgetFadeAnimator::OnWidgetDestroying(Widget* widget) { widget_observation_.Reset(); fade_animation_.End(); animation_type_ = FadeType::kNone; widget_ = nullptr; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/animation/widget_fade_animator.cc
C++
unknown
2,967
// 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_ANIMATION_WIDGET_FADE_ANIMATOR_H_ #define UI_VIEWS_ANIMATION_WIDGET_FADE_ANIMATOR_H_ #include "base/callback_list.h" #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" #include "base/time/time.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/gfx/animation/tween.h" #include "ui/views/animation/animation_delegate_views.h" #include "ui/views/views_export.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace views { class Widget; // Animates a widget's opacity between fully hidden and fully shown, providing // a fade-in/fade-out effect. class VIEWS_EXPORT WidgetFadeAnimator : public AnimationDelegateViews, public WidgetObserver { public: // Describes the current fade animation. enum class FadeType { kNone, kFadeIn, kFadeOut, }; // Defines a callback for when a fade completes. Not called on cancel. The // |animation_type| of the completed animation is specified (it will never be // kNone). using FadeCompleteCallbackSignature = void(WidgetFadeAnimator*, FadeType animation_type); using FadeCompleteCallback = base::RepeatingCallback<FadeCompleteCallbackSignature>; // Creates a new fade animator for the specified widget. If the widget closes // the animator will no longer be valid and should not be used. explicit WidgetFadeAnimator(Widget* widget); WidgetFadeAnimator(const WidgetFadeAnimator&) = delete; WidgetFadeAnimator& operator=(const WidgetFadeAnimator&) = delete; ~WidgetFadeAnimator() override; void set_fade_in_duration(base::TimeDelta fade_in_duration) { fade_in_duration_ = fade_in_duration; } base::TimeDelta fade_in_duration() const { return fade_in_duration_; } void set_fade_out_duration(base::TimeDelta fade_out_duration) { fade_out_duration_ = fade_out_duration; } base::TimeDelta fade_out_duration() const { return fade_out_duration_; } void set_tween_type(gfx::Tween::Type tween_type) { tween_type_ = tween_type; } gfx::Tween::Type tween_type() const { return tween_type_; } void set_close_on_hide(bool close_on_hide) { close_on_hide_ = close_on_hide; } bool close_on_hide() const { return close_on_hide_; } Widget* widget() { return widget_; } bool IsFadingIn() const { return animation_type_ == FadeType::kFadeIn; } bool IsFadingOut() const { return animation_type_ == FadeType::kFadeOut; } // Plays the fade-in animation. If the widget is not currently visible, it // will be made visible. void FadeIn(); // Cancels any pending fade-in, leaves the widget at the current opacity to // avoid abrupt visual changes. CancelFadeIn() should be followed with // something, either another FadeIn(), or widget closing. It has no effect // if the widget is not fading in. void CancelFadeIn(); // Plays the fade-out animation. At the end of the fade, the widget will be // hidden or closed, as per |close_on_hide|. If the widget is already hidden // or closed, completes immediately. void FadeOut(); // Cancels any pending fade-out, returning the widget to 100% opacity. Has no // effect if the widget is not fading out. void CancelFadeOut(); // Adds a listener for fade complete events. base::CallbackListSubscription AddFadeCompleteCallback( FadeCompleteCallback callback); private: // AnimationDelegateViews: void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; // WidgetObserver: void OnWidgetDestroying(Widget* widget) override; raw_ptr<Widget> widget_; base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this}; gfx::LinearAnimation fade_animation_{this}; FadeType animation_type_ = FadeType::kNone; // Duration for fade-in animations. The default should be visually pleasing // for most applications. base::TimeDelta fade_in_duration_ = base::Milliseconds(200); // Duration for fade-out animations. The default should be visually pleasing // for most applications. base::TimeDelta fade_out_duration_ = base::Milliseconds(150); // The tween type to use. The default value should be pleasing for most // applications. gfx::Tween::Type tween_type_ = gfx::Tween::FAST_OUT_SLOW_IN; // Whether the widget should be closed at the end of a fade-out animation. bool close_on_hide_ = false; base::RepeatingCallbackList<FadeCompleteCallbackSignature> fade_complete_callbacks_; }; } // namespace views #endif // UI_VIEWS_ANIMATION_WIDGET_FADE_ANIMATOR_H_
Zhao-PengFei35/chromium_src_4
ui/views/animation/widget_fade_animator.h
C++
unknown
4,903
// 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/animation/widget_fade_animator.h" #include <memory> #include "base/test/bind.h" #include "base/time/time.h" #include "ui/gfx/animation/animation_test_api.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" namespace views { namespace { constexpr base::TimeDelta kFadeDuration = base::Milliseconds(1000); constexpr base::TimeDelta kHalfFadeDuration = kFadeDuration / 2; class TestWidgetFadeAnimator : public WidgetFadeAnimator { public: using WidgetFadeAnimator::WidgetFadeAnimator; ~TestWidgetFadeAnimator() override = default; void AnimationContainerWasSet(gfx::AnimationContainer* container) override { WidgetFadeAnimator::AnimationContainerWasSet(container); container_test_api_.reset(); if (container) { container_test_api_ = std::make_unique<gfx::AnimationContainerTestApi>(container); } } gfx::AnimationContainerTestApi* test_api() { return container_test_api_.get(); } private: std::unique_ptr<gfx::AnimationContainerTestApi> container_test_api_; }; } // namespace class WidgetFadeAnimatorTest : public test::WidgetTest { public: void SetUp() override { test::WidgetTest::SetUp(); widget_ = CreateTestWidget(Widget::InitParams::Type::TYPE_WINDOW); delegate_ = std::make_unique<TestWidgetFadeAnimator>(widget_.get()); delegate_->set_fade_in_duration(kFadeDuration); delegate_->set_fade_out_duration(kFadeDuration); } void TearDown() override { if (widget_ && !widget_->IsClosed()) widget_->CloseNow(); test::WidgetTest::TearDown(); } protected: std::unique_ptr<Widget> widget_; std::unique_ptr<TestWidgetFadeAnimator> delegate_; }; TEST_F(WidgetFadeAnimatorTest, FadeIn) { EXPECT_FALSE(widget_->IsVisible()); delegate_->FadeIn(); // Fade in should set visibility and opacity to some small value. EXPECT_TRUE(widget_->IsVisible()); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, FadeInAnimationProgressesToEnd) { delegate_->FadeIn(); // Note that there is currently no way to *read* a widget's opacity, so we can // only verify that the widget's visibility changes appropriately at the // beginning and end of each animation. delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_TRUE(widget_->IsVisible()); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, FadeOut) { widget_->Show(); EXPECT_TRUE(widget_->IsVisible()); delegate_->FadeOut(); // Fade in should set visibility and opacity to some small value. EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_TRUE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, FadeOutAnimationProgressesToEnd) { widget_->Show(); delegate_->FadeOut(); // Note that there is currently no way to *read* a widget's opacity, so we can // only verify that the widget's visibility changes appropriately at the // beginning and end of each animation. delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_TRUE(delegate_->IsFadingOut()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_FALSE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, CancelFadeOutAtStart) { widget_->Show(); delegate_->FadeOut(); delegate_->CancelFadeOut(); EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, CancelFadeOutInMiddle) { widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_->CancelFadeOut(); EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, CancelFadeOutAtEndHasNoEffect) { widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kFadeDuration); delegate_->CancelFadeOut(); EXPECT_FALSE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, CancelFadeOutHasNoEffectIfFadingIn) { delegate_->FadeIn(); delegate_->CancelFadeOut(); EXPECT_TRUE(widget_->IsVisible()); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_->CancelFadeOut(); EXPECT_TRUE(widget_->IsVisible()); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_->CancelFadeOut(); EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, FadeOutClosesWidget) { delegate_->set_close_on_hide(true); widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kFadeDuration); EXPECT_TRUE(widget_->IsClosed()); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, WidgetClosedDuringFade) { widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); widget_->CloseNow(); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, WidgetDestroyedDuringFade) { widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); widget_->Close(); widget_.reset(); EXPECT_FALSE(delegate_->IsFadingOut()); } TEST_F(WidgetFadeAnimatorTest, AnimatorDestroyedDuringFade) { delegate_->FadeIn(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_.reset(); } TEST_F(WidgetFadeAnimatorTest, FadeOutInterruptsFadeIn) { delegate_->FadeIn(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_->FadeOut(); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_TRUE(delegate_->IsFadingOut()); EXPECT_TRUE(widget_->IsVisible()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_TRUE(delegate_->IsFadingOut()); EXPECT_TRUE(widget_->IsVisible()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); EXPECT_FALSE(widget_->IsVisible()); } TEST_F(WidgetFadeAnimatorTest, FadeInInterruptsFadeOut) { widget_->Show(); delegate_->FadeOut(); delegate_->test_api()->IncrementTime(kHalfFadeDuration); delegate_->FadeIn(); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); EXPECT_TRUE(widget_->IsVisible()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_TRUE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); EXPECT_TRUE(widget_->IsVisible()); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_FALSE(delegate_->IsFadingIn()); EXPECT_FALSE(delegate_->IsFadingOut()); EXPECT_TRUE(widget_->IsVisible()); } TEST_F(WidgetFadeAnimatorTest, FadeInCallback) { int called_count = 0; WidgetFadeAnimator::FadeType anim_type = WidgetFadeAnimator::FadeType::kNone; auto subscription = delegate_->AddFadeCompleteCallback(base::BindLambdaForTesting( [&](WidgetFadeAnimator*, WidgetFadeAnimator::FadeType animation_type) { ++called_count; anim_type = animation_type; })); delegate_->FadeIn(); EXPECT_EQ(0, called_count); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_EQ(0, called_count); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_EQ(1, called_count); EXPECT_EQ(WidgetFadeAnimator::FadeType::kFadeIn, anim_type); } TEST_F(WidgetFadeAnimatorTest, FadeOutCallback) { int called_count = 0; WidgetFadeAnimator::FadeType anim_type = WidgetFadeAnimator::FadeType::kNone; auto subscription = delegate_->AddFadeCompleteCallback(base::BindLambdaForTesting( [&](WidgetFadeAnimator*, WidgetFadeAnimator::FadeType animation_type) { ++called_count; anim_type = animation_type; })); widget_->Show(); delegate_->FadeOut(); EXPECT_EQ(0, called_count); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_EQ(0, called_count); delegate_->test_api()->IncrementTime(kHalfFadeDuration); EXPECT_EQ(1, called_count); EXPECT_EQ(WidgetFadeAnimator::FadeType::kFadeOut, anim_type); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/animation/widget_fade_animator_unittest.cc
C++
unknown
9,046
// 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/background.h" #include <utility> #include "base/check.h" #include "build/build_config.h" #include "cc/paint/paint_flags.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/views/painter.h" #include "ui/views/view.h" #if BUILDFLAG(IS_WIN) #include "skia/ext/skia_utils_win.h" #endif namespace views { // SolidBackground is a trivial Background implementation that fills the // background in a solid color. class SolidBackground : public Background { public: explicit SolidBackground(SkColor color) { SetNativeControlColor(color); } SolidBackground(const SolidBackground&) = delete; SolidBackground& operator=(const SolidBackground&) = delete; void Paint(gfx::Canvas* canvas, View* view) const override { // Fill the background. Note that we don't constrain to the bounds as // canvas is already clipped for us. canvas->DrawColor(get_color()); } }; // Shared class for RoundedRectBackground and ThemedRoundedRectBackground. class BaseRoundedRectBackground : public Background { public: BaseRoundedRectBackground(float top_radius, float bottom_radius, int for_border_thickness) : BaseRoundedRectBackground( Radii{ .top_left = top_radius, .top_right = top_radius, .bottom_right = bottom_radius, .bottom_left = bottom_radius, }, for_border_thickness) {} BaseRoundedRectBackground(const Radii& radii, int for_border_thickness) : radii_(radii), half_thickness_(for_border_thickness / 2.0f) {} BaseRoundedRectBackground(const BaseRoundedRectBackground&) = delete; BaseRoundedRectBackground& operator=(const BaseRoundedRectBackground&) = delete; void Paint(gfx::Canvas* canvas, View* view) const override { gfx::Rect rect(view->GetLocalBounds()); rect.Inset(half_thickness_); SkPath path; SkScalar radii[8] = {radii_.top_left, radii_.top_left, radii_.top_right, radii_.top_right, radii_.bottom_right, radii_.bottom_right, radii_.bottom_left, radii_.bottom_left}; path.addRoundRect(gfx::RectToSkRect(rect), radii); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(get_color()); canvas->DrawPath(path, flags); } private: const Radii radii_; const float half_thickness_; }; // RoundedRectBackground is a filled solid colored background that has // rounded corners. class RoundedRectBackground : public BaseRoundedRectBackground { public: RoundedRectBackground(SkColor color, float radius, int for_border_thickness) : BaseRoundedRectBackground(radius, radius, for_border_thickness) { SetNativeControlColor(color); } RoundedRectBackground(const RoundedRectBackground&) = delete; RoundedRectBackground& operator=(const RoundedRectBackground&) = delete; }; // ThemedVectorIconBackground is an image drawn on the view's background using // ThemedVectorIcon to react to theme changes. class ThemedVectorIconBackground : public Background { public: explicit ThemedVectorIconBackground(const ui::ThemedVectorIcon& icon) : icon_(icon) { DCHECK(!icon_.empty()); } ThemedVectorIconBackground(const ThemedVectorIconBackground&) = delete; ThemedVectorIconBackground& operator=(const ThemedVectorIconBackground&) = delete; void OnViewThemeChanged(View* view) override { view->SchedulePaint(); } void Paint(gfx::Canvas* canvas, View* view) const override { canvas->DrawImageInt(icon_.GetImageSkia(view->GetColorProvider()), 0, 0); } private: const ui::ThemedVectorIcon icon_; }; // ThemedSolidBackground is a solid background that stays in sync with a view's // ColorProvider. class ThemedSolidBackground : public SolidBackground { public: explicit ThemedSolidBackground(ui::ColorId color_id) : SolidBackground(gfx::kPlaceholderColor), color_id_(color_id) {} ThemedSolidBackground(const ThemedSolidBackground&) = delete; ThemedSolidBackground& operator=(const ThemedSolidBackground&) = delete; ~ThemedSolidBackground() override = default; void OnViewThemeChanged(View* view) override { SetNativeControlColor(view->GetColorProvider()->GetColor(color_id_)); view->SchedulePaint(); } private: const ui::ColorId color_id_; }; // ThemedRoundedRectBackground is a solid rounded rect background that stays in // sync with a view's ColorProvider. class ThemedRoundedRectBackground : public BaseRoundedRectBackground { public: ThemedRoundedRectBackground(ui::ColorId color_id, float radius, int for_border_thickness) : ThemedRoundedRectBackground(color_id, radius, radius, for_border_thickness) {} ThemedRoundedRectBackground(ui::ColorId color_id, float top_radius, float bottom_radius, int for_border_thickness) : ThemedRoundedRectBackground(color_id, Radii{.top_left = top_radius, .top_right = top_radius, .bottom_right = bottom_radius, .bottom_left = bottom_radius}, for_border_thickness) {} ThemedRoundedRectBackground(ui::ColorId color_id, const Radii& radii, int for_border_thickness) : BaseRoundedRectBackground(radii, for_border_thickness), color_id_(color_id) {} ThemedRoundedRectBackground(const ThemedRoundedRectBackground&) = delete; ThemedRoundedRectBackground& operator=(const ThemedRoundedRectBackground&) = delete; ~ThemedRoundedRectBackground() override = default; void OnViewThemeChanged(View* view) override { SetNativeControlColor(view->GetColorProvider()->GetColor(color_id_)); view->SchedulePaint(); } private: const ui::ColorId color_id_; }; class BackgroundPainter : public Background { public: explicit BackgroundPainter(std::unique_ptr<Painter> painter) : painter_(std::move(painter)) { DCHECK(painter_); } BackgroundPainter(const BackgroundPainter&) = delete; BackgroundPainter& operator=(const BackgroundPainter&) = delete; ~BackgroundPainter() override = default; void Paint(gfx::Canvas* canvas, View* view) const override { Painter::PaintPainterAt(canvas, painter_.get(), view->GetLocalBounds()); } private: std::unique_ptr<Painter> painter_; }; Background::Background() = default; Background::~Background() = default; void Background::SetNativeControlColor(SkColor color) { color_ = color; } void Background::OnViewThemeChanged(View* view) {} std::unique_ptr<Background> CreateSolidBackground(SkColor color) { return std::make_unique<SolidBackground>(color); } std::unique_ptr<Background> CreateRoundedRectBackground( SkColor color, float radius, int for_border_thickness) { return std::make_unique<RoundedRectBackground>(color, radius, for_border_thickness); } std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, float radius, int for_border_thickness) { return std::make_unique<ThemedRoundedRectBackground>(color_id, radius, for_border_thickness); } std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, float top_radius, float bottom_radius, int for_border_thickness) { return std::make_unique<ThemedRoundedRectBackground>( color_id, top_radius, bottom_radius, for_border_thickness); } std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, const Radii& radii, int for_border_thickness) { return std::make_unique<ThemedRoundedRectBackground>(color_id, radii, for_border_thickness); } std::unique_ptr<Background> CreateThemedVectorIconBackground( const ui::ThemedVectorIcon& icon) { return std::make_unique<ThemedVectorIconBackground>(icon); } std::unique_ptr<Background> CreateThemedSolidBackground(ui::ColorId color_id) { return std::make_unique<ThemedSolidBackground>(color_id); } std::unique_ptr<Background> CreateBackgroundFromPainter( std::unique_ptr<Painter> painter) { return std::make_unique<BackgroundPainter>(std::move(painter)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/background.cc
C++
unknown
9,009
// 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_BACKGROUND_H_ #define UI_VIEWS_BACKGROUND_H_ #include <stddef.h> #include <memory> #include "build/build_config.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/themed_vector_icon.h" #include "ui/color/color_id.h" #include "ui/gfx/color_palette.h" #include "ui/views/views_export.h" namespace gfx { class Canvas; } namespace ui { class ThemedVectorIcon; } namespace views { class Painter; class View; ///////////////////////////////////////////////////////////////////////////// // // Background class // // A background implements a way for views to paint a background. The // background can be either solid or based on a gradient. Of course, // Background can be subclassed to implement various effects. // // Any View can have a background. See View::SetBackground() and // View::OnPaintBackground() // ///////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT Background { public: Background(); Background(const Background&) = delete; Background& operator=(const Background&) = delete; virtual ~Background(); // Render the background for the provided view virtual void Paint(gfx::Canvas* canvas, View* view) const = 0; // Set a solid, opaque color to be used when drawing backgrounds of native // controls. Unfortunately alpha=0 is not an option. void SetNativeControlColor(SkColor color); // This is called by the View on which it is attached. This is overridden for // subclasses that depend on theme colors. virtual void OnViewThemeChanged(View* view); // Returns the "background color". This is equivalent to the color set in // SetNativeControlColor(). For solid backgrounds, this is the color; for // gradient backgrounds, it's the midpoint of the gradient; for painter // backgrounds, this is not useful (returns a default color). SkColor get_color() const { return color_; } private: SkColor color_ = gfx::kPlaceholderColor; }; struct VIEWS_EXPORT Radii { float top_left; float top_right; float bottom_right; float bottom_left; }; // Creates a background that fills the canvas in the specified color. VIEWS_EXPORT std::unique_ptr<Background> CreateSolidBackground(SkColor color); // Creates a background that fills the canvas with rounded corners. // If using a rounded rect border as well, pass its radius as `radius` and its // thickness as `for_border_thickness`. This will inset the background properly // so it doesn't bleed through the border. VIEWS_EXPORT std::unique_ptr<Background> CreateRoundedRectBackground( SkColor color, float radius, int for_border_thickness = 0); // Same as above except it uses the color specified by the views's ColorProvider // and the given color identifier. VIEWS_EXPORT std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, float radius, int for_border_thickness = 0); // Same as above except its top corner radius and bottom corner radius can be // different and customized. VIEWS_EXPORT std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, float top_radius, float bottom_radius, int for_border_thickness); // Same as above except each corner radius can be different and customized. VIEWS_EXPORT std::unique_ptr<Background> CreateThemedRoundedRectBackground( ui::ColorId color_id, const Radii& radii, int for_border_thickness); // Creates a background that fills the canvas in the color specified by the // view's ColorProvider and the given color identifier. VIEWS_EXPORT std::unique_ptr<Background> CreateThemedSolidBackground( ui::ColorId color_id); // Creates a background from the specified Painter. VIEWS_EXPORT std::unique_ptr<Background> CreateBackgroundFromPainter( std::unique_ptr<Painter> painter); // Creates a background from the specified ThemedVectorIcon. VIEWS_EXPORT std::unique_ptr<Background> CreateThemedVectorIconBackground( const ui::ThemedVectorIcon& icon); } // namespace views #endif // UI_VIEWS_BACKGROUND_H_
Zhao-PengFei35/chromium_src_4
ui/views/background.h
C++
unknown
4,215
// 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/badge_painter.h" #include <algorithm> #include "base/i18n/rtl.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/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/text_constants.h" #include "ui/gfx/text_utils.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/style/typography.h" #include "ui/views/view.h" namespace views { namespace { // Returns the highlight rect for the badge given the font and text rect // for the badge text. gfx::Rect GetBadgeRectOutsetAroundText(const gfx::FontList& badge_font, const gfx::Rect& badge_text_rect) { gfx::Rect badge_rect = badge_text_rect; badge_rect.Inset(-gfx::AdjustVisualBorderForFont( badge_font, gfx::Insets(BadgePainter::kBadgeInternalPadding))); return badge_rect; } } // namespace // static void BadgePainter::PaintBadge(gfx::Canvas* canvas, const View* view, int unmirrored_badge_left_x, int text_top_y, const std::u16string& text, const gfx::FontList& primary_font) { gfx::FontList badge_font = GetBadgeFont(primary_font); // Calculate bounding box for badge text. unmirrored_badge_left_x += kBadgeInternalPadding; text_top_y += gfx::GetFontCapHeightCenterOffset(primary_font, badge_font); gfx::Rect badge_text_bounds(gfx::Point(unmirrored_badge_left_x, text_top_y), gfx::GetStringSize(text, badge_font)); if (base::i18n::IsRTL()) { badge_text_bounds.set_x(view->GetMirroredXForRect(badge_text_bounds)); } // Render the badge itself. cc::PaintFlags flags; const ui::ColorProvider* color_provider = view->GetColorProvider(); const SkColor background_color = color_provider->GetColor(ui::kColorBadgeBackground); flags.setColor(background_color); canvas->DrawRoundRect( GetBadgeRectOutsetAroundText(badge_font, badge_text_bounds), LayoutProvider::Get()->GetCornerRadiusMetric( ShapeContextTokens::kBadgeRadius), flags); // Render the badge text. const SkColor foreground_color = color_provider->GetColor(ui::kColorBadgeForeground); canvas->DrawStringRect(text, badge_font, foreground_color, badge_text_bounds); } // static gfx::Size BadgePainter::GetBadgeSize(const std::u16string& text, const gfx::FontList& primary_font) { gfx::FontList badge_font = GetBadgeFont(primary_font); const gfx::Size text_size = gfx::GetStringSize(text, badge_font); return GetBadgeRectOutsetAroundText(badge_font, gfx::Rect(text_size)).size(); } gfx::FontList BadgePainter::GetBadgeFont(const gfx::FontList& context_font) { if (features::IsChromeRefresh2023()) { return views::style::GetFont(views::style::CONTEXT_BADGE, views::style::STYLE_SECONDARY); } // Preferred font is slightly smaller and slightly more bold than the title // 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. return context_font.Derive(BadgePainter::kBadgeFontSizeAdjustment, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/badge_painter.cc
C++
unknown
3,690
// 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_BADGE_PAINTER_H_ #define UI_VIEWS_BADGE_PAINTER_H_ #include <string> #include "ui/views/views_export.h" namespace gfx { class Canvas; class FontList; class Size; } // namespace gfx namespace views { class View; // Painter that paints a badge on the canvas of any other view. // Provides static methods only; class VIEWS_EXPORT BadgePainter { public: // This is a utility class and should not be instantiated. BadgePainter() = delete; // Draws the badge on `canvas`. `unmirrored_badge_left_x` is the // leading edge of the badge, not mirrored for RTL. `text_top_y` is the // top of the text the badge should align with, and `primary_font` is the font // of that text. // // You can call this method from any View to draw the badge directly onto the // view as part of OnPaint() or a similar method. static void PaintBadge(gfx::Canvas* canvas, const View* view, int unmirrored_badge_left_x, int text_top_y, const std::u16string& text, const gfx::FontList& primary_font); // Returns the space required for the badge itself, not counting leading // or trailing margin. It is recommended to leave a margin of // BadgePainter::kBadgeHorizontalMargin between the badge and any other text // or image elements. static gfx::Size GetBadgeSize(const std::u16string& text, const gfx::FontList& primary_font); // Returns the appropriate font to use for the badge based on the font // currently being used to render the surrounding text. static gfx::FontList GetBadgeFont(const gfx::FontList& context_font); // Layout Constants // // Note that there are a few differences between Views and Mac constants here // that are due to the fact that the rendering is different and therefore // tweaks to the spacing need to be made to achieve the same visual result. // Difference in the font size (in pixels) between menu label font and // badge font size. static constexpr int kBadgeFontSizeAdjustment = -1; // Space between primary text and badge. static constexpr int kBadgeHorizontalMargin = 8; // Highlight padding around text. static constexpr int kBadgeInternalPadding = 4; static constexpr int kBadgeInternalPaddingTopMac = 1; }; } // namespace views #endif // UI_VIEWS_BADGE_PAINTER_H_
Zhao-PengFei35/chromium_src_4
ui/views/badge_painter.h
C++
unknown
2,573
// 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/border.h" #include <memory> #include <utility> #include "base/check.h" #include "base/memory/ptr_util.h" #include "cc/paint/paint_flags.h" #include "ui/color/color_provider.h" #include "ui/compositor/layer.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/insets_conversions.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/scoped_canvas.h" #include "ui/views/painter.h" #include "ui/views/view.h" namespace views { namespace { // A simple border with different thicknesses on each side and single color. class SolidSidedBorder : public Border { public: SolidSidedBorder(const gfx::Insets& insets, SkColor color); SolidSidedBorder(const SolidSidedBorder&) = delete; SolidSidedBorder& operator=(const SolidSidedBorder&) = delete; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: const gfx::Insets insets_; }; SolidSidedBorder::SolidSidedBorder(const gfx::Insets& insets, SkColor color) : Border(color), insets_(insets) {} void SolidSidedBorder::Paint(const View& view, gfx::Canvas* canvas) { // Undo DSF so that we can be sure to draw an integral number of pixels for // the border. Integral scale factors should be unaffected by this, but for // fractional scale factors this ensures sharp lines. gfx::ScopedCanvas scoped(canvas); float dsf = canvas->UndoDeviceScaleFactor(); gfx::RectF scaled_bounds; if (view.layer()) { scaled_bounds = gfx::ConvertRectToPixels( view.GetLocalBounds(), view.layer()->device_scale_factor()); } else { scaled_bounds = gfx::RectF(view.GetLocalBounds()); scaled_bounds.Scale(dsf); } gfx::InsetsF insets_in_pixels( gfx::ToFlooredInsets(gfx::ConvertInsetsToPixels(insets_, dsf))); scaled_bounds.Inset(insets_in_pixels); canvas->sk_canvas()->clipRect(gfx::RectFToSkRect(scaled_bounds), SkClipOp::kDifference, true); canvas->DrawColor(color()); } gfx::Insets SolidSidedBorder::GetInsets() const { return insets_; } gfx::Size SolidSidedBorder::GetMinimumSize() const { return gfx::Size(insets_.width(), insets_.height()); } class ThemedSolidSidedBorder : public SolidSidedBorder { public: ThemedSolidSidedBorder(const gfx::Insets& insets, ui::ColorId color_id); // SolidSidedBorder: void Paint(const View& view, gfx::Canvas* canvas) override; void OnViewThemeChanged(View* view) override; private: ui::ColorId color_id_; }; ThemedSolidSidedBorder::ThemedSolidSidedBorder(const gfx::Insets& insets, ui::ColorId color_id) : SolidSidedBorder(insets, gfx::kPlaceholderColor), color_id_(color_id) {} void ThemedSolidSidedBorder::Paint(const View& view, gfx::Canvas* canvas) { set_color(view.GetColorProvider()->GetColor(color_id_)); SolidSidedBorder::Paint(view, canvas); } void ThemedSolidSidedBorder::OnViewThemeChanged(View* view) { view->SchedulePaint(); } // A border with a rounded rectangle and single color. class RoundedRectBorder : public Border { public: RoundedRectBorder(int thickness, float corner_radius, const gfx::Insets& paint_insets, SkColor color); RoundedRectBorder(const RoundedRectBorder&) = delete; RoundedRectBorder& operator=(const RoundedRectBorder&) = delete; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: const int thickness_; const float corner_radius_; const gfx::Insets paint_insets_; }; RoundedRectBorder::RoundedRectBorder(int thickness, float corner_radius, const gfx::Insets& paint_insets, SkColor color) : Border(color), thickness_(thickness), corner_radius_(corner_radius), paint_insets_(paint_insets) {} void RoundedRectBorder::Paint(const View& view, gfx::Canvas* canvas) { cc::PaintFlags flags; flags.setStrokeWidth(thickness_); flags.setColor(color()); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setAntiAlias(true); const float half_thickness = thickness_ / 2.0f; gfx::RectF bounds(view.GetLocalBounds()); bounds.Inset(gfx::InsetsF(paint_insets_)); bounds.Inset(half_thickness); canvas->DrawRoundRect(bounds, corner_radius_ - half_thickness, flags); } gfx::Insets RoundedRectBorder::GetInsets() const { return gfx::Insets(thickness_) + paint_insets_; } gfx::Size RoundedRectBorder::GetMinimumSize() const { return gfx::Size(thickness_ * 2, thickness_ * 2); } class EmptyBorder : public Border { public: explicit EmptyBorder(const gfx::Insets& insets); EmptyBorder(const EmptyBorder&) = delete; EmptyBorder& operator=(const EmptyBorder&) = delete; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: const gfx::Insets insets_; }; EmptyBorder::EmptyBorder(const gfx::Insets& insets) : insets_(insets) {} void EmptyBorder::Paint(const View& view, gfx::Canvas* canvas) {} gfx::Insets EmptyBorder::GetInsets() const { return insets_; } gfx::Size EmptyBorder::GetMinimumSize() const { return gfx::Size(); } class ExtraInsetsBorder : public Border { public: ExtraInsetsBorder(std::unique_ptr<Border> border, const gfx::Insets& insets); ExtraInsetsBorder(const ExtraInsetsBorder&) = delete; ExtraInsetsBorder& operator=(const ExtraInsetsBorder&) = delete; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: std::unique_ptr<Border> border_; const gfx::Insets extra_insets_; }; ExtraInsetsBorder::ExtraInsetsBorder(std::unique_ptr<Border> border, const gfx::Insets& insets) : Border(border->color()), border_(std::move(border)), extra_insets_(insets) {} void ExtraInsetsBorder::Paint(const View& view, gfx::Canvas* canvas) { border_->Paint(view, canvas); } gfx::Insets ExtraInsetsBorder::GetInsets() const { return border_->GetInsets() + extra_insets_; } gfx::Size ExtraInsetsBorder::GetMinimumSize() const { gfx::Size size = border_->GetMinimumSize(); size.Enlarge(extra_insets_.width(), extra_insets_.height()); return size; } class BorderPainter : public Border { public: BorderPainter(std::unique_ptr<Painter> painter, const gfx::Insets& insets); BorderPainter(const BorderPainter&) = delete; BorderPainter& operator=(const BorderPainter&) = delete; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: std::unique_ptr<Painter> painter_; const gfx::Insets insets_; }; BorderPainter::BorderPainter(std::unique_ptr<Painter> painter, const gfx::Insets& insets) : painter_(std::move(painter)), insets_(insets) { DCHECK(painter_); } void BorderPainter::Paint(const View& view, gfx::Canvas* canvas) { Painter::PaintPainterAt(canvas, painter_.get(), view.GetLocalBounds()); } gfx::Insets BorderPainter::GetInsets() const { return insets_; } gfx::Size BorderPainter::GetMinimumSize() const { return painter_->GetMinimumSize(); } class ThemedRoundedRectBorder : public RoundedRectBorder { public: ThemedRoundedRectBorder(int thickness, float corner_radius, const gfx::Insets& paint_insets, ui::ColorId color_id) : RoundedRectBorder(thickness, corner_radius, paint_insets, gfx::kPlaceholderColor), color_id_(color_id) {} ThemedRoundedRectBorder(const ThemedRoundedRectBorder&) = delete; ThemedRoundedRectBorder& operator=(const ThemedRoundedRectBorder&) = delete; void Paint(const View& view, gfx::Canvas* canvas) override { set_color(view.GetColorProvider()->GetColor(color_id_)); RoundedRectBorder::Paint(view, canvas); } void OnViewThemeChanged(View* view) override { view->SchedulePaint(); } private: const ui::ColorId color_id_; }; } // namespace Border::Border() = default; Border::Border(SkColor color) : color_(color) {} Border::~Border() = default; void Border::OnViewThemeChanged(View* view) {} std::unique_ptr<Border> NullBorder() { return nullptr; } std::unique_ptr<Border> CreateSolidBorder(int thickness, SkColor color) { return std::make_unique<SolidSidedBorder>(gfx::Insets(thickness), color); } std::unique_ptr<Border> CreateThemedSolidBorder(int thickness, ui::ColorId color) { return std::make_unique<ThemedSolidSidedBorder>(gfx::Insets(thickness), color); } std::unique_ptr<Border> CreateEmptyBorder(const gfx::Insets& insets) { return std::make_unique<EmptyBorder>(insets); } std::unique_ptr<Border> CreateEmptyBorder(int thickness) { return CreateEmptyBorder(gfx::Insets(thickness)); } std::unique_ptr<Border> CreateRoundedRectBorder(int thickness, float corner_radius, SkColor color) { return CreateRoundedRectBorder(thickness, corner_radius, gfx::Insets(), color); } std::unique_ptr<Border> CreateRoundedRectBorder(int thickness, float corner_radius, const gfx::Insets& paint_insets, SkColor color) { return std::make_unique<RoundedRectBorder>(thickness, corner_radius, paint_insets, color); } std::unique_ptr<Border> CreateThemedRoundedRectBorder(int thickness, float corner_radius, ui::ColorId color_id) { return CreateThemedRoundedRectBorder(thickness, corner_radius, gfx::Insets(), color_id); } std::unique_ptr<Border> CreateThemedRoundedRectBorder( int thickness, float corner_radius, const gfx::Insets& paint_insets, ui::ColorId color_id) { return std::make_unique<ThemedRoundedRectBorder>(thickness, corner_radius, paint_insets, color_id); } std::unique_ptr<Border> CreateSolidSidedBorder(const gfx::Insets& insets, SkColor color) { return std::make_unique<SolidSidedBorder>(insets, color); } std::unique_ptr<Border> CreateThemedSolidSidedBorder(const gfx::Insets& insets, ui::ColorId color_id) { return std::make_unique<ThemedSolidSidedBorder>(insets, color_id); } std::unique_ptr<Border> CreatePaddedBorder(std::unique_ptr<Border> border, const gfx::Insets& insets) { return std::make_unique<ExtraInsetsBorder>(std::move(border), insets); } std::unique_ptr<Border> CreateBorderPainter(std::unique_ptr<Painter> painter, const gfx::Insets& insets) { return base::WrapUnique(new BorderPainter(std::move(painter), insets)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/border.cc
C++
unknown
11,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. #ifndef UI_VIEWS_BORDER_H_ #define UI_VIEWS_BORDER_H_ #include <memory> #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_id.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/views_export.h" namespace gfx { class Canvas; class Size; } // namespace gfx namespace views { class Painter; class View; //////////////////////////////////////////////////////////////////////////////// // // Border class. // // The border class is used to display a border around a view. // To set a border on a view, call SetBorder on the view, for example: // view->SetBorder( // CreateSolidBorder(1, view->GetColorProvider()->GetColor( // ui::kColorFocusableBorderUnfocused))); // Make sure the border color is updated on theme changes. // Once set on a view, the border is owned by the view. // // IMPORTANT NOTE: not all views support borders at this point. In order to // support the border, views should make sure to use bounds excluding the // border (by calling View::GetLocalBoundsExcludingBorder) when doing layout and // painting. // //////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT Border { public: Border(); explicit Border(SkColor color); Border(const Border&) = delete; Border& operator=(const Border&) = delete; virtual ~Border(); // Renders the border for the specified view. virtual void Paint(const View& view, gfx::Canvas* canvas) = 0; // Returns the border insets. virtual gfx::Insets GetInsets() const = 0; // Returns the minimum size this border requires. Note that this may not be // the same as the insets. For example, a Border may paint images to draw // some graphical border around a view, and this would return the minimum size // such that these images would not be clipped or overlapping -- but the // insets may be larger or smaller, depending on how the view wanted its // content laid out relative to these images. virtual gfx::Size GetMinimumSize() const = 0; // This is called by the View on which it is attached. This is overridden for // subclasses that depend on theme colors. virtual void OnViewThemeChanged(View* view); SkColor color() const { return color_; } // Sets the border color. void set_color(SkColor color) { color_ = color; } private: SkColor color_ = gfx::kPlaceholderColor; }; // Convenience for creating a scoped_ptr with no Border. VIEWS_EXPORT std::unique_ptr<Border> NullBorder(); // Creates a border that is a simple line of the specified thickness and color. VIEWS_EXPORT std::unique_ptr<Border> CreateSolidBorder(int thickness, SkColor color); // Creates a border that is a simple line of the specified thickness and color, // which updates on theme changes. VIEWS_EXPORT std::unique_ptr<Border> CreateThemedSolidBorder(int thickness, ui::ColorId color); // Creates a border that is a rounded rectangle of the specified thickness and // color. // NOTE: `corner_radius` is an OUTER EDGE RADIUS, not a stroke radius! VIEWS_EXPORT std::unique_ptr<Border> CreateRoundedRectBorder(int thickness, float corner_radius, SkColor color); VIEWS_EXPORT std::unique_ptr<Border> CreateRoundedRectBorder( int thickness, float corner_radius, const gfx::Insets& paint_insets, SkColor color); // Same as above except the color updates with theme changes. VIEWS_EXPORT std::unique_ptr<Border> CreateThemedRoundedRectBorder( int thickness, float corner_radius, ui::ColorId color_id); VIEWS_EXPORT std::unique_ptr<Border> CreateThemedRoundedRectBorder( int thickness, float corner_radius, const gfx::Insets& paint_insets, ui::ColorId color_id); // Creates a border for reserving space. The returned border does not paint // anything. VIEWS_EXPORT std::unique_ptr<Border> CreateEmptyBorder( const gfx::Insets& insets); // A simpler version of the above for a border with uniform thickness. VIEWS_EXPORT std::unique_ptr<Border> CreateEmptyBorder(int thickness); // Creates a border of the specified color, and thickness on each side specified // in |insets|. VIEWS_EXPORT std::unique_ptr<Border> CreateSolidSidedBorder( const gfx::Insets& insets, SkColor color); // Creates a border of the specified color with thickness on each side specified // in |insets|. The border updates on theme changes. VIEWS_EXPORT std::unique_ptr<Border> CreateThemedSolidSidedBorder( const gfx::Insets& insets, ui::ColorId color_id); // Creates a new border that draws |border| and adds additional padding. This is // equivalent to changing the insets of |border| without changing how or what it // paints. Example: // // view->SetBorder(CreatePaddedBorder( // CreateSolidBorder(1, view->GetColorProvider()->GetColor( // ui::kColorFocusableBorderUnfocused)), // gfx::Insets::TLBR(2, 0, 0, 0))); // // yields a single dip red border and an additional 2dip of unpainted padding // above the view content (below the border). VIEWS_EXPORT std::unique_ptr<Border> CreatePaddedBorder( std::unique_ptr<Border> border, const gfx::Insets& insets); // Creates a Border from the specified Painter. |insets| define size of an area // allocated for a Border. VIEWS_EXPORT std::unique_ptr<Border> CreateBorderPainter( std::unique_ptr<Painter> painter, const gfx::Insets& insets); } // namespace views #endif // UI_VIEWS_BORDER_H_
Zhao-PengFei35/chromium_src_4
ui/views/border.h
C++
unknown
5,723
// 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/border.h" #include <algorithm> #include <memory> #include <set> #include <utility> #include <vector> #include "base/memory/raw_ptr.h" #include "cc/paint/paint_recorder.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/views/painter.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" namespace { class MockCanvas : public SkCanvas { public: struct DrawRectCall { DrawRectCall(const SkRect& rect, const SkPaint& paint) : rect(rect), paint(paint) {} bool operator<(const DrawRectCall& other) const { return std::tie(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom) < std::tie(other.rect.fLeft, other.rect.fTop, other.rect.fRight, other.rect.fBottom); } SkRect rect; SkPaint paint; }; struct DrawRRectCall { DrawRRectCall(const SkRRect& rrect, const SkPaint& paint) : rrect(rrect), paint(paint) {} bool operator<(const DrawRRectCall& other) const { SkRect rect = rrect.rect(); SkRect other_rect = other.rrect.rect(); return std::tie(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom) < std::tie(other_rect.fLeft, other_rect.fTop, other_rect.fRight, other_rect.fBottom); } SkRRect rrect; SkPaint paint; }; MockCanvas(int width, int height) : SkCanvas(width, height) {} MockCanvas(const MockCanvas&) = delete; MockCanvas& operator=(const MockCanvas&) = delete; // Return calls in sorted order. std::vector<DrawRectCall> draw_rect_calls() { return std::vector<DrawRectCall>(draw_rect_calls_.begin(), draw_rect_calls_.end()); } // Return calls in sorted order. std::vector<DrawRRectCall> draw_rrect_calls() { return std::vector<DrawRRectCall>(draw_rrect_calls_.begin(), draw_rrect_calls_.end()); } const std::vector<SkPaint>& draw_paint_calls() const { return draw_paint_calls_; } const SkRect& last_clip_bounds() const { return last_clip_bounds_; } // SkCanvas overrides: void onDrawRect(const SkRect& rect, const SkPaint& paint) override { draw_rect_calls_.insert(DrawRectCall(rect, paint)); } void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override { draw_rrect_calls_.insert(DrawRRectCall(rrect, paint)); } void onDrawPaint(const SkPaint& paint) override { draw_paint_calls_.push_back(paint); } void onClipRect(const SkRect& rect, SkClipOp op, ClipEdgeStyle edge_style) override { last_clip_bounds_ = rect; } private: // Stores all the calls for querying by the test, in sorted order. std::set<DrawRectCall> draw_rect_calls_; std::set<DrawRRectCall> draw_rrect_calls_; // Stores the onDrawPaint calls in chronological order. std::vector<SkPaint> draw_paint_calls_; SkRect last_clip_bounds_; }; // Simple Painter that will be used to test BorderPainter. class MockPainter : public views::Painter { public: MockPainter() = default; MockPainter(const MockPainter&) = delete; MockPainter& operator=(const MockPainter&) = delete; // Gets the canvas given to the last call to Paint(). gfx::Canvas* given_canvas() const { return given_canvas_; } // Gets the size given to the last call to Paint(). const gfx::Size& given_size() const { return given_size_; } // Painter overrides: gfx::Size GetMinimumSize() const override { // Just return some arbitrary size. return gfx::Size(60, 40); } void Paint(gfx::Canvas* canvas, const gfx::Size& size) override { // Just record the arguments. given_canvas_ = canvas; given_size_ = size; } private: raw_ptr<gfx::Canvas> given_canvas_ = nullptr; gfx::Size given_size_; }; } // namespace namespace views { class BorderTest : public ViewsTestBase { public: enum { // The canvas should be much bigger than the view. kCanvasWidth = 1000, kCanvasHeight = 500, }; void SetUp() override { ViewsTestBase::SetUp(); view_ = std::make_unique<views::View>(); view_->SetSize(gfx::Size(100, 50)); recorder_ = std::make_unique<cc::PaintRecorder>(); canvas_ = std::make_unique<gfx::Canvas>(recorder_->beginRecording(), 1.0f); } void TearDown() override { ViewsTestBase::TearDown(); canvas_.reset(); recorder_.reset(); view_.reset(); } std::unique_ptr<MockCanvas> DrawIntoMockCanvas() { cc::PaintRecord record = recorder_->finishRecordingAsPicture(); std::unique_ptr<MockCanvas> mock( new MockCanvas(kCanvasWidth, kCanvasHeight)); record.Playback(mock.get()); return mock; } protected: std::unique_ptr<cc::PaintRecorder> recorder_; std::unique_ptr<views::View> view_; std::unique_ptr<gfx::Canvas> canvas_; }; TEST_F(BorderTest, NullBorder) { std::unique_ptr<Border> border(NullBorder()); EXPECT_FALSE(border); } TEST_F(BorderTest, SolidBorder) { const SkColor kBorderColor = SK_ColorMAGENTA; std::unique_ptr<Border> border(CreateSolidBorder(3, kBorderColor)); EXPECT_EQ(gfx::Size(6, 6), border->GetMinimumSize()); EXPECT_EQ(gfx::Insets(3), border->GetInsets()); border->Paint(*view_, canvas_.get()); std::unique_ptr<MockCanvas> mock = DrawIntoMockCanvas(); std::vector<MockCanvas::DrawRectCall> draw_rect_calls = mock->draw_rect_calls(); gfx::Rect bounds = view_->GetLocalBounds(); bounds.Inset(border->GetInsets()); ASSERT_EQ(1u, mock->draw_paint_calls().size()); EXPECT_EQ(kBorderColor, mock->draw_paint_calls()[0].getColor()); EXPECT_EQ(gfx::RectF(bounds), gfx::SkRectToRectF(mock->last_clip_bounds())); } TEST_F(BorderTest, RoundedRectBorder) { std::unique_ptr<Border> border(CreateRoundedRectBorder( 3, LayoutProvider::Get()->GetCornerRadiusMetric(Emphasis::kLow), SK_ColorBLUE)); EXPECT_EQ(gfx::Size(6, 6), border->GetMinimumSize()); EXPECT_EQ(gfx::Insets(3), border->GetInsets()); border->Paint(*view_, canvas_.get()); std::unique_ptr<MockCanvas> mock = DrawIntoMockCanvas(); SkRRect expected_rrect; expected_rrect.setRectXY(SkRect::MakeLTRB(1.5, 1.5, 98.5, 48.5), 2.5, 2.5); EXPECT_TRUE(mock->draw_rect_calls().empty()); std::vector<MockCanvas::DrawRRectCall> draw_rrect_calls = mock->draw_rrect_calls(); ASSERT_EQ(1u, draw_rrect_calls.size()); EXPECT_EQ(expected_rrect, draw_rrect_calls[0].rrect); EXPECT_EQ(3, draw_rrect_calls[0].paint.getStrokeWidth()); EXPECT_EQ(SK_ColorBLUE, draw_rrect_calls[0].paint.getColor()); EXPECT_EQ(SkPaint::kStroke_Style, draw_rrect_calls[0].paint.getStyle()); EXPECT_TRUE(draw_rrect_calls[0].paint.isAntiAlias()); } TEST_F(BorderTest, EmptyBorder) { constexpr auto kInsets = gfx::Insets::TLBR(1, 2, 3, 4); std::unique_ptr<Border> border(CreateEmptyBorder(kInsets)); // The EmptyBorder has no minimum size despite nonzero insets. EXPECT_EQ(gfx::Size(), border->GetMinimumSize()); EXPECT_EQ(kInsets, border->GetInsets()); // Should have no effect. border->Paint(*view_, canvas_.get()); std::unique_ptr<Border> border2(CreateEmptyBorder(kInsets)); EXPECT_EQ(kInsets, border2->GetInsets()); } TEST_F(BorderTest, SolidSidedBorder) { constexpr SkColor kBorderColor = SK_ColorMAGENTA; constexpr auto kInsets = gfx::Insets::TLBR(1, 2, 3, 4); std::unique_ptr<Border> border(CreateSolidSidedBorder(kInsets, kBorderColor)); EXPECT_EQ(gfx::Size(6, 4), border->GetMinimumSize()); EXPECT_EQ(kInsets, border->GetInsets()); border->Paint(*view_, canvas_.get()); std::unique_ptr<MockCanvas> mock = DrawIntoMockCanvas(); std::vector<MockCanvas::DrawRectCall> draw_rect_calls = mock->draw_rect_calls(); gfx::Rect bounds = view_->GetLocalBounds(); bounds.Inset(border->GetInsets()); ASSERT_EQ(1u, mock->draw_paint_calls().size()); EXPECT_EQ(kBorderColor, mock->draw_paint_calls().front().getColor()); EXPECT_EQ(gfx::RectF(bounds), gfx::SkRectToRectF(mock->last_clip_bounds())); } TEST_F(BorderTest, BorderPainter) { constexpr auto kInsets = gfx::Insets::TLBR(1, 2, 3, 4); std::unique_ptr<MockPainter> painter(new MockPainter()); MockPainter* painter_ptr = painter.get(); std::unique_ptr<Border> border( CreateBorderPainter(std::move(painter), kInsets)); EXPECT_EQ(gfx::Size(60, 40), border->GetMinimumSize()); EXPECT_EQ(kInsets, border->GetInsets()); border->Paint(*view_, canvas_.get()); // Expect that the Painter was called with our canvas and the view's size. EXPECT_EQ(canvas_.get(), painter_ptr->given_canvas()); EXPECT_EQ(view_->size(), painter_ptr->given_size()); } TEST_F(BorderTest, ExtraInsetsBorder) { constexpr SkColor kBorderColor = SK_ColorMAGENTA; constexpr int kOriginalInset = 3; std::unique_ptr<Border> border = CreateSolidBorder(kOriginalInset, kBorderColor); constexpr gfx::Insets kOriginalInsets(kOriginalInset); EXPECT_EQ(kOriginalInsets.size(), border->GetMinimumSize()); EXPECT_EQ(kOriginalInsets, border->GetInsets()); EXPECT_EQ(kBorderColor, border->color()); constexpr int kExtraInset = 2; constexpr gfx::Insets kExtraInsets(kExtraInset); std::unique_ptr<Border> extra_insets_border = CreatePaddedBorder(std::move(border), kExtraInsets); constexpr gfx::Insets kTotalInsets(kOriginalInset + kExtraInset); EXPECT_EQ(kTotalInsets.size(), extra_insets_border->GetMinimumSize()); EXPECT_EQ(kTotalInsets, extra_insets_border->GetInsets()); EXPECT_EQ(kBorderColor, extra_insets_border->color()); extra_insets_border->Paint(*view_, canvas_.get()); std::unique_ptr<MockCanvas> mock = DrawIntoMockCanvas(); std::vector<MockCanvas::DrawRectCall> draw_rect_calls = mock->draw_rect_calls(); gfx::Rect bounds = view_->GetLocalBounds(); // We only use the wrapped border's insets for painting the border. The extra // insets of the ExtraInsetsBorder are applied within the wrapped border. bounds.Inset(extra_insets_border->GetInsets() - gfx::Insets(kExtraInset)); ASSERT_EQ(1u, mock->draw_paint_calls().size()); EXPECT_EQ(kBorderColor, mock->draw_paint_calls().front().getColor()); EXPECT_EQ(gfx::RectF(bounds), gfx::SkRectToRectF(mock->last_clip_bounds())); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/border_unittest.cc
C++
unknown
10,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. #include "ui/views/bubble/bubble_border.h" #include <algorithm> #include <map> #include <tuple> #include <utility> #include "base/check_op.h" #include "base/logging.h" #include "base/no_destructor.h" #include "base/notreached.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkBlendMode.h" #include "third_party/skia/include/core/SkClipOp.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkScalar.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/geometry/rect.h" #include "ui/gfx/geometry/rrect_f.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/scoped_canvas.h" #include "ui/gfx/shadow_value.h" #include "ui/gfx/skia_paint_util.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/bubble/bubble_border_arrow_utils.h" #include "ui/views/view.h" namespace views { namespace { // GetShadowValues and GetBorderAndShadowFlags cache their results. The shadow // values depend on the shadow elevation, color and shadow type, so we create a // tuple to key the cache. using ShadowCacheKey = std::tuple<int, SkColor, BubbleBorder::Shadow>; SkColor GetKeyShadowColor(int elevation, const ui::ColorProvider* color_provider) { switch (elevation) { case 3: { return color_provider->GetColor( ui::kColorShadowValueKeyShadowElevationThree); } case 16: { return color_provider->GetColor( ui::kColorShadowValueKeyShadowElevationSixteen); } default: // This surface has not been updated for Refresh. Fall back to the // deprecated style. return color_provider->GetColor(ui::kColorShadowBase); } } SkColor GetAmbientShadowColor(int elevation, const ui::ColorProvider* color_provider) { switch (elevation) { case 3: { return color_provider->GetColor( ui::kColorShadowValueAmbientShadowElevationThree); } case 16: { return color_provider->GetColor( ui::kColorShadowValueAmbientShadowElevationSixteen); } default: // This surface has not been updated for Refresh. Fall back to the // deprecated style. return color_provider->GetColor(ui::kColorShadowBase); } } enum BubbleArrowPart { kFill, kBorder }; SkPath GetVisibleArrowPath(BubbleBorder::Arrow arrow, const gfx::Rect& bounds, BubbleArrowPart part) { constexpr size_t kNumPoints = 4; gfx::RectF bounds_f(bounds); SkPoint points[kNumPoints]; switch (GetBubbleArrowSide(arrow)) { case BubbleArrowSide::kRight: points[0] = {bounds_f.x(), bounds_f.y()}; points[1] = {bounds_f.right(), bounds_f.y() + BubbleBorder::kVisibleArrowRadius - 1}; points[2] = {bounds_f.right(), bounds_f.y() + BubbleBorder::kVisibleArrowRadius}; points[3] = {bounds_f.x(), bounds_f.bottom() - 1}; break; case BubbleArrowSide::kLeft: points[0] = {bounds_f.right(), bounds_f.bottom() - 1}; points[1] = {bounds_f.x(), bounds_f.y() + BubbleBorder::kVisibleArrowRadius}; points[2] = {bounds_f.x(), bounds_f.y() + BubbleBorder::kVisibleArrowRadius - 1}; points[3] = {bounds_f.right(), bounds_f.y()}; break; case BubbleArrowSide::kTop: points[0] = {bounds_f.x(), bounds_f.bottom()}; points[1] = {bounds_f.x() + BubbleBorder::kVisibleArrowRadius - 1, bounds_f.y()}; points[2] = {bounds_f.x() + BubbleBorder::kVisibleArrowRadius, bounds_f.y()}; points[3] = {bounds_f.right() - 1, bounds_f.bottom()}; break; case BubbleArrowSide::kBottom: points[0] = {bounds_f.right() - 1, bounds_f.y()}; points[1] = {bounds_f.x() + BubbleBorder::kVisibleArrowRadius, bounds_f.bottom()}; points[2] = {bounds_f.x() + BubbleBorder::kVisibleArrowRadius - 1, bounds_f.bottom()}; points[3] = {bounds_f.x(), bounds_f.y()}; break; } return SkPath::Polygon(points, kNumPoints, part == BubbleArrowPart::kFill); } const gfx::ShadowValues& GetShadowValues( const ui::ColorProvider* color_provider, absl::optional<int> elevation, BubbleBorder::Shadow shadow_type) { // If the color provider does not exist the shadow values are being created in // order to calculate Insets. In that case the color plays no role so always // set those colors to gfx::kPlaceholderColor. SkColor color = color_provider ? color_provider->GetColor(ui::kColorShadowBase) : gfx::kPlaceholderColor; // The shadows are always the same for any elevation and color combination, so // construct them once and cache. static base::NoDestructor<std::map<ShadowCacheKey, gfx::ShadowValues>> shadow_map; ShadowCacheKey key(elevation.value_or(-1), color, shadow_type); if (shadow_map->find(key) != shadow_map->end()) return shadow_map->find(key)->second; gfx::ShadowValues shadows; if (elevation.has_value()) { DCHECK_GE(elevation.value(), 0); SkColor key_shadow_color = color_provider ? GetKeyShadowColor(elevation.value(), color_provider) : gfx::kPlaceholderColor; SkColor ambient_shadow_color = color_provider ? GetAmbientShadowColor(elevation.value(), color_provider) : gfx::kPlaceholderColor; shadows = gfx::ShadowValue::MakeShadowValues( elevation.value(), key_shadow_color, ambient_shadow_color); #if BUILDFLAG(IS_CHROMEOS_ASH) if (shadow_type == BubbleBorder::CHROMEOS_SYSTEM_UI_SHADOW) { shadows = gfx::ShadowValue::MakeChromeOSSystemUIShadowValues( elevation.value(), key_shadow_color); } #endif } else { constexpr int kSmallShadowVerticalOffset = 2; constexpr int kSmallShadowBlur = 4; SkColor kSmallShadowColor = color_provider ? color_provider->GetColor(ui::kColorBubbleBorderShadowSmall) : gfx::kPlaceholderColor; SkColor kLargeShadowColor = color_provider ? color_provider->GetColor(ui::kColorBubbleBorderShadowLarge) : gfx::kPlaceholderColor; // gfx::ShadowValue counts blur pixels both inside and outside the shape, // whereas these blur values only describe the outside portion, hence they // must be doubled. shadows = gfx::ShadowValues({ {gfx::Vector2d(0, kSmallShadowVerticalOffset), 2 * kSmallShadowBlur, kSmallShadowColor}, {gfx::Vector2d(0, BubbleBorder::kShadowVerticalOffset), 2 * BubbleBorder::kShadowBlur, kLargeShadowColor}, }); } shadow_map->insert({key, shadows}); return shadow_map->find(key)->second; } const cc::PaintFlags& GetBorderAndShadowFlags( const ui::ColorProvider* color_provider, absl::optional<int> elevation, BubbleBorder::Shadow shadow_type) { // The flags are always the same for any elevation and color combination, so // construct them once and cache. static base::NoDestructor<std::map<ShadowCacheKey, cc::PaintFlags>> flag_map; ShadowCacheKey key(elevation.value_or(-1), color_provider->GetColor(ui::kColorShadowBase), shadow_type); if (flag_map->find(key) != flag_map->end()) return flag_map->find(key)->second; cc::PaintFlags flags; flags.setColor( color_provider->GetColor(ui::kColorBubbleBorderWhenShadowPresent)); flags.setAntiAlias(true); flags.setLooper(gfx::CreateShadowDrawLooper( GetShadowValues(color_provider, elevation, shadow_type))); flag_map->insert({key, flags}); return flag_map->find(key)->second; } template <typename T> void DrawBorderAndShadowImpl( T rect, void (cc::PaintCanvas::*draw)(const T&, const cc::PaintFlags&), gfx::Canvas* canvas, const ui::ColorProvider* color_provider, absl::optional<int> shadow_elevation = absl::nullopt, BubbleBorder::Shadow shadow_type = BubbleBorder::STANDARD_SHADOW) { // Borders with custom shadow elevations do not draw the 1px border. if (!shadow_elevation.has_value()) { // Provide a 1 px border outside the bounds. constexpr int kBorderStrokeThicknessPx = 1; const SkScalar one_pixel = SkFloatToScalar(kBorderStrokeThicknessPx / canvas->image_scale()); rect.outset(one_pixel, one_pixel); } (canvas->sk_canvas()->*draw)( rect, GetBorderAndShadowFlags(color_provider, shadow_elevation, shadow_type)); } } // namespace constexpr int BubbleBorder::kBorderThicknessDip; constexpr int BubbleBorder::kShadowBlur; constexpr int BubbleBorder::kShadowVerticalOffset; constexpr int BubbleBorder::kVisibleArrowGap; constexpr int BubbleBorder::kVisibleArrowLength; constexpr int BubbleBorder::kVisibleArrowRadius; constexpr int BubbleBorder::kVisibleArrowBuffer; BubbleBorder::BubbleBorder(Arrow arrow, Shadow shadow, ui::ColorId color_id) : arrow_(arrow), shadow_(shadow), color_id_(color_id) { DCHECK_LT(shadow_, SHADOW_COUNT); } BubbleBorder::~BubbleBorder() = default; // static gfx::Insets BubbleBorder::GetBorderAndShadowInsets( absl::optional<int> elevation, BubbleBorder::Shadow shadow_type) { // Borders with custom shadow elevations do not draw the 1px border. if (elevation.has_value()) return -gfx::ShadowValue::GetMargin( GetShadowValues(nullptr, elevation, shadow_type)); constexpr gfx::Insets blur(kShadowBlur + kBorderThicknessDip); constexpr auto offset = gfx::Insets::TLBR(-kShadowVerticalOffset, 0, kShadowVerticalOffset, 0); return blur + offset; } void BubbleBorder::SetCornerRadius(int corner_radius) { corner_radius_ = corner_radius; } void BubbleBorder::SetRoundedCorners(int top_left, int top_right, int bottom_right, int bottom_left) { radii_[0].iset(top_left, top_left); radii_[1].iset(top_right, top_right); radii_[2].iset(bottom_right, bottom_right); radii_[3].iset(bottom_left, bottom_left); } void BubbleBorder::SetColor(SkColor color) { requested_color_ = color; UpdateColor(nullptr); } gfx::Rect BubbleBorder::GetBounds(const gfx::Rect& anchor_rect, const gfx::Size& contents_size) const { const gfx::Size size(GetSizeForContentsSize(contents_size)); // In floating mode, the bounds of the bubble border and the |anchor_rect| // have coinciding central points. if (arrow_ == FLOAT) { gfx::Rect rect(anchor_rect.CenterPoint(), size); rect.Offset(gfx::Vector2d(-size.width() / 2, -size.height() / 2)); return rect; } // If no arrow is used, in the vertical direction, the bubble is placed below // the |anchor_rect| while they have coinciding horizontal centers. if (arrow_ == NONE) { gfx::Rect rect(anchor_rect.bottom_center(), size); rect.Offset(gfx::Vector2d(-size.width() / 2, 0)); return rect; } // In all other cases, the used arrow determines the placement of the bubble // with respect to the |anchor_rect|. gfx::Rect contents_bounds(contents_size); // Always apply the border part of the inset before calculating coordinates, // that ensures the bubble's border is aligned with the anchor's border. // For the purposes of positioning, the border is rounded up to a dip, which // may cause misalignment in scale factors greater than 1. // TODO(estade): when it becomes possible to provide px bounds instead of // dip bounds, fix this. // Borders with custom shadow elevations do not draw the 1px border. const gfx::Insets border_insets = shadow_ == NO_SHADOW || md_shadow_elevation_.has_value() ? gfx::Insets() : gfx::Insets(kBorderThicknessDip); const gfx::Insets insets = GetInsets(); const gfx::Insets shadow_insets = insets - border_insets; // TODO(dfried): Collapse border into visible arrow where applicable. contents_bounds.Inset(-border_insets); DCHECK(!avoid_shadow_overlap_ || !visible_arrow_); // If |avoid_shadow_overlap_| is true, the shadow part of the inset is also // applied now, to ensure that the shadow itself doesn't overlap the anchor. if (avoid_shadow_overlap_) contents_bounds.Inset(-shadow_insets); // Adjust the contents to align with the arrow. The `anchor_point` is the // point on `anchor_rect` to offset from; it is also used as part of the // visible arrow calculation if present. gfx::Point anchor_point = GetArrowAnchorPointFromAnchorRect(arrow_, anchor_rect); contents_bounds += GetContentBoundsOffsetToArrowAnchorPoint( contents_bounds, arrow_, anchor_point); // With NO_SHADOW, there should be further insets, but the same logic is // used to position the bubble origin according to |anchor_rect|. DCHECK(shadow_ != NO_SHADOW || insets_.has_value() || shadow_insets.IsEmpty() || visible_arrow_); if (!avoid_shadow_overlap_) contents_bounds.Inset(-shadow_insets); // |arrow_offset_| is used to adjust bubbles that would normally be // partially offscreen. if (is_arrow_on_horizontal(arrow_)) contents_bounds += gfx::Vector2d(-arrow_offset_, 0); else contents_bounds += gfx::Vector2d(0, -arrow_offset_); // If no visible arrow is shown, return the content bounds. if (!visible_arrow_) return contents_bounds; // Finally, get the needed movement vector of |contents_bounds| to create the // space needed to place the visible arrow. adjustments because we don't want // the positioning to be altered. Offset by the size of the arrow's inset on // each side (only one side will be nonzero) to create space for the visible // arrow. contents_bounds += GetContentsBoundsOffsetToPlaceVisibleArrow(arrow_, /*include_gap=*/true); // We have an anchor point which is appropriate for the arrow type, but // when anchoring to a small view it looks better to track from the middle // of the view rather than a corner. We may still adjust this point if // it's too close to the edge of the bubble (in this case by adjusting the // bubble by a few pixels rather than the anchor point). const gfx::Point anchor_center = anchor_rect.CenterPoint(); const gfx::Point contents_center = contents_bounds.CenterPoint(); if (IsVerticalArrow(arrow_)) { const int right_bound = contents_bounds.right() - (kVisibleArrowBuffer + kVisibleArrowRadius + shadow_insets.right()); const int left_bound = contents_bounds.x() + kVisibleArrowBuffer + kVisibleArrowRadius + shadow_insets.left(); if (anchor_point.x() > anchor_center.x() && anchor_center.x() > contents_center.x()) { anchor_point.set_x(anchor_center.x()); } else if (anchor_point.x() > right_bound) { anchor_point.set_x(std::max(anchor_rect.x(), right_bound)); } else if (anchor_point.x() < anchor_center.x() && anchor_center.x() < contents_center.x()) { anchor_point.set_x(anchor_center.x()); } else if (anchor_point.x() < left_bound) { anchor_point.set_x(std::min(anchor_rect.right(), left_bound)); } if (anchor_point.x() < left_bound) { contents_bounds -= gfx::Vector2d(left_bound - anchor_point.x(), 0); } else if (anchor_point.x() > right_bound) { contents_bounds += gfx::Vector2d(anchor_point.x() - right_bound, 0); } } else { const int bottom_bound = contents_bounds.bottom() - (kVisibleArrowBuffer + kVisibleArrowRadius + shadow_insets.bottom()); const int top_bound = contents_bounds.y() + kVisibleArrowBuffer + kVisibleArrowRadius + shadow_insets.top(); if (anchor_point.y() > anchor_center.y() && anchor_center.y() > contents_center.y()) { anchor_point.set_y(anchor_center.y()); } else if (anchor_point.y() > bottom_bound) { anchor_point.set_y(std::max(anchor_rect.y(), bottom_bound)); } else if (anchor_point.y() < anchor_center.y() && anchor_center.y() < contents_center.y()) { anchor_point.set_y(anchor_center.y()); } else if (anchor_point.y() < top_bound) { anchor_point.set_y(std::min(anchor_rect.bottom(), top_bound)); } if (anchor_point.y() < top_bound) { contents_bounds -= gfx::Vector2d(0, top_bound - anchor_point.y()); } else if (anchor_point.y() > bottom_bound) { contents_bounds += gfx::Vector2d(0, anchor_point.y() - bottom_bound); } } CalculateVisibleArrowRect(contents_bounds, anchor_point); return contents_bounds; } // static gfx::Vector2d BubbleBorder::GetContentsBoundsOffsetToPlaceVisibleArrow( BubbleBorder::Arrow arrow, bool include_gap) { DCHECK(has_arrow(arrow)); const gfx::Insets visible_arrow_insets = GetVisibleArrowInsets(arrow, include_gap); return gfx::Vector2d( visible_arrow_insets.left() - visible_arrow_insets.right(), visible_arrow_insets.top() - visible_arrow_insets.bottom()); } void BubbleBorder::Paint(const views::View& view, gfx::Canvas* canvas) { if (shadow_ == NO_SHADOW) { PaintNoShadow(view, canvas); return; } gfx::ScopedCanvas scoped(canvas); SkRRect r_rect = GetClientRect(view); canvas->sk_canvas()->clipRRect(r_rect, SkClipOp::kDifference, true /*doAntiAlias*/); DrawBorderAndShadowImpl(r_rect, &cc::PaintCanvas::drawRRect, canvas, view.GetColorProvider(), md_shadow_elevation_, shadow_); if (visible_arrow_) PaintVisibleArrow(view, canvas); } // static void BubbleBorder::DrawBorderAndShadow( SkRect rect, gfx::Canvas* canvas, const ui::ColorProvider* color_provider) { DrawBorderAndShadowImpl(rect, &cc::PaintCanvas::drawRect, canvas, color_provider); } gfx::Insets BubbleBorder::GetInsets() const { // Visible arrow is not compatible with OS-drawn shadow or with manual insets. DCHECK((!insets_ && shadow_ != NO_SHADOW) || !visible_arrow_); if (insets_.has_value()) { return insets_.value(); } gfx::Insets insets; switch (shadow_) { case STANDARD_SHADOW: #if BUILDFLAG(IS_CHROMEOS_ASH) case CHROMEOS_SYSTEM_UI_SHADOW: #endif insets = GetBorderAndShadowInsets(md_shadow_elevation_, shadow_); break; default: break; } if (visible_arrow_) { const gfx::Insets arrow_insets = GetVisibleArrowInsets(arrow_, false); insets = gfx::Insets::TLBR(std::max(insets.top(), arrow_insets.top()), std::max(insets.left(), arrow_insets.left()), std::max(insets.bottom(), arrow_insets.bottom()), std::max(insets.right(), arrow_insets.right())); } return insets; } gfx::Size BubbleBorder::GetMinimumSize() const { return GetSizeForContentsSize(gfx::Size()); } void BubbleBorder::OnViewThemeChanged(View* view) { UpdateColor(view); } gfx::Size BubbleBorder::GetSizeForContentsSize( const gfx::Size& contents_size) const { // Enlarge the contents size by the thickness of the border images. gfx::Size size(contents_size); const gfx::Insets insets = GetInsets(); size.Enlarge(insets.width(), insets.height()); return size; } bool BubbleBorder::AddArrowToBubbleCornerAndPointTowardsAnchor( const gfx::Rect& anchor_rect, gfx::Rect& popup_bounds) { // This function should only be called for a visible arrow. DCHECK(arrow_ != Arrow::NONE && arrow_ != Arrow::FLOAT); // The total size of the arrow in its normal direction. const int kVisibleArrowDiamater = 2 * kVisibleArrowRadius; // To store the resulting x and y position of the arrow. int x_position, y_position; // The definition of an vertical arrow is inconsistent. if (IsVerticalArrow(arrow_)) { // The optimal x position depends on the |arrow_|. // For a center-aligned arrow, the optimal position of the arrow points // towards the center of the element. If the arrow is right-aligned, it // points towards the right edge of the element, and to the left otherwise. int x_optimal_position = (int{arrow_} & ArrowMask::CENTER) ? anchor_rect.CenterPoint().x() - kVisibleArrowRadius : ((int{arrow_} & ArrowMask::RIGHT) ? anchor_rect.right() - kVisibleArrowDiamater : anchor_rect.x()); // The most left position for the arrow is the left edge of the bubble // plus the minimum spacing of the arrow from the edge. int leftmost_position_on_bubble = popup_bounds.x() + kVisibleArrowBuffer; // Analogous, the most right position is the right side minus the diameter // of the arrow and the spacing of the arrow from the edge. int rightmost_position_on_bubble = popup_bounds.right() - kVisibleArrowDiamater - kVisibleArrowBuffer; // If the right-most position is smaller than the left-most position, the // bubble's width is not sufficient to add an arrow. if (leftmost_position_on_bubble > rightmost_position_on_bubble) { // Make the arrow invisible because there is not enough space to show it. set_visible_arrow(false); return false; } // Make sure the x position is limited to the range defined by the bubble. x_position = std::clamp(x_optimal_position, leftmost_position_on_bubble, rightmost_position_on_bubble); // Calculate the y position of the arrow to be either on top of below the // bubble. y_position = (int{arrow_} & ArrowMask::BOTTOM) ? popup_bounds.bottom() : popup_bounds.y() - kVisibleArrowLength; } else { // Adjust y position of the popup to keep the arrow pointing exactly in // the middle of the anchor element, still respecting // the |kVisibleArrowBuffer| restrictions. int popup_y_upper_bound = anchor_rect.CenterPoint().y() - (kVisibleArrowRadius + kVisibleArrowBuffer); int popup_y_lower_bound = anchor_rect.CenterPoint().y() + (kVisibleArrowRadius + kVisibleArrowBuffer) - popup_bounds.height(); // The popup height is not enough to accommodate the arrow. if (popup_y_upper_bound < popup_y_lower_bound) { set_visible_arrow(false); return false; } int popup_y_adjusted = std::clamp(popup_bounds.y(), popup_y_lower_bound, popup_y_upper_bound); popup_bounds.set_y(popup_y_adjusted); // For an horizontal arrow, the x position is either the left or the right // edge of the bubble, taking the length of the arrow into account. x_position = (int{arrow_} & ArrowMask::RIGHT) ? popup_bounds.right() : popup_bounds.x() - kVisibleArrowLength; // Calculate the top- and bottom-most position for the bubble. int topmost_position_on_bubble = popup_bounds.y() + kVisibleArrowBuffer; int bottommost_position_on_bubble = popup_bounds.bottom() - kVisibleArrowDiamater - kVisibleArrowBuffer; // If the top-most position is below the bottom-most position, the bubble // has not enough height to place an arrow. if (topmost_position_on_bubble > bottommost_position_on_bubble) { // Make the arrow invisible because there is not enough space to show it. set_visible_arrow(false); return false; } // Align the arrow with the horizontal center of the element. // Here, there is no differentiation between the different positions of a // left or right aligned arrow. y_position = std::clamp(anchor_rect.CenterPoint().y() - kVisibleArrowRadius, topmost_position_on_bubble, bottommost_position_on_bubble); } visible_arrow_rect_.set_size(GetVisibleArrowSize(arrow_)); visible_arrow_rect_.set_origin({x_position, y_position}); // The arrow is positioned around the popup, but the popup is still in its // original position and the arrow may overlap the anchor element. To make // the whole tandem visually pointing to the anchor it must be shifted // in the opposite direction. gfx::Vector2d popup_offset = GetContentsBoundsOffsetToPlaceVisibleArrow(arrow_, false); popup_bounds.set_origin(popup_bounds.origin() + popup_offset); visible_arrow_rect_.set_origin(visible_arrow_rect_.origin() + popup_offset); set_visible_arrow(true); return true; } void BubbleBorder::CalculateVisibleArrowRect( const gfx::Rect& contents_bounds, const gfx::Point& anchor_point) const { const gfx::Insets insets = GetInsets(); gfx::Point new_origin; switch (GetBubbleArrowSide(arrow_)) { case BubbleArrowSide::kTop: new_origin = gfx::Point(anchor_point.x() - kVisibleArrowRadius + 1, contents_bounds.y() + insets.top() - kVisibleArrowLength); break; case BubbleArrowSide::kBottom: new_origin = gfx::Point(anchor_point.x() - kVisibleArrowRadius + 1, contents_bounds.bottom() - insets.bottom()); break; case BubbleArrowSide::kRight: new_origin = gfx::Point(contents_bounds.right() - insets.right(), anchor_point.y() - kVisibleArrowRadius + 1); break; case BubbleArrowSide::kLeft: new_origin = gfx::Point(contents_bounds.x() + insets.left() - kVisibleArrowLength, anchor_point.y() - kVisibleArrowRadius + 1); break; } visible_arrow_rect_.set_origin(new_origin); visible_arrow_rect_.set_size(GetVisibleArrowSize(arrow_)); } SkRRect BubbleBorder::GetClientRect(const View& view) const { gfx::RectF bounds(view.GetLocalBounds()); bounds.Inset(gfx::InsetsF(GetInsets())); SkRRect r_rect = SkRRect::MakeRectXY(gfx::RectFToSkRect(bounds), corner_radius(), corner_radius()); if (!radii_[0].isZero() || !radii_[1].isZero() || !radii_[2].isZero() || !radii_[3].isZero()) { r_rect.setRectRadii(gfx::RectFToSkRect(bounds), radii_); } return r_rect; } void BubbleBorder::UpdateColor(View* view) { const SkColor computed_color = view ? view->GetColorProvider()->GetColor(color_id_) : gfx::kPlaceholderColor; color_ = requested_color_.value_or(computed_color); if (view) view->SchedulePaint(); } void BubbleBorder::PaintNoShadow(const View& view, gfx::Canvas* canvas) { gfx::ScopedCanvas scoped(canvas); canvas->sk_canvas()->clipRRect(GetClientRect(view), SkClipOp::kDifference, true /*doAntiAlias*/); canvas->sk_canvas()->drawColor(SkColors::kTransparent, SkBlendMode::kSrc); } void BubbleBorder::PaintVisibleArrow(const View& view, gfx::Canvas* canvas) { gfx::Point arrow_origin = visible_arrow_rect_.origin(); View::ConvertPointFromScreen(&view, &arrow_origin); const gfx::Rect arrow_bounds(arrow_origin, visible_arrow_rect_.size()); // Clip the canvas to a box that's big enough to hold the shadow in every // dimension but won't overlap the bubble itself. gfx::ScopedCanvas scoped(canvas); gfx::Rect clip_rect = arrow_bounds; const BubbleArrowSide side = GetBubbleArrowSide(arrow_); clip_rect.Inset(gfx::Insets::TLBR(side == BubbleArrowSide::kBottom ? 0 : -2, side == BubbleArrowSide::kRight ? 0 : -2, side == BubbleArrowSide::kTop ? 0 : -2, side == BubbleArrowSide::kLeft ? 0 : -2)); canvas->ClipRect(clip_rect); cc::PaintFlags flags; flags.setStrokeCap(cc::PaintFlags::kRound_Cap); flags.setColor(view.GetColorProvider()->GetColor( ui::kColorBubbleBorderWhenShadowPresent)); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(1.2); flags.setAntiAlias(true); canvas->DrawPath( GetVisibleArrowPath(arrow_, arrow_bounds, BubbleArrowPart::kBorder), flags); flags.setColor(color()); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setStrokeWidth(1.0); flags.setAntiAlias(true); canvas->DrawPath( GetVisibleArrowPath(arrow_, arrow_bounds, BubbleArrowPart::kFill), flags); } void BubbleBackground::Paint(gfx::Canvas* canvas, views::View* view) const { // Fill the contents with a round-rect region to match the border images. cc::PaintFlags flags; flags.setAntiAlias(true); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(border_->color()); gfx::RectF bounds(view->GetLocalBounds()); bounds.Inset(gfx::InsetsF(border_->GetInsets())); canvas->DrawRoundRect(bounds, border_->corner_radius(), flags); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_border.cc
C++
unknown
29,114
// 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_BUBBLE_BUBBLE_BORDER_H_ #define UI_VIEWS_BUBBLE_BUBBLE_BORDER_H_ #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkRRect.h" #include "ui/color/color_id.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/views_export.h" class SkRRect; struct SkRect; namespace gfx { class Canvas; } namespace ui { class ColorProvider; } namespace views { // Renders a border, with optional arrow, and a custom dropshadow. // This can be used to produce floating "bubble" objects with rounded corners. class VIEWS_EXPORT BubbleBorder : public Border { public: // Possible locations for the (optional) arrow. // 0 bit specifies left or right. // 1 bit specifies top or bottom. // 2 bit specifies horizontal or vertical. // 3 bit specifies whether the arrow at the center of its residing edge. enum ArrowMask { RIGHT = 0x01, BOTTOM = 0x02, VERTICAL = 0x04, CENTER = 0x08, }; enum Arrow { TOP_LEFT = 0, TOP_RIGHT = RIGHT, BOTTOM_LEFT = BOTTOM, BOTTOM_RIGHT = BOTTOM | RIGHT, LEFT_TOP = VERTICAL, RIGHT_TOP = VERTICAL | RIGHT, LEFT_BOTTOM = VERTICAL | BOTTOM, RIGHT_BOTTOM = VERTICAL | BOTTOM | RIGHT, TOP_CENTER = CENTER, BOTTOM_CENTER = CENTER | BOTTOM, LEFT_CENTER = CENTER | VERTICAL, RIGHT_CENTER = CENTER | VERTICAL | RIGHT, NONE = 16, // No arrow. Positioned under the supplied rect. FLOAT = 17, // No arrow. Centered over the supplied rect. }; enum Shadow { STANDARD_SHADOW = 0, #if BUILDFLAG(IS_CHROMEOS_ASH) // CHROMEOS_SYSTEM_UI_SHADOW uses ChromeOS system UI shadow style. CHROMEOS_SYSTEM_UI_SHADOW, #endif // NO_SHADOW don't draw a stroke or a shadow. This is used for platforms // that provide their own shadows or UIs that doesn't need shadows. NO_SHADOW, SHADOW_COUNT, #if BUILDFLAG(IS_MAC) // On Mac, the native window server should provide its own shadow for // windows that could overlap the browser window. DIALOG_SHADOW = NO_SHADOW, #elif BUILDFLAG(IS_CHROMEOS_ASH) DIALOG_SHADOW = CHROMEOS_SYSTEM_UI_SHADOW, #else DIALOG_SHADOW = STANDARD_SHADOW, #endif }; // The border is stroked at 1px, but for the purposes of reserving space we // have to deal in dip coordinates, so round up to 1dip. static constexpr int kBorderThicknessDip = 1; // Specific to MD bubbles: size of shadow blur (outside the bubble) and // vertical offset, both in DIP. static constexpr int kShadowBlur = 6; static constexpr int kShadowVerticalOffset = 2; // Space between the anchor view and a visible arrow if one is present. static constexpr int kVisibleArrowGap = 4; // Length of the visible arrow (distance from the bubble to the tip of the // arrow) if one is present. static constexpr int kVisibleArrowLength = 8; // Radius (half-width) of the visible arrow, when one is present. static constexpr int kVisibleArrowRadius = 9; // Distance between the edge of the bubble widget and the edge of the visible // arrow if one is present. static constexpr int kVisibleArrowBuffer = 12; BubbleBorder(Arrow arrow, Shadow shadow, ui::ColorId color_id = ui::kColorDialogBackground); BubbleBorder(const BubbleBorder&) = delete; BubbleBorder& operator=(const BubbleBorder&) = delete; ~BubbleBorder() override; static bool has_arrow(Arrow a) { return a < NONE; } static bool is_arrow_on_left(Arrow a) { return has_arrow(a) && (a == LEFT_CENTER || !(a & (RIGHT | CENTER))); } static bool is_arrow_on_top(Arrow a) { return has_arrow(a) && (a == TOP_CENTER || !(a & (BOTTOM | CENTER))); } static bool is_arrow_on_horizontal(Arrow a) { return a >= NONE ? false : !(int{a} & VERTICAL); } static bool is_arrow_at_center(Arrow a) { return has_arrow(a) && !!(int{a} & CENTER); } static Arrow horizontal_mirror(Arrow a) { return (a == TOP_CENTER || a == BOTTOM_CENTER || a >= NONE) ? a : static_cast<Arrow>(int{a} ^ RIGHT); } static Arrow vertical_mirror(Arrow a) { return (a == LEFT_CENTER || a == RIGHT_CENTER || a >= NONE) ? a : static_cast<Arrow>(int{a} ^ BOTTOM); } // Returns the insets required by a border and shadow based on // |shadow_elevation|. This is only used for MD bubbles. A null // |shadow_elevation| will yield the default BubbleBorder MD insets. static gfx::Insets GetBorderAndShadowInsets( absl::optional<int> shadow_elevation = absl::nullopt, Shadow shadow_type = Shadow::STANDARD_SHADOW); // Draws a border and shadow outside the |rect| on |canvas|. |color_provider| // is passed into GetBorderAndShadowFlags to obtain the shadow color. static void DrawBorderAndShadow(SkRect rect, gfx::Canvas* canvas, const ui::ColorProvider* color_provider); // Set the corner radius, enables Material Design. void SetCornerRadius(int radius); // Set the customized rounded corners. void SetRoundedCorners(int top_left, int top_right, int bottom_right, int bottom_left); // Get or set the arrow type. void set_arrow(Arrow arrow) { arrow_ = arrow; } Arrow arrow() const { return arrow_; } void set_visible_arrow(bool visible_arrow) { visible_arrow_ = visible_arrow; } bool visible_arrow() const { return visible_arrow_; } // Get the shadow type. Shadow shadow() const { return shadow_; } // Get or set the color for the bubble and arrow body. void SetColor(SkColor color); SkColor color() const { return color_; } // Sets a desired pixel distance between the arrow tip and the outside edge of // the neighboring border image. For example: |----offset----| // '(' represents shadow around the '{' edge: ((({ ^ }))) // The arrow will still anchor to the same location but the bubble will shift // location to place the arrow |offset| pixels from the perpendicular edge. void set_arrow_offset(int offset) { arrow_offset_ = offset; } int arrow_offset() const { return arrow_offset_; } // Sets the shadow elevation for MD shadows. A null |shadow_elevation| will // yield the default BubbleBorder MD shadow. void set_md_shadow_elevation(int shadow_elevation) { md_shadow_elevation_ = shadow_elevation; } // Set a flag to avoid the bubble's shadow overlapping the anchor. void set_avoid_shadow_overlap(bool value) { avoid_shadow_overlap_ = value; } // Sets an explicit insets value to be used. void set_insets(const gfx::Insets& insets) { insets_ = insets; } // Get the desired widget bounds (in screen coordinates) given the anchor rect // and bubble content size; calculated from shadow and arrow image dimensions. virtual gfx::Rect GetBounds(const gfx::Rect& anchor_rect, const gfx::Size& contents_size) const; // Returns the corner radius of the current image set. int corner_radius() const { return corner_radius_; } // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; void OnViewThemeChanged(View* view) override; // Sets and activates the visible |arrow|. The position of the visible arrow // on the edge of the |bubble_bounds| is determined using the // |anchor_rect|. While the side of the arrow is already determined by // |arrow|, the placement along the side is chosen to point towards the // |anchor_rect|. For a horizontal bubble with an arrow on either the left // or right side, the arrow is placed to point towards the vertical center of // |anchor_rect|. For a vertical arrow that is either on top of below the // bubble, the placement depends on the specifics of |arrow|: // // * A right-aligned arrow (TOP_RIGHT, BOTTOM_RIGHT) optimizes the arrow // position to point at the right edge of the |element_bounds|. // * A center-aligned arrow (TOP_CENTER, BOTTOM_CENTER) points towards the // horizontal center of |element_bounds|. // * Otherwise, the arrow points towards the left edge of |element_bounds|. // // If it is not possible for the arrow to point towards the targeted point // because there is no overlap between the bubble and the element in the // significant direction, the arrow is placed at the most extreme allowed // position that is closest to the targeted point. // // Note that |bubble_bounds| can be slightly shifted to accommodate appended // arrow and make the whole popup visialy pointing to the anchor element. // // Returns false if the arrow cannot be added due to missing space on the // bubble border. bool AddArrowToBubbleCornerAndPointTowardsAnchor(const gfx::Rect& anchor_rect, gfx::Rect& bubble_bounds); // Returns a constant reference to the |visible_arrow_rect_| for teseting // purposes. const gfx::Rect& GetVisibibleArrowRectForTesting() { return visible_arrow_rect_; } private: FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, GetSizeForContentsSizeTest); FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, GetBoundsOriginTest); FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, ShadowTypes); FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, VisibleArrowSizesAreConsistent); FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, MoveContentsBoundsToPlaceVisibleArrow); // Returns the translation vector for a bubble to make space for // inserting the visible arrow at the right position for |arrow_|. // |include_gap| controls if the displacement accounts for the // kVisibleArrowGap. static gfx::Vector2d GetContentsBoundsOffsetToPlaceVisibleArrow( BubbleBorder::Arrow arrow, bool include_gap = true); // The border and arrow stroke size used in image assets, in pixels. static constexpr int kStroke = 1; gfx::Size GetSizeForContentsSize(const gfx::Size& contents_size) const; // Calculates and assigns the |visible_arrow_rect_| for the given // |contents_bounds| and the |anchor_point| in which the arrow is rendered to. void CalculateVisibleArrowRect(const gfx::Rect& contents_bounds, const gfx::Point& anchor_point) const; // Returns the region within |view| representing the client area. This can be // set as a canvas clip to ensure any fill or shadow from the border does not // draw over the contents of the bubble. SkRRect GetClientRect(const View& view) const; // Sets `color_` appropriately, using `view` to obtain a ColorProvider. // `view` may be null if `requested_color_` is set. void UpdateColor(View* view); // Paint for the NO_SHADOW shadow type. This just paints transparent pixels // to make the window shape based on insets and GetBorderCornerRadius(). void PaintNoShadow(const View& view, gfx::Canvas* canvas); // Paint a visible arrow pointing to the anchor region. void PaintVisibleArrow(const View& view, gfx::Canvas* canvas); Arrow arrow_; int arrow_offset_ = 0; // Corner radius for the bubble border. If supplied the border will use // material design. int corner_radius_ = 0; // The rounded corner radius for the 4 corners. SkVector radii_[4]{{}, {}, {}, {}}; // Whether a visible arrow should be present. bool visible_arrow_ = false; // Cached arrow bounding box, calculated when bounds are calculated. mutable gfx::Rect visible_arrow_rect_; Shadow shadow_; absl::optional<int> md_shadow_elevation_; ui::ColorId color_id_; absl::optional<SkColor> requested_color_; SkColor color_ = gfx::kPlaceholderColor; bool avoid_shadow_overlap_ = false; absl::optional<gfx::Insets> insets_; }; // A Background that clips itself to the specified BubbleBorder and uses the // color of the BubbleBorder. class VIEWS_EXPORT BubbleBackground : public Background { public: explicit BubbleBackground(BubbleBorder* border) : border_(border) {} BubbleBackground(const BubbleBackground&) = delete; BubbleBackground& operator=(const BubbleBackground&) = delete; // Overridden from Background: void Paint(gfx::Canvas* canvas, View* view) const override; private: raw_ptr<BubbleBorder, DanglingUntriaged> border_; }; } // namespace views #endif // UI_VIEWS_BUBBLE_BUBBLE_BORDER_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_border.h
C++
unknown
12,876
// 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/bubble/bubble_border_arrow_utils.h" namespace views { gfx::Point GetArrowAnchorPointFromAnchorRect(BubbleBorder::Arrow arrow, const gfx::Rect& anchor_rect) { switch (arrow) { case BubbleBorder::TOP_LEFT: return anchor_rect.bottom_left(); case BubbleBorder::TOP_RIGHT: return anchor_rect.bottom_right(); case BubbleBorder::BOTTOM_LEFT: return anchor_rect.origin(); case BubbleBorder::BOTTOM_RIGHT: return anchor_rect.top_right(); case BubbleBorder::LEFT_TOP: return anchor_rect.top_right(); case BubbleBorder::RIGHT_TOP: return anchor_rect.origin(); case BubbleBorder::LEFT_BOTTOM: return anchor_rect.bottom_right(); case BubbleBorder::RIGHT_BOTTOM: return anchor_rect.bottom_left(); case BubbleBorder::TOP_CENTER: return anchor_rect.bottom_center(); case BubbleBorder::BOTTOM_CENTER: return anchor_rect.top_center(); case BubbleBorder::LEFT_CENTER: return anchor_rect.right_center(); case BubbleBorder::RIGHT_CENTER: return anchor_rect.left_center(); default: NOTREACHED_NORETURN(); } } gfx::Vector2d GetContentBoundsOffsetToArrowAnchorPoint( const gfx::Rect& contents_bounds, BubbleBorder::Arrow arrow, const gfx::Point& anchor_point) { switch (arrow) { case BubbleBorder::TOP_LEFT: return anchor_point - contents_bounds.origin(); case BubbleBorder::TOP_RIGHT: return anchor_point - contents_bounds.top_right(); case BubbleBorder::BOTTOM_LEFT: return anchor_point - contents_bounds.bottom_left(); case BubbleBorder::BOTTOM_RIGHT: return anchor_point - contents_bounds.bottom_right(); case BubbleBorder::LEFT_TOP: return anchor_point - contents_bounds.origin(); case BubbleBorder::RIGHT_TOP: return anchor_point - contents_bounds.top_right(); case BubbleBorder::LEFT_BOTTOM: return anchor_point - contents_bounds.bottom_left(); case BubbleBorder::RIGHT_BOTTOM: return anchor_point - contents_bounds.bottom_right(); case BubbleBorder::TOP_CENTER: return anchor_point - contents_bounds.top_center(); case BubbleBorder::BOTTOM_CENTER: return anchor_point - contents_bounds.bottom_center(); case BubbleBorder::LEFT_CENTER: return anchor_point - contents_bounds.left_center(); case BubbleBorder::RIGHT_CENTER: return anchor_point - contents_bounds.right_center(); default: NOTREACHED_NORETURN(); } } BubbleArrowSide GetBubbleArrowSide(BubbleBorder::Arrow arrow) { // Note: VERTICAL arrows are on the sides of the bubble, while !VERTICAL are // on the top or bottom. if (int{arrow} & BubbleBorder::VERTICAL) { return (int{arrow} & BubbleBorder::RIGHT) ? BubbleArrowSide::kRight : BubbleArrowSide::kLeft; } return (int{arrow} & BubbleBorder::BOTTOM) ? BubbleArrowSide::kBottom : BubbleArrowSide::kTop; } gfx::Vector2d GetContentsBoundsOffsetToPlaceVisibleArrow( BubbleBorder::Arrow arrow, bool include_gap) { if (arrow == BubbleBorder::NONE || arrow == BubbleBorder::FLOAT) { return gfx::Vector2d(); } const gfx::Insets visible_arrow_insets = GetVisibleArrowInsets(arrow, include_gap); return gfx::Vector2d( visible_arrow_insets.left() - visible_arrow_insets.right(), visible_arrow_insets.top() - visible_arrow_insets.bottom()); } gfx::Insets GetVisibleArrowInsets(BubbleBorder::Arrow arrow, bool include_gap) { DCHECK(BubbleBorder::has_arrow(arrow)); const int arrow_size = include_gap ? BubbleBorder::kVisibleArrowGap + BubbleBorder::kVisibleArrowLength : BubbleBorder::kVisibleArrowLength; gfx::Insets result; switch (GetBubbleArrowSide(arrow)) { case BubbleArrowSide::kRight: result.set_right(arrow_size); break; case BubbleArrowSide::kLeft: result.set_left(arrow_size); break; case BubbleArrowSide::kTop: result.set_top(arrow_size); break; case BubbleArrowSide::kBottom: result.set_bottom(arrow_size); break; } return result; } bool IsVerticalArrow(BubbleBorder::Arrow arrow) { const BubbleArrowSide side = GetBubbleArrowSide(arrow); return side == BubbleArrowSide::kTop || side == BubbleArrowSide::kBottom; } gfx::Size GetVisibleArrowSize(BubbleBorder::Arrow arrow) { int kVisibleArrowDiameter = 2 * BubbleBorder::kVisibleArrowRadius; return IsVerticalArrow(arrow) ? gfx::Size(kVisibleArrowDiameter, BubbleBorder::kVisibleArrowLength) : gfx::Size(BubbleBorder::kVisibleArrowLength, kVisibleArrowDiameter); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_border_arrow_utils.cc
C++
unknown
5,078
// 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_BUBBLE_BUBBLE_BORDER_ARROW_UTILS_H_ #define UI_VIEWS_BUBBLE_BUBBLE_BORDER_ARROW_UTILS_H_ #include "ui/views/bubble/bubble_border.h" #include "ui/views/views_export.h" namespace views { // The side of the bubble the arrow is located on. enum class BubbleArrowSide { kLeft, kRight, kTop, kBottom }; // Converts the |arrow| into a BubbleArrowSide. VIEWS_EXPORT BubbleArrowSide GetBubbleArrowSide(BubbleBorder::Arrow arrow); // Returns the appropriate anchor point on the edge of the |anchor_rect| for a // given |arrow| position. VIEWS_EXPORT gfx::Point GetArrowAnchorPointFromAnchorRect( BubbleBorder::Arrow arrow, const gfx::Rect& anchor_rect); // Returns the origin offset to move the |contents_bounds| to be placed // appropriately for a given |arrow| at the |anchor_point|. VIEWS_EXPORT gfx::Vector2d GetContentBoundsOffsetToArrowAnchorPoint( const gfx::Rect& contents_bounds, BubbleBorder::Arrow arrow, const gfx::Point& anchor_point); // Converts the |arrow| into a BubbleArrowSide. VIEWS_EXPORT BubbleArrowSide GetBubbleArrowSide(BubbleBorder::Arrow arrow); // Returns the translation vector for a bubble to make space for // inserting the visible arrow at the right position for |arrow_|. // |include_gap| controls if the displacement accounts for the // kVisibleArrowGap. VIEWS_EXPORT gfx::Vector2d GetContentsBoundsOffsetToPlaceVisibleArrow( BubbleBorder::Arrow arrow, bool include_gap = true); VIEWS_EXPORT gfx::Insets GetVisibleArrowInsets(BubbleBorder::Arrow arrow, bool include_gap); // Returns true if the arrow is vertical meaning that it is either placed on // the top of the bottom of the border. VIEWS_EXPORT bool IsVerticalArrow(BubbleBorder::Arrow arrow); // Returns the size of the bounding rectangle of the visible |arrow|. VIEWS_EXPORT gfx::Size GetVisibleArrowSize(BubbleBorder::Arrow arrow); } // namespace views #endif // UI_VIEWS_BUBBLE_BUBBLE_BORDER_ARROW_UTILS_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_border_arrow_utils.h
C++
unknown
2,142
// 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/bubble/bubble_border.h" #include <stddef.h> #include <memory> #include "base/strings/stringprintf.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/views/bubble/bubble_border_arrow_utils.h" #include "ui/views/test/views_test_base.h" namespace views { using BubbleBorderTest = views::ViewsTestBase; TEST_F(BubbleBorderTest, GetMirroredArrow) { // Horizontal mirroring. EXPECT_EQ(BubbleBorder::TOP_RIGHT, BubbleBorder::horizontal_mirror(BubbleBorder::TOP_LEFT)); EXPECT_EQ(BubbleBorder::TOP_LEFT, BubbleBorder::horizontal_mirror(BubbleBorder::TOP_RIGHT)); EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_LEFT)); EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_RIGHT)); EXPECT_EQ(BubbleBorder::RIGHT_TOP, BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_TOP)); EXPECT_EQ(BubbleBorder::LEFT_TOP, BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_TOP)); EXPECT_EQ(BubbleBorder::RIGHT_BOTTOM, BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_BOTTOM)); EXPECT_EQ(BubbleBorder::LEFT_BOTTOM, BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_BOTTOM)); EXPECT_EQ(BubbleBorder::TOP_CENTER, BubbleBorder::horizontal_mirror(BubbleBorder::TOP_CENTER)); EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_CENTER)); EXPECT_EQ(BubbleBorder::RIGHT_CENTER, BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_CENTER)); EXPECT_EQ(BubbleBorder::LEFT_CENTER, BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_CENTER)); EXPECT_EQ(BubbleBorder::NONE, BubbleBorder::horizontal_mirror(BubbleBorder::NONE)); EXPECT_EQ(BubbleBorder::FLOAT, BubbleBorder::horizontal_mirror(BubbleBorder::FLOAT)); // Vertical mirroring. EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, BubbleBorder::vertical_mirror(BubbleBorder::TOP_LEFT)); EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, BubbleBorder::vertical_mirror(BubbleBorder::TOP_RIGHT)); EXPECT_EQ(BubbleBorder::TOP_LEFT, BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_LEFT)); EXPECT_EQ(BubbleBorder::TOP_RIGHT, BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_RIGHT)); EXPECT_EQ(BubbleBorder::LEFT_BOTTOM, BubbleBorder::vertical_mirror(BubbleBorder::LEFT_TOP)); EXPECT_EQ(BubbleBorder::RIGHT_BOTTOM, BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_TOP)); EXPECT_EQ(BubbleBorder::LEFT_TOP, BubbleBorder::vertical_mirror(BubbleBorder::LEFT_BOTTOM)); EXPECT_EQ(BubbleBorder::RIGHT_TOP, BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_BOTTOM)); EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, BubbleBorder::vertical_mirror(BubbleBorder::TOP_CENTER)); EXPECT_EQ(BubbleBorder::TOP_CENTER, BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_CENTER)); EXPECT_EQ(BubbleBorder::LEFT_CENTER, BubbleBorder::vertical_mirror(BubbleBorder::LEFT_CENTER)); EXPECT_EQ(BubbleBorder::RIGHT_CENTER, BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_CENTER)); EXPECT_EQ(BubbleBorder::NONE, BubbleBorder::vertical_mirror(BubbleBorder::NONE)); EXPECT_EQ(BubbleBorder::FLOAT, BubbleBorder::vertical_mirror(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, HasArrow) { EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_LEFT)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_RIGHT)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_LEFT)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_RIGHT)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_TOP)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_TOP)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_BOTTOM)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_BOTTOM)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_CENTER)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_CENTER)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_CENTER)); EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_CENTER)); EXPECT_FALSE(BubbleBorder::has_arrow(BubbleBorder::NONE)); EXPECT_FALSE(BubbleBorder::has_arrow(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, IsArrowOnLeft) { EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_LEFT)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_RIGHT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_LEFT)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_RIGHT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_TOP)); EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_BOTTOM)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_BOTTOM)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_CENTER)); EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::NONE)); EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, IsArrowOnTop) { EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_LEFT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_RIGHT)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_LEFT)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_RIGHT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_TOP)); EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_BOTTOM)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_BOTTOM)); EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::NONE)); EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, IsArrowOnHorizontal) { EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_LEFT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_RIGHT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_LEFT)); EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_RIGHT)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_BOTTOM)); EXPECT_FALSE( BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_BOTTOM)); EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_CENTER)); EXPECT_TRUE( BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_CENTER)); EXPECT_FALSE( BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::NONE)); EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, IsArrowAtCenter) { EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_LEFT)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_RIGHT)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_LEFT)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_RIGHT)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_TOP)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_BOTTOM)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_BOTTOM)); EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_CENTER)); EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_CENTER)); EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_CENTER)); EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_CENTER)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::NONE)); EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::FLOAT)); } TEST_F(BubbleBorderTest, GetSizeForContentsSizeTest) { views::BubbleBorder border(BubbleBorder::NONE, BubbleBorder::NO_SHADOW); const gfx::Insets kInsets = border.GetInsets(); // kSmallSize is smaller than the minimum allowable size and does not // contribute to the resulting size. const gfx::Size kSmallSize = gfx::Size(1, 2); // kMediumSize is larger than the minimum allowable size and contributes to // the resulting size. const gfx::Size kMediumSize = gfx::Size(50, 60); const gfx::Size kSmallHorizArrow(kSmallSize.width() + kInsets.width(), kSmallSize.height() + kInsets.height()); const gfx::Size kSmallVertArrow(kSmallHorizArrow.width(), kSmallHorizArrow.height()); const gfx::Size kSmallNoArrow(kSmallHorizArrow.width(), kSmallHorizArrow.height()); const gfx::Size kMediumHorizArrow(kMediumSize.width() + kInsets.width(), kMediumSize.height() + kInsets.height()); const gfx::Size kMediumVertArrow(kMediumHorizArrow.width(), kMediumHorizArrow.height()); const gfx::Size kMediumNoArrow(kMediumHorizArrow.width(), kMediumHorizArrow.height()); struct TestCase { BubbleBorder::Arrow arrow; gfx::Size content; gfx::Size expected_without_arrow; }; TestCase cases[] = { // Content size: kSmallSize {BubbleBorder::TOP_LEFT, kSmallSize, kSmallNoArrow}, {BubbleBorder::TOP_CENTER, kSmallSize, kSmallNoArrow}, {BubbleBorder::TOP_RIGHT, kSmallSize, kSmallNoArrow}, {BubbleBorder::BOTTOM_LEFT, kSmallSize, kSmallNoArrow}, {BubbleBorder::BOTTOM_CENTER, kSmallSize, kSmallNoArrow}, {BubbleBorder::BOTTOM_RIGHT, kSmallSize, kSmallNoArrow}, {BubbleBorder::LEFT_TOP, kSmallSize, kSmallNoArrow}, {BubbleBorder::LEFT_CENTER, kSmallSize, kSmallNoArrow}, {BubbleBorder::LEFT_BOTTOM, kSmallSize, kSmallNoArrow}, {BubbleBorder::RIGHT_TOP, kSmallSize, kSmallNoArrow}, {BubbleBorder::RIGHT_CENTER, kSmallSize, kSmallNoArrow}, {BubbleBorder::RIGHT_BOTTOM, kSmallSize, kSmallNoArrow}, {BubbleBorder::NONE, kSmallSize, kSmallNoArrow}, {BubbleBorder::FLOAT, kSmallSize, kSmallNoArrow}, // Content size: kMediumSize {BubbleBorder::TOP_LEFT, kMediumSize, kMediumNoArrow}, {BubbleBorder::TOP_CENTER, kMediumSize, kMediumNoArrow}, {BubbleBorder::TOP_RIGHT, kMediumSize, kMediumNoArrow}, {BubbleBorder::BOTTOM_LEFT, kMediumSize, kMediumNoArrow}, {BubbleBorder::BOTTOM_CENTER, kMediumSize, kMediumNoArrow}, {BubbleBorder::BOTTOM_RIGHT, kMediumSize, kMediumNoArrow}, {BubbleBorder::LEFT_TOP, kMediumSize, kMediumNoArrow}, {BubbleBorder::LEFT_CENTER, kMediumSize, kMediumNoArrow}, {BubbleBorder::LEFT_BOTTOM, kMediumSize, kMediumNoArrow}, {BubbleBorder::RIGHT_TOP, kMediumSize, kMediumNoArrow}, {BubbleBorder::RIGHT_CENTER, kMediumSize, kMediumNoArrow}, {BubbleBorder::RIGHT_BOTTOM, kMediumSize, kMediumNoArrow}, {BubbleBorder::NONE, kMediumSize, kMediumNoArrow}, {BubbleBorder::FLOAT, kMediumSize, kMediumNoArrow}}; for (size_t i = 0; i < std::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("i=%d arrow=%d", static_cast<int>(i), cases[i].arrow)); border.set_arrow(cases[i].arrow); EXPECT_EQ(cases[i].expected_without_arrow, border.GetSizeForContentsSize(cases[i].content)); } } TEST_F(BubbleBorderTest, GetBoundsOriginTest) { for (int i = 0; i < BubbleBorder::SHADOW_COUNT; ++i) { const BubbleBorder::Shadow shadow = static_cast<BubbleBorder::Shadow>(i); SCOPED_TRACE(testing::Message() << "BubbleBorder::Shadow: " << shadow); views::BubbleBorder border(BubbleBorder::TOP_LEFT, shadow); const gfx::Rect kAnchor(100, 100, 20, 30); const gfx::Size kContentSize(500, 600); const gfx::Insets kInsets = border.GetInsets(); border.set_arrow(BubbleBorder::TOP_LEFT); const gfx::Size kTotalSize = border.GetSizeForContentsSize(kContentSize); border.set_arrow(BubbleBorder::RIGHT_BOTTOM); EXPECT_EQ(kTotalSize, border.GetSizeForContentsSize(kContentSize)); border.set_arrow(BubbleBorder::NONE); EXPECT_EQ(kTotalSize, border.GetSizeForContentsSize(kContentSize)); const int kStrokeWidth = shadow == BubbleBorder::NO_SHADOW ? 0 : BubbleBorder::kStroke; const int kBorderedContentHeight = kContentSize.height() + (2 * kStrokeWidth); const int kStrokeTopInset = kStrokeWidth - kInsets.top(); const int kStrokeBottomInset = kStrokeWidth - kInsets.bottom(); const int kStrokeLeftInset = kStrokeWidth - kInsets.left(); const int kStrokeRightInset = kStrokeWidth - kInsets.right(); const int kTopHorizArrowY = kAnchor.bottom() + kStrokeTopInset; const int kBottomHorizArrowY = kAnchor.y() - kTotalSize.height() - kStrokeBottomInset; const int kLeftVertArrowX = kAnchor.x() + kAnchor.width() + kStrokeLeftInset; const int kRightVertArrowX = kAnchor.x() - kTotalSize.width() - kStrokeRightInset; struct TestCase { BubbleBorder::Arrow arrow; int expected_x; int expected_y; }; TestCase cases[] = { // Horizontal arrow tests. {BubbleBorder::TOP_LEFT, kAnchor.x() + kStrokeLeftInset, kTopHorizArrowY}, {BubbleBorder::TOP_CENTER, kAnchor.CenterPoint().x() - (kTotalSize.width() / 2), kTopHorizArrowY}, {BubbleBorder::BOTTOM_RIGHT, kAnchor.x() + kAnchor.width() - kTotalSize.width() - kStrokeRightInset, kBottomHorizArrowY}, // Vertical arrow tests. {BubbleBorder::LEFT_TOP, kLeftVertArrowX, kAnchor.y() + kStrokeTopInset}, {BubbleBorder::LEFT_CENTER, kLeftVertArrowX, kAnchor.CenterPoint().y() - (kBorderedContentHeight / 2) + kStrokeTopInset}, {BubbleBorder::RIGHT_BOTTOM, kRightVertArrowX, kAnchor.y() + kAnchor.height() - kTotalSize.height() - kStrokeBottomInset}, // No arrow tests. {BubbleBorder::NONE, kAnchor.x() + (kAnchor.width() - kTotalSize.width()) / 2, kAnchor.y() + kAnchor.height()}, {BubbleBorder::FLOAT, kAnchor.x() + (kAnchor.width() - kTotalSize.width()) / 2, kAnchor.y() + (kAnchor.height() - kTotalSize.height()) / 2}, }; for (size_t j = 0; j < std::size(cases); ++j) { SCOPED_TRACE(base::StringPrintf("shadow=%d j=%d arrow=%d", static_cast<int>(shadow), static_cast<int>(j), cases[j].arrow)); const BubbleBorder::Arrow arrow = cases[j].arrow; border.set_arrow(arrow); gfx::Point origin = border.GetBounds(kAnchor, kContentSize).origin(); EXPECT_EQ(cases[j].expected_x, origin.x()); EXPECT_EQ(cases[j].expected_y, origin.y()); } } } TEST_F(BubbleBorderTest, BubblePositionedCorrectlyWithVisibleArrow) { views::BubbleBorder border(BubbleBorder::TOP_LEFT, BubbleBorder::STANDARD_SHADOW); const gfx::Insets kInsets = border.GetInsets(); border.set_visible_arrow(true); constexpr gfx::Size kContentSize(200, 150); // Anchor position. constexpr gfx::Point kAnchorOrigin(100, 100); // Anchor smaller than contents. constexpr gfx::Rect kAnchor1(kAnchorOrigin, gfx::Size(40, 50)); // Anchor larger than contents. constexpr gfx::Rect kAnchor2(kAnchorOrigin, gfx::Size(400, 300)); // Anchor extremely small. constexpr gfx::Rect kAnchor3(kAnchorOrigin, gfx::Size(10, 12)); // TODO(dfried): in all of these tests, the border is factored into the height // of the bubble an extra time, because of the fact that the arrow doesn't // properly overlap the border in the calculation (though it does visually). // Please fix at some point. // TOP_LEFT: border.set_arrow(BubbleBorder::TOP_LEFT); gfx::Rect bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor1.x() - kInsets.left(), bounds.x()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor2.x() - kInsets.left() + BubbleBorder::kBorderThicknessDip, bounds.x()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_GT(kAnchor3.x() - kInsets.left() + BubbleBorder::kBorderThicknessDip, bounds.x()); // TOP_CENTER: border.set_arrow(BubbleBorder::TOP_CENTER); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor1.bottom_center().x() - bounds.width() / 2, bounds.x()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor2.bottom_center().x() - bounds.width() / 2, bounds.x()); bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor3.bottom_center().x() - bounds.width() / 2, bounds.x()); // TOP_RIGHT: border.set_arrow(BubbleBorder::TOP_RIGHT); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ(kAnchor1.right() + kInsets.right(), bounds.right()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_EQ( kAnchor2.right() + kInsets.right() - BubbleBorder::kBorderThicknessDip, bounds.right()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.bottom() + BubbleBorder::kVisibleArrowLength, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.bottom() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.y()); EXPECT_LT( kAnchor3.right() + kInsets.right() - BubbleBorder::kBorderThicknessDip, bounds.right()); // BOTTOM_LEFT: border.set_arrow(BubbleBorder::BOTTOM_LEFT); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor1.x() - kInsets.left(), bounds.x()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor2.x() - kInsets.left() + BubbleBorder::kBorderThicknessDip, bounds.x()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_GT(kAnchor3.x() - kInsets.left() + BubbleBorder::kBorderThicknessDip, bounds.x()); // BOTTOM_CENTER: border.set_arrow(BubbleBorder::BOTTOM_CENTER); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor1.bottom_center().x() - bounds.width() / 2, bounds.x()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor2.bottom_center().x() - bounds.width() / 2, bounds.x()); bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor3.bottom_center().x() - bounds.width() / 2, bounds.x()); // BOTTOM_RIGHT: border.set_arrow(BubbleBorder::BOTTOM_RIGHT); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor1.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ(kAnchor1.right() + kInsets.right(), bounds.right()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor2.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_EQ( kAnchor2.right() + kInsets.right() - BubbleBorder::kBorderThicknessDip, bounds.right()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.height() + kInsets.top() + BubbleBorder::kVisibleArrowLength + BubbleBorder::kBorderThicknessDip, bounds.height()); EXPECT_EQ(kContentSize.width() + kInsets.width(), bounds.width()); EXPECT_EQ(kAnchor3.y() - BubbleBorder::kVisibleArrowGap, bounds.bottom()); EXPECT_LT( kAnchor3.right() + kInsets.right() - BubbleBorder::kBorderThicknessDip, bounds.right()); // LEFT_TOP: border.set_arrow(BubbleBorder::LEFT_TOP); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_EQ(kAnchor1.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_EQ(kAnchor2.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_GT(kAnchor3.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); // LEFT_CENTER: // Because the shadow counts as part of the bounds, the shadow offset (which // is applied vertically) will affect the vertical positioning of a bubble // which is placed next to the anchor by a similar amount. border.set_arrow(BubbleBorder::LEFT_CENTER); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_NEAR(kAnchor1.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_NEAR(kAnchor2.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_NEAR(kAnchor3.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); // LEFT_BOTTOM: border.set_arrow(BubbleBorder::LEFT_BOTTOM); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_EQ( kAnchor1.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_EQ( kAnchor2.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.right() + BubbleBorder::kVisibleArrowGap + BubbleBorder::kBorderThicknessDip, bounds.x()); EXPECT_LT( kAnchor3.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); // RIGHT_TOP: border.set_arrow(BubbleBorder::RIGHT_TOP); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_EQ(kAnchor1.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_EQ(kAnchor2.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_GT(kAnchor3.y() - kInsets.top() + BubbleBorder::kBorderThicknessDip, bounds.y()); // // RIGHT_CENTER: // Because the shadow counts as part of the bounds, the shadow offset (which // is applied vertically) will affect the vertical positioning of a bubble // which is placed next to the anchor by a similar amount. border.set_arrow(BubbleBorder::RIGHT_CENTER); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_NEAR(kAnchor1.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_NEAR(kAnchor2.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_NEAR(kAnchor3.right_center().y() - bounds.height() / 2, bounds.y(), BubbleBorder::kShadowVerticalOffset); // RIGHT_BOTTOM: border.set_arrow(BubbleBorder::RIGHT_BOTTOM); bounds = border.GetBounds(kAnchor1, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor1.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_EQ( kAnchor1.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); bounds = border.GetBounds(kAnchor2, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor2.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_EQ( kAnchor2.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); // Too small of an anchor view will shift the bubble to make sure the arrow // is not too close to the edge of the bubble. bounds = border.GetBounds(kAnchor3, kContentSize); EXPECT_EQ(kContentSize.width() + kInsets.right() + BubbleBorder::kVisibleArrowLength, bounds.width()); EXPECT_EQ(kContentSize.height() + kInsets.height(), bounds.height()); EXPECT_EQ(kAnchor3.x() - BubbleBorder::kVisibleArrowGap - BubbleBorder::kBorderThicknessDip, bounds.right()); EXPECT_LT( kAnchor3.bottom() + kInsets.bottom() - BubbleBorder::kBorderThicknessDip, bounds.bottom()); } TEST_F(BubbleBorderTest, AddArrowToBubbleCornerAndPointTowardsAnchor) { // Create bubble bounds located at pixel x=400,y=600 with a dimension of // 300x200 pixels. const gfx::Rect bubble_bounds(400, 600, 300, 200); // The element will have a fixed size as well. const gfx::Size element_size(350, 100); int most_left_x_position = bubble_bounds.x() + BubbleBorder::kVisibleArrowBuffer; int most_right_x_position = bubble_bounds.right() - BubbleBorder::kVisibleArrowBuffer - BubbleBorder::kVisibleArrowRadius * 2; // The y position of an arrow at the upper edge of the bubble. int upper_arrow_y_position = bubble_bounds.y(); // The y position of an arrow at the lower edge of the bubble. int lower_arrow_y_position = bubble_bounds.bottom() - BubbleBorder::kVisibleArrowLength; struct TestCase { gfx::Point element_origin; BubbleBorder::Arrow supplied_arrow; gfx::Point expected_arrow_position; bool expected_arrow_visibility_and_return_value; gfx::Rect expected_bubble_bounds; } test_cases[]{ // First are using the following scenario: // // y=200 ----------------- // | x | element // ----------------- // // y=600 ----------- // | | // | | bubble // | | // y=800 ----------- // // | x=380 // | x=400 {{380, 200}, BubbleBorder::Arrow::TOP_LEFT, // The arrow sits close to the right edge of the bubble. // The bubble is located above the upper edge. Note that // insets need to be taken into account. {most_left_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{380, 200}, BubbleBorder::Arrow::TOP_CENTER, // The arrow points to the horizontal center of the element. // Note that the spatial extension of the arrow has to be // taken into account. The bubble is located above the upper // edge. Note that insets need to be taken into account. {380 + element_size.width() / 2 - BubbleBorder::kVisibleArrowRadius, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{380, 200}, BubbleBorder::Arrow::TOP_RIGHT, // The arrow points to the horizontal center of the element. // Note that the spatial extension of the arrow has to be // taken into account. The bubble is located above the upper // edge. Note that insets need to be taken into account. {most_right_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, // The following tests are using a bubble that is highly displaced from // the // element: // // y=200 ----------------- // | x | element // ----------------- // // y=600 ----------- // | | // | | bubble // | | // y=800 ----------- // // | x=750 // | x=400 // The arrow should always be located on the most right position. {{750, 200}, BubbleBorder::Arrow::TOP_LEFT, {most_right_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{750, 200}, BubbleBorder::Arrow::TOP_CENTER, {most_right_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{750, 200}, BubbleBorder::Arrow::TOP_RIGHT, {most_right_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, // And the reverse scenario: // // y=200 ----------------- // | x | element // ----------------- // // y=600 ----------- // | | // | | bubble // | | // y=800 ----------- // // | x=0 // | x=400 // The arrow should always be located on the most right position. {{0, 200}, BubbleBorder::Arrow::TOP_LEFT, {most_left_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{0, 200}, BubbleBorder::Arrow::TOP_CENTER, {most_left_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{0, 200}, BubbleBorder::Arrow::TOP_RIGHT, {most_left_x_position, upper_arrow_y_position}, true, bubble_bounds + gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, // The following tests use a BOTTOM arrow. This should only replace the // upper_arrow_y_position with the lower_arrow_y_position in all tests. {{380, 200}, BubbleBorder::Arrow::BOTTOM_LEFT, {most_left_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{380, 200}, BubbleBorder::Arrow::BOTTOM_CENTER, {380 + element_size.width() / 2 - BubbleBorder::kVisibleArrowRadius, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{380, 200}, BubbleBorder::Arrow::BOTTOM_RIGHT, {most_right_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{750, 200}, BubbleBorder::Arrow::BOTTOM_LEFT, {most_right_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{750, 200}, BubbleBorder::Arrow::BOTTOM_CENTER, {most_right_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{750, 200}, BubbleBorder::Arrow::BOTTOM_RIGHT, {most_right_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{0, 200}, BubbleBorder::Arrow::BOTTOM_LEFT, {most_left_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{0, 200}, BubbleBorder::Arrow::BOTTOM_CENTER, {most_left_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, {{0, 200}, BubbleBorder::Arrow::BOTTOM_RIGHT, {most_left_x_position, lower_arrow_y_position}, true, bubble_bounds - gfx::Vector2d(0, BubbleBorder::kVisibleArrowLength)}, // Now, the horizontal arrow scenario is tested // y=600 ----------- // y=650 ----------------- | | // | x | | | // y=750 ----------------- | | // y=800 ----------- // | x=0 // | x=400 // The arrow is always located on the right side to point towards the // vertical center of the element. {{0, 650}, BubbleBorder::Arrow::LEFT_TOP, {bubble_bounds.x(), 650 + element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, bubble_bounds + gfx::Vector2d(BubbleBorder::kVisibleArrowLength, 0)}, {{0, 650}, BubbleBorder::Arrow::LEFT_CENTER, {bubble_bounds.x(), 650 + element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, bubble_bounds + gfx::Vector2d(BubbleBorder::kVisibleArrowLength, 0)}, {{0, 650}, BubbleBorder::Arrow::LEFT_BOTTOM, {bubble_bounds.x(), 650 + element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, bubble_bounds + gfx::Vector2d(BubbleBorder::kVisibleArrowLength, 0)}, // With the element moved to the top of the screen, the arrow should // always be placed at the most top position on the bubble, the bubble // position is adjusted as well {{0, 0}, BubbleBorder::Arrow::LEFT_TOP, {bubble_bounds.x(), element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, {bubble_bounds.x() + BubbleBorder::kVisibleArrowLength, element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius - BubbleBorder::kVisibleArrowBuffer, bubble_bounds.width(), bubble_bounds.height()}}, {{0, 0}, BubbleBorder::Arrow::LEFT_CENTER, {bubble_bounds.x(), element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, {bubble_bounds.x() + BubbleBorder::kVisibleArrowLength, element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius - BubbleBorder::kVisibleArrowBuffer, bubble_bounds.width(), bubble_bounds.height()}}, {{0, 0}, BubbleBorder::Arrow::LEFT_BOTTOM, {bubble_bounds.x(), element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius}, true, {bubble_bounds.x() + BubbleBorder::kVisibleArrowLength, element_size.height() / 2 - BubbleBorder::kVisibleArrowRadius - BubbleBorder::kVisibleArrowBuffer, bubble_bounds.width(), bubble_bounds.height()}}, }; for (auto test_case : test_cases) { gfx::Rect bubble_bounds_copy = bubble_bounds; views::BubbleBorder border(BubbleBorder::Arrow::NONE, BubbleBorder::STANDARD_SHADOW); border.set_arrow(test_case.supplied_arrow); EXPECT_EQ(border.AddArrowToBubbleCornerAndPointTowardsAnchor( {test_case.element_origin, element_size}, bubble_bounds_copy), test_case.expected_arrow_visibility_and_return_value); EXPECT_EQ(border.visible_arrow(), test_case.expected_arrow_visibility_and_return_value); EXPECT_EQ(border.GetVisibibleArrowRectForTesting().origin(), test_case.expected_arrow_position); EXPECT_EQ(GetVisibleArrowSize(test_case.supplied_arrow), border.GetVisibibleArrowRectForTesting().size()); EXPECT_EQ(test_case.expected_bubble_bounds, bubble_bounds_copy); } } TEST_F(BubbleBorderTest, AddArrowToBubbleCornerAndPointTowardsAnchorWithInsufficientSpace) { // This bubble bound has uinsufficient width to place an arrow on the top or // the bottom. const gfx::Rect insufficient_width_bubble_bounds(0, 0, 10, 200); // This bound has insufficient height to place an arrow on the left or right. const gfx::Rect insufficient_height_bubble_bounds(0, 0, 100, 10); // Create bounds for the element, the specifics do no matter. const gfx::Rect element_bounds(0, 0, 350, 100); struct TestCase { gfx::Rect bubble_bounds; BubbleBorder::Arrow supplied_arrow; bool expected_arrow_visibility_and_return_value; } test_cases[]{ // Bubble is placeable on top because there is sufficient width. {insufficient_height_bubble_bounds, BubbleBorder::Arrow::TOP_CENTER, true}, // Bubble is not placeable on top because the width is insufficient. {insufficient_width_bubble_bounds, BubbleBorder::Arrow::TOP_CENTER, false}, // Bubble is not placeable on the side because the height is insufficient. {insufficient_height_bubble_bounds, BubbleBorder::Arrow::LEFT_CENTER, false}, // Bubble is placeable on the side because the height is sufficient. {insufficient_width_bubble_bounds, BubbleBorder::Arrow::LEFT_CENTER, true}, }; for (auto test_case : test_cases) { views::BubbleBorder border(BubbleBorder::Arrow::NONE, BubbleBorder::STANDARD_SHADOW); border.set_arrow(test_case.supplied_arrow); EXPECT_EQ(border.AddArrowToBubbleCornerAndPointTowardsAnchor( element_bounds, test_case.bubble_bounds), test_case.expected_arrow_visibility_and_return_value); } } TEST_F(BubbleBorderTest, IsVerticalArrow) { struct TestCase { BubbleBorder::Arrow arrow; bool is_vertical_expected; }; TestCase test_cases[] = { // BOTTOM and TOP arrows are vertical. {BubbleBorder::Arrow::BOTTOM_CENTER, true}, {BubbleBorder::Arrow::BOTTOM_LEFT, true}, {BubbleBorder::Arrow::BOTTOM_RIGHT, true}, {BubbleBorder::Arrow::TOP_CENTER, true}, {BubbleBorder::Arrow::TOP_LEFT, true}, {BubbleBorder::Arrow::TOP_RIGHT, true}, // The rest is horizontal. {BubbleBorder::Arrow::LEFT_BOTTOM, false}, {BubbleBorder::Arrow::LEFT_CENTER, false}, {BubbleBorder::Arrow::LEFT_TOP, false}, {BubbleBorder::Arrow::RIGHT_BOTTOM, false}, {BubbleBorder::Arrow::RIGHT_CENTER, false}, {BubbleBorder::Arrow::RIGHT_TOP, false}, }; for (const auto& test_case : test_cases) { EXPECT_EQ(IsVerticalArrow(test_case.arrow), test_case.is_vertical_expected); } } // Test that the correct arrow size is returned for a given arrow position. TEST_F(BubbleBorderTest, GetVisibleArrowSize) { const gfx::Size vertical_size(2 * BubbleBorder::kVisibleArrowRadius, BubbleBorder::kVisibleArrowLength); const gfx::Size horizontal_size(BubbleBorder::kVisibleArrowLength, 2 * BubbleBorder::kVisibleArrowRadius); struct TestCase { BubbleBorder::Arrow arrow; gfx::Size expected_size; }; TestCase test_cases[] = { // BOTTOM and TOP arrows have a vertical size. {BubbleBorder::Arrow::BOTTOM_CENTER, vertical_size}, {BubbleBorder::Arrow::BOTTOM_LEFT, vertical_size}, {BubbleBorder::Arrow::BOTTOM_RIGHT, vertical_size}, {BubbleBorder::Arrow::TOP_CENTER, vertical_size}, {BubbleBorder::Arrow::TOP_LEFT, vertical_size}, {BubbleBorder::Arrow::TOP_RIGHT, vertical_size}, // The rest has a horizontal size. {BubbleBorder::Arrow::LEFT_BOTTOM, horizontal_size}, {BubbleBorder::Arrow::LEFT_CENTER, horizontal_size}, {BubbleBorder::Arrow::LEFT_TOP, horizontal_size}, {BubbleBorder::Arrow::RIGHT_BOTTOM, horizontal_size}, {BubbleBorder::Arrow::RIGHT_CENTER, horizontal_size}, {BubbleBorder::Arrow::RIGHT_TOP, horizontal_size}, }; for (const auto& test_case : test_cases) { EXPECT_EQ(GetVisibleArrowSize(test_case.arrow), test_case.expected_size); } } // Test that the contents bounds are moved correctly to place the visible arrow // at the appropriate position. TEST_F(BubbleBorderTest, MoveContentsBoundsToPlaceVisibleArrow) { const int arrow_length = BubbleBorder::kVisibleArrowLength + BubbleBorder::kVisibleArrowGap; struct TestCase { BubbleBorder::Arrow arrow; gfx::Vector2d expected_contents_bounds_move; gfx::Point initial_bubble_origin = gfx::Point(0, 0); }; TestCase test_cases[] = { // BOTTOM cases: The contents is moved to the top of the screen. {BubbleBorder::Arrow::BOTTOM_LEFT, gfx::Vector2d(0, -arrow_length)}, {BubbleBorder::Arrow::BOTTOM_CENTER, gfx::Vector2d(0, -arrow_length)}, {BubbleBorder::Arrow::BOTTOM_RIGHT, gfx::Vector2d(0, -arrow_length)}, // TOP cases: The contents is moved to the bottom of the screen. {BubbleBorder::Arrow::TOP_LEFT, gfx::Vector2d(0, arrow_length)}, {BubbleBorder::Arrow::TOP_CENTER, gfx::Vector2d(0, arrow_length)}, {BubbleBorder::Arrow::TOP_RIGHT, gfx::Vector2d(0, arrow_length)}, // LEFT cases: The contents is moved to the right. {BubbleBorder::Arrow::LEFT_BOTTOM, gfx::Vector2d(arrow_length, 0)}, {BubbleBorder::Arrow::LEFT_CENTER, gfx::Vector2d(arrow_length, 0)}, {BubbleBorder::Arrow::LEFT_TOP, gfx::Vector2d(arrow_length, 0)}, // RIGHT cases: The contents is moved to the left. {BubbleBorder::Arrow::RIGHT_BOTTOM, gfx::Vector2d(-arrow_length, 0)}, {BubbleBorder::Arrow::RIGHT_CENTER, gfx::Vector2d(-arrow_length, 0)}, {BubbleBorder::Arrow::RIGHT_TOP, gfx::Vector2d(-arrow_length, 0)}, }; for (const auto& test_case : test_cases) { // Create a bubble border with a visible arrow. views::BubbleBorder border(test_case.arrow, BubbleBorder::STANDARD_SHADOW); border.set_visible_arrow(true); // Create, move and verify the contents bounds. EXPECT_EQ(border.GetContentsBoundsOffsetToPlaceVisibleArrow( test_case.arrow, /*include_gap=*/true), test_case.expected_contents_bounds_move); } } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_border_unittest.cc
C++
unknown
54,548
// 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/bubble/bubble_dialog_delegate_view.h" #include <algorithm> #include <set> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/feature_list.h" #include "base/functional/bind.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_role_properties.h" #include "ui/base/class_property.h" #include "ui/base/default_style.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/color/color_provider_manager.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_element.h" #include "ui/compositor/layer_animator.h" #include "ui/display/screen.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/vector2d_conversions.h" #include "ui/views/bubble/bubble_frame_view.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/view_class_properties.h" #include "ui/views/views_features.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" #include "ui/views/window/dialog_client_view.h" #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_MAC) #include "ui/views/widget/widget_utils_mac.h" #else #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #endif DEFINE_UI_CLASS_PROPERTY_TYPE(std::vector<views::BubbleDialogDelegate*>*) namespace views { namespace { // Some anchors may have multiple bubbles associated with them. This can happen // if a bubble does not have close_on_deactivate and another bubble appears // that needs the same anchor view. This property maintains a vector of bubbles // in anchored order where the last item is the primary anchored bubble. If the // last item is removed, the new last item, if available, is notified that it is // the new primary anchored bubble. DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::vector<views::BubbleDialogDelegate*>, kAnchorVector, nullptr) std::vector<BubbleDialogDelegate*>& GetAnchorVector(View* view) { if (!view->GetProperty(kAnchorVector)) { return *(view->SetProperty( kAnchorVector, std::make_unique<std::vector<BubbleDialogDelegate*>>())); } return *(view->GetProperty(kAnchorVector)); } // Override base functionality of Widget to give bubble dialogs access to the // theme provider of the window they're anchored to. class BubbleWidget : public Widget { public: BubbleWidget() = default; BubbleWidget(const BubbleWidget&) = delete; BubbleWidget& operator=(const BubbleWidget&) = delete; // Widget: const ui::ThemeProvider* GetThemeProvider() const override { const Widget* const anchor = GetAnchorWidget(); return anchor ? anchor->GetThemeProvider() : Widget::GetThemeProvider(); } ui::ColorProviderManager::ThemeInitializerSupplier* GetCustomTheme() const override { const Widget* const anchor = GetAnchorWidget(); return anchor ? anchor->GetCustomTheme() : Widget::GetCustomTheme(); } const ui::NativeTheme* GetNativeTheme() const override { const Widget* const anchor = GetAnchorWidget(); return anchor ? anchor->GetNativeTheme() : Widget::GetNativeTheme(); } Widget* GetPrimaryWindowWidget() override { Widget* const anchor = GetAnchorWidget(); return anchor ? anchor->GetPrimaryWindowWidget() : Widget::GetPrimaryWindowWidget(); } private: const Widget* GetAnchorWidget() const { // TODO(pbos): Could this use Widget::parent() instead of anchor_widget()? BubbleDialogDelegate* const bubble_delegate = static_cast<BubbleDialogDelegate*>(widget_delegate()); return bubble_delegate ? bubble_delegate->anchor_widget() : nullptr; } Widget* GetAnchorWidget() { return const_cast<Widget*>(std::as_const(*this).GetAnchorWidget()); } }; // The frame view for bubble dialog widgets. These are not user-sizable so have // simplified logic for minimum and maximum sizes to avoid repeated calls to // CalculatePreferredSize(). class BubbleDialogFrameView : public BubbleFrameView { public: explicit BubbleDialogFrameView(const gfx::Insets& title_margins) : BubbleFrameView(title_margins, gfx::Insets()) {} BubbleDialogFrameView(const BubbleDialogFrameView&) = delete; BubbleDialogFrameView& operator=(const BubbleDialogFrameView&) = delete; // View: gfx::Size GetMinimumSize() const override { return gfx::Size(); } gfx::Size GetMaximumSize() const override { return gfx::Size(); } }; // Create a widget to host the bubble. Widget* CreateBubbleWidget(BubbleDialogDelegate* bubble) { DCHECK(bubble->owned_by_widget()); Widget* bubble_widget = new BubbleWidget(); Widget::InitParams bubble_params(Widget::InitParams::TYPE_BUBBLE); bubble_params.delegate = bubble; bubble_params.opacity = Widget::InitParams::WindowOpacity::kTranslucent; bubble_params.accept_events = bubble->accept_events(); bubble_params.remove_standard_frame = true; bubble_params.layer_type = bubble->GetLayerType(); // Use a window default shadow if the bubble doesn't provides its own. if (bubble->GetShadow() == BubbleBorder::NO_SHADOW) bubble_params.shadow_type = Widget::InitParams::ShadowType::kDefault; else bubble_params.shadow_type = Widget::InitParams::ShadowType::kNone; #if BUILDFLAG(IS_CHROMEOS_ASH) bubble_params.background_elevation = ui::ColorProviderManager::ElevationMode::kHigh; #endif gfx::NativeView parent = nullptr; if (bubble->has_parent()) { if (bubble->parent_window()) { parent = bubble->parent_window(); } else if (bubble->anchor_widget()) { parent = bubble->anchor_widget()->GetNativeView(); } } bubble_params.parent = parent; bubble_params.activatable = bubble->CanActivate() ? Widget::InitParams::Activatable::kYes : Widget::InitParams::Activatable::kNo; bubble->OnBeforeBubbleWidgetInit(&bubble_params, bubble_widget); DCHECK(bubble_params.parent || !bubble->has_parent()); bubble_widget->Init(std::move(bubble_params)); #if !BUILDFLAG(IS_MAC) // On Mac, having a parent window creates a permanent stacking order, so // there's no need to do this. Also, calling StackAbove() on Mac shows the // bubble implicitly, for which the bubble is currently not ready. if (!base::FeatureList::IsEnabled(views::features::kWidgetLayering)) { if (bubble->has_parent() && parent) bubble_widget->StackAbove(parent); } #endif return bubble_widget; } } // namespace class BubbleDialogDelegate::AnchorViewObserver : public ViewObserver { public: AnchorViewObserver(BubbleDialogDelegate* parent, View* anchor_view) : parent_(parent), anchor_view_(anchor_view) { anchor_view_->AddObserver(this); AddToAnchorVector(); } AnchorViewObserver(const AnchorViewObserver&) = delete; AnchorViewObserver& operator=(const AnchorViewObserver&) = delete; ~AnchorViewObserver() override { RemoveFromAnchorVector(); anchor_view_->RemoveObserver(this); } View* anchor_view() const { return anchor_view_; } // ViewObserver: void OnViewIsDeleting(View* observed_view) override { // The anchor is being deleted, make sure the parent bubble no longer // observes it. DCHECK_EQ(anchor_view_, observed_view); parent_->SetAnchorView(nullptr); } void OnViewBoundsChanged(View* observed_view) override { // This code really wants to know the anchor bounds in screen coordinates // have changed. There isn't a good way to detect this outside of the view. // Observing View bounds changing catches some cases but not all of them. DCHECK_EQ(anchor_view_, observed_view); parent_->OnAnchorBoundsChanged(); } // TODO(pbos): Consider observing View visibility changes and only updating // view bounds when the anchor is visible. private: void AddToAnchorVector() { auto& vector = GetAnchorVector(anchor_view_); DCHECK(!base::Contains(vector, parent_)); vector.push_back(parent_); } void RemoveFromAnchorVector() { auto& vector = GetAnchorVector(anchor_view_); DCHECK(!vector.empty()); auto iter = vector.cend() - 1; bool latest_anchor_bubble_will_change = (*iter == parent_); if (!latest_anchor_bubble_will_change) iter = std::find(vector.cbegin(), iter, parent_); DCHECK(iter != vector.cend()); vector.erase(iter); if (!vector.empty() && latest_anchor_bubble_will_change) vector.back()->NotifyAnchoredBubbleIsPrimary(); } const raw_ptr<BubbleDialogDelegate> parent_; const raw_ptr<View> anchor_view_; }; // This class is responsible for observing events on a BubbleDialogDelegate's // anchor widget and notifying the BubbleDialogDelegate of them. #if BUILDFLAG(IS_MAC) class BubbleDialogDelegate::AnchorWidgetObserver : public WidgetObserver { #else class BubbleDialogDelegate::AnchorWidgetObserver : public WidgetObserver, public aura::WindowObserver { #endif public: AnchorWidgetObserver(BubbleDialogDelegate* owner, Widget* widget) : owner_(owner) { widget_observation_.Observe(widget); #if !BUILDFLAG(IS_MAC) window_observation_.Observe(widget->GetNativeWindow()); #endif } ~AnchorWidgetObserver() override = default; // WidgetObserver: void OnWidgetDestroying(Widget* widget) override { #if !BUILDFLAG(IS_MAC) DCHECK(window_observation_.IsObservingSource(widget->GetNativeWindow())); window_observation_.Reset(); #endif DCHECK(widget_observation_.IsObservingSource(widget)); widget_observation_.Reset(); owner_->OnAnchorWidgetDestroying(); // |this| may be destroyed here! } void OnWidgetActivationChanged(Widget* widget, bool active) override { owner_->OnWidgetActivationChanged(widget, active); } void OnWidgetBoundsChanged(Widget* widget, const gfx::Rect&) override { owner_->OnAnchorBoundsChanged(); } #if !BUILDFLAG(IS_MAC) // aura::WindowObserver: void OnWindowTransformed(aura::Window* window, ui::PropertyChangeReason reason) override { if (window->is_destroying()) return; // Update the anchor bounds when the transform animation is complete, or // when the transform is set without animation. if (!window->layer()->GetAnimator()->IsAnimatingOnePropertyOf( ui::LayerAnimationElement::TRANSFORM)) { owner_->OnAnchorBoundsChanged(); } } // If the native window is closed by the OS, OnWidgetDestroying() won't // fire. Instead, OnWindowDestroying() will fire before aura::Window // destruction. See //docs/ui/views/widget_destruction.md. void OnWindowDestroying(aura::Window* window) override { window_observation_.Reset(); } #endif private: raw_ptr<BubbleDialogDelegate> owner_; base::ScopedObservation<views::Widget, views::WidgetObserver> widget_observation_{this}; #if !BUILDFLAG(IS_MAC) base::ScopedObservation<aura::Window, aura::WindowObserver> window_observation_{this}; #endif }; // This class is responsible for observing events on a BubbleDialogDelegate's // widget and notifying the BubbleDialogDelegate of them. class BubbleDialogDelegate::BubbleWidgetObserver : public WidgetObserver { public: BubbleWidgetObserver(BubbleDialogDelegate* owner, Widget* widget) : owner_(owner) { observation_.Observe(widget); } ~BubbleWidgetObserver() override = default; void OnWidgetClosing(Widget* widget) override { owner_->OnBubbleWidgetClosing(); owner_->OnWidgetClosing(widget); } void OnWidgetDestroying(Widget* widget) override { owner_->OnWidgetDestroying(widget); } void OnWidgetDestroyed(Widget* widget) override { DCHECK(observation_.IsObservingSource(widget)); observation_.Reset(); owner_->OnWidgetDestroyed(widget); } void OnWidgetBoundsChanged(Widget* widget, const gfx::Rect& bounds) override { owner_->OnWidgetBoundsChanged(widget, bounds); } void OnWidgetVisibilityChanged(Widget* widget, bool visible) override { owner_->OnBubbleWidgetVisibilityChanged(visible); owner_->OnWidgetVisibilityChanged(widget, visible); } void OnWidgetActivationChanged(Widget* widget, bool active) override { owner_->OnBubbleWidgetActivationChanged(active); owner_->OnWidgetActivationChanged(widget, active); } private: const raw_ptr<BubbleDialogDelegate> owner_; base::ScopedObservation<views::Widget, views::WidgetObserver> observation_{ this}; }; class BubbleDialogDelegate::ThemeObserver : public ViewObserver { public: explicit ThemeObserver(BubbleDialogDelegate* delegate) : delegate_(delegate) { observation_.Observe(delegate->GetContentsView()); } void OnViewThemeChanged(views::View* view) override { delegate_->UpdateColorsFromTheme(); } private: const raw_ptr<BubbleDialogDelegate> delegate_; base::ScopedObservation<View, ViewObserver> observation_{this}; }; class BubbleDialogDelegateView::CloseOnDeactivatePin::Pins { public: Pins() = default; ~Pins() = default; bool is_pinned() const { return !pins_.empty(); } base::WeakPtr<Pins> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void AddPin(CloseOnDeactivatePin* pin) { const auto result = pins_.insert(pin); DCHECK(result.second); } void RemovePin(CloseOnDeactivatePin* pin) { const auto result = pins_.erase(pin); DCHECK(result); } protected: std::set<CloseOnDeactivatePin*> pins_; base::WeakPtrFactory<Pins> weak_ptr_factory_{this}; }; BubbleDialogDelegate::CloseOnDeactivatePin::CloseOnDeactivatePin( base::WeakPtr<Pins> pins) : pins_(pins) { pins_->AddPin(this); } BubbleDialogDelegate::CloseOnDeactivatePin::~CloseOnDeactivatePin() { Pins* const pins = pins_.get(); if (pins) pins->RemovePin(this); } BubbleDialogDelegate::BubbleDialogDelegate(View* anchor_view, BubbleBorder::Arrow arrow, BubbleBorder::Shadow shadow) : arrow_(arrow), shadow_(shadow), close_on_deactivate_pins_( std::make_unique<CloseOnDeactivatePin::Pins>()) { SetOwnedByWidget(true); SetAnchorView(anchor_view); SetArrow(arrow); SetShowCloseButton(false); LayoutProvider* const layout_provider = LayoutProvider::Get(); set_margins(layout_provider->GetDialogInsetsForContentType( DialogContentType::kText, DialogContentType::kText)); set_title_margins(layout_provider->GetInsetsMetric(INSETS_DIALOG_TITLE)); set_footnote_margins( layout_provider->GetInsetsMetric(INSETS_DIALOG_SUBSECTION)); RegisterWidgetInitializedCallback(base::BindOnce( [](BubbleDialogDelegate* bubble_delegate) { bubble_delegate->theme_observer_ = std::make_unique<ThemeObserver>(bubble_delegate); // Call the theme callback to make sure the initial theme is picked up // by the BubbleDialogDelegate. bubble_delegate->UpdateColorsFromTheme(); }, this)); } BubbleDialogDelegate::~BubbleDialogDelegate() { SetAnchorView(nullptr); } // static Widget* BubbleDialogDelegate::CreateBubble( std::unique_ptr<BubbleDialogDelegate> bubble_delegate_unique) { BubbleDialogDelegate* const bubble_delegate = bubble_delegate_unique.get(); DCHECK(bubble_delegate->owned_by_widget()); // On Mac, MODAL_TYPE_WINDOW is implemented using sheets, which can't be // anchored at a specific point - they are always placed near the top center // of the window. To avoid unpleasant surprises, disallow setting an anchor // view or rectangle on these types of bubbles. if (bubble_delegate->GetModalType() == ui::MODAL_TYPE_WINDOW) { DCHECK(!bubble_delegate->GetAnchorView()); DCHECK_EQ(bubble_delegate->GetAnchorRect(), gfx::Rect()); } bubble_delegate->Init(); // Get the latest anchor widget from the anchor view at bubble creation time. bubble_delegate->SetAnchorView(bubble_delegate->GetAnchorView()); Widget* const bubble_widget = CreateBubbleWidget(bubble_delegate_unique.release()); bubble_delegate->set_adjust_if_offscreen( PlatformStyle::kAdjustBubbleIfOffscreen); bubble_delegate->SizeToContents(); bubble_delegate->bubble_widget_observer_ = std::make_unique<BubbleWidgetObserver>(bubble_delegate, bubble_widget); return bubble_widget; } Widget* BubbleDialogDelegateView::CreateBubble( std::unique_ptr<BubbleDialogDelegateView> delegate) { return BubbleDialogDelegate::CreateBubble(std::move(delegate)); } Widget* BubbleDialogDelegateView::CreateBubble(BubbleDialogDelegateView* view) { return CreateBubble(base::WrapUnique(view)); } BubbleDialogDelegateView::BubbleDialogDelegateView() : BubbleDialogDelegateView(nullptr, BubbleBorder::TOP_LEFT) {} BubbleDialogDelegateView::BubbleDialogDelegateView(View* anchor_view, BubbleBorder::Arrow arrow, BubbleBorder::Shadow shadow) : BubbleDialogDelegate(anchor_view, arrow, shadow) {} BubbleDialogDelegateView::~BubbleDialogDelegateView() { // TODO(pbos): Investigate if this is actually still needed, and if so // document here why that's the case. If it's due to specific client layout // managers, push this down to client destructors. SetLayoutManager(nullptr); // TODO(pbos): See if we can resolve this better. This currently prevents a // crash that shows up in BubbleFrameViewTest.WidthSnaps. This crash seems to // happen at GetWidget()->IsVisible() inside SetAnchorView(nullptr) and seems // to be as a result of WidgetDelegate's widget_ not getting updated during // destruction when BubbleDialogDelegateView::DeleteDelegate() doesn't delete // itself, as Widget drops a reference to widget_delegate_ and can't inform it // of WidgetDeleting in ~Widget. SetAnchorView(nullptr); } BubbleDialogDelegate* BubbleDialogDelegate::AsBubbleDialogDelegate() { return this; } std::unique_ptr<NonClientFrameView> BubbleDialogDelegate::CreateNonClientFrameView(Widget* widget) { auto frame = std::make_unique<BubbleDialogFrameView>(title_margins_); frame->SetFootnoteMargins(footnote_margins_); frame->SetFootnoteView(DisownFootnoteView()); std::unique_ptr<BubbleBorder> border = std::make_unique<BubbleBorder>(arrow(), GetShadow()); border->SetColor(color()); if (GetParams().round_corners) { border->SetCornerRadius(GetCornerRadius()); } frame->SetBubbleBorder(std::move(border)); return frame; } ClientView* BubbleDialogDelegate::CreateClientView(Widget* widget) { client_view_ = DialogDelegate::CreateClientView(widget); // In order for the |client_view|'s content view hierarchy to respect its // rounded corner clip we must paint the client view to a layer. This is // necessary because layers do not respect the clip of a non-layer backed // parent. if (paint_client_to_layer_) { client_view_->SetPaintToLayer(); client_view_->layer()->SetRoundedCornerRadius( gfx::RoundedCornersF(GetCornerRadius())); client_view_->layer()->SetIsFastRoundedCorner(true); } return client_view_; } Widget* BubbleDialogDelegateView::GetWidget() { return View::GetWidget(); } const Widget* BubbleDialogDelegateView::GetWidget() const { return View::GetWidget(); } View* BubbleDialogDelegateView::GetContentsView() { return this; } void BubbleDialogDelegate::OnBubbleWidgetClosing() { // To prevent keyboard focus traversal issues, the anchor view's // kAnchoredDialogKey property is cleared immediately upon Close(). This // avoids a bug that occured when a focused anchor view is made unfocusable // right after the bubble is closed. Previously, focus would advance into the // bubble then would be lost when the bubble was destroyed. // // If kAnchoredDialogKey does not point to |this|, then |this| is not on the // focus traversal path. Don't reset kAnchoredDialogKey or we risk detaching // a widget from the traversal path. if (GetAnchorView() && GetAnchorView()->GetProperty(kAnchoredDialogKey) == this) GetAnchorView()->ClearProperty(kAnchoredDialogKey); } void BubbleDialogDelegate::OnAnchorWidgetDestroying() { SetAnchorView(nullptr); } void BubbleDialogDelegate::OnBubbleWidgetActivationChanged(bool active) { #if BUILDFLAG(IS_MAC) // Install |mac_bubble_closer_| the first time the widget becomes active. if (active && !mac_bubble_closer_) { mac_bubble_closer_ = std::make_unique<ui::BubbleCloser>( GetWidget()->GetNativeWindow().GetNativeNSWindow(), base::BindRepeating(&BubbleDialogDelegate::OnDeactivate, base::Unretained(this))); } #endif if (!active) OnDeactivate(); } void BubbleDialogDelegate::OnAnchorWidgetBoundsChanged() { if (GetBubbleFrameView()) SizeToContents(); } BubbleBorder::Shadow BubbleDialogDelegate::GetShadow() const { return shadow_; } View* BubbleDialogDelegate::GetAnchorView() const { if (!anchor_view_observer_) return nullptr; return anchor_view_observer_->anchor_view(); } void BubbleDialogDelegate::SetMainImage(ui::ImageModel main_image) { // Adding a main image while the bubble is showing is not supported (but // changing it is). Adding an image while it's showing would require a jarring // re-layout. if (main_image_.IsEmpty()) DCHECK(!GetBubbleFrameView()); main_image_ = std::move(main_image); if (GetBubbleFrameView()) GetBubbleFrameView()->UpdateMainImage(); } bool BubbleDialogDelegate::ShouldCloseOnDeactivate() const { return close_on_deactivate_ && !close_on_deactivate_pins_->is_pinned(); } std::unique_ptr<BubbleDialogDelegate::CloseOnDeactivatePin> BubbleDialogDelegate::PreventCloseOnDeactivate() { return base::WrapUnique( new CloseOnDeactivatePin(close_on_deactivate_pins_->GetWeakPtr())); } void BubbleDialogDelegate::SetHighlightedButton(Button* highlighted_button) { bool visible = GetWidget() && GetWidget()->IsVisible(); // If the Widget is visible, ensure the old highlight (if any) is removed // when the highlighted view changes. if (visible && highlighted_button != highlighted_button_tracker_.view()) UpdateHighlightedButton(false); highlighted_button_tracker_.SetView(highlighted_button); if (visible) UpdateHighlightedButton(true); } void BubbleDialogDelegate::SetArrow(BubbleBorder::Arrow arrow) { SetArrowWithoutResizing(arrow); // If SetArrow() is called before CreateWidget(), there's no need to update // the BubbleFrameView. if (GetBubbleFrameView()) SizeToContents(); } void BubbleDialogDelegate::SetArrowWithoutResizing(BubbleBorder::Arrow arrow) { if (base::i18n::IsRTL()) arrow = BubbleBorder::horizontal_mirror(arrow); if (arrow_ == arrow) return; arrow_ = arrow; // If SetArrow() is called before CreateWidget(), there's no need to update // the BubbleFrameView. if (GetBubbleFrameView()) GetBubbleFrameView()->SetArrow(arrow); } gfx::Rect BubbleDialogDelegate::GetAnchorRect() const { // TODO(tluk) eliminate the need for GetAnchorRect() to return an empty rect // if neither an |anchor_rect_| or an anchor view have been set. View* anchor_view = GetAnchorView(); if (!anchor_view) return anchor_rect_.value_or(gfx::Rect()); anchor_rect_ = anchor_view->GetAnchorBoundsInScreen(); #if !BUILDFLAG(IS_MAC) // GetAnchorBoundsInScreen returns values that take anchor widget's // translation into account, so undo that here. Without this, features which // apply transforms on windows such as ChromeOS overview mode will see bubbles // offset. // TODO(sammiequon): Investigate if we can remove |anchor_widget_| and just // replace its calls with anchor_view->GetWidget(). DCHECK_EQ(anchor_widget_, anchor_view->GetWidget()); if (anchor_widget_) { gfx::Transform transform = anchor_widget_->GetNativeWindow()->layer()->GetTargetTransform(); if (!transform.IsIdentity()) anchor_rect_->Offset( -gfx::ToRoundedVector2d(transform.To2dTranslation())); } #endif // Remove additional whitespace padding that was added to the view // so that anchor_rect centers on the anchor and not skewed by the whitespace BubbleFrameView* frame_view = GetBubbleFrameView(); if (frame_view && frame_view->GetDisplayVisibleArrow()) { gfx::Insets* padding = anchor_view->GetProperty(kInternalPaddingKey); if (padding != nullptr) anchor_rect_->Inset(*padding); } return anchor_rect_.value(); } SkColor BubbleDialogDelegate::GetBackgroundColor() { UpdateColorsFromTheme(); return color(); } ui::LayerType BubbleDialogDelegate::GetLayerType() const { return ui::LAYER_TEXTURED; } void BubbleDialogDelegate::SetPaintClientToLayer(bool paint_client_to_layer) { DCHECK(!client_view_); paint_client_to_layer_ = paint_client_to_layer; } void BubbleDialogDelegate::UseCompactMargins() { set_margins(gfx::Insets(6)); } // static gfx::Size BubbleDialogDelegate::GetMaxAvailableScreenSpaceToPlaceBubble( View* anchor_view, BubbleBorder::Arrow arrow, bool adjust_if_offscreen, BubbleFrameView::PreferredArrowAdjustment arrow_adjustment) { // TODO(sanchit.abrol@microsoft.com): Implement for other arrows. DCHECK(arrow == BubbleBorder::TOP_LEFT || arrow == BubbleBorder::TOP_RIGHT || arrow == BubbleBorder::BOTTOM_RIGHT || arrow == BubbleBorder::BOTTOM_LEFT); DCHECK_EQ(arrow_adjustment, BubbleFrameView::PreferredArrowAdjustment::kMirror); gfx::Rect anchor_rect = anchor_view->GetAnchorBoundsInScreen(); gfx::Rect screen_rect = display::Screen::GetScreen() ->GetDisplayNearestPoint(anchor_rect.CenterPoint()) .work_area(); gfx::Size max_available_space; if (adjust_if_offscreen) { max_available_space = GetAvailableSpaceToPlaceBubble( BubbleBorder::TOP_LEFT, anchor_rect, screen_rect); max_available_space.SetToMax(GetAvailableSpaceToPlaceBubble( BubbleBorder::TOP_RIGHT, anchor_rect, screen_rect)); max_available_space.SetToMax(GetAvailableSpaceToPlaceBubble( BubbleBorder::BOTTOM_RIGHT, anchor_rect, screen_rect)); max_available_space.SetToMax(GetAvailableSpaceToPlaceBubble( BubbleBorder::BOTTOM_LEFT, anchor_rect, screen_rect)); } else { max_available_space = GetAvailableSpaceToPlaceBubble(arrow, anchor_rect, screen_rect); } return max_available_space; } // static gfx::Size BubbleDialogDelegate::GetAvailableSpaceToPlaceBubble( BubbleBorder::Arrow arrow, gfx::Rect anchor_rect, gfx::Rect screen_rect) { int available_height_below = screen_rect.bottom() - anchor_rect.bottom(); int available_height_above = anchor_rect.y() - screen_rect.y(); int available_width_on_left = anchor_rect.right() - screen_rect.x(); int available_width_on_right = screen_rect.right() - anchor_rect.x(); return {BubbleBorder::is_arrow_on_left(arrow) ? available_width_on_right : available_width_on_left, BubbleBorder::is_arrow_on_top(arrow) ? available_height_below : available_height_above}; } void BubbleDialogDelegate::OnAnchorBoundsChanged() { if (!GetWidget()) return; // TODO(pbos): Reconsider whether to update the anchor when the view isn't // drawn. SizeToContents(); // We will not accept input event a short time after anchored view changed. UpdateInputProtectorsTimeStamp(); } void BubbleDialogDelegate::UpdateInputProtectorsTimeStamp() { if (auto* dialog = GetDialogClientView()) dialog->UpdateInputProtectorTimeStamp(); GetBubbleFrameView()->UpdateInputProtectorTimeStamp(); } gfx::Rect BubbleDialogDelegate::GetBubbleBounds() { // The argument rect has its origin at the bubble's arrow anchor point; // its size is the preferred size of the bubble's client view (this view). bool anchor_minimized = anchor_widget() && anchor_widget()->IsMinimized(); // If GetAnchorView() returns nullptr or GetAnchorRect() returns an empty rect // at (0, 0), don't try and adjust arrow if off-screen. gfx::Rect anchor_rect = GetAnchorRect(); bool has_anchor = GetAnchorView() || anchor_rect != gfx::Rect(); return GetBubbleFrameView()->GetUpdatedWindowBounds( anchor_rect, arrow(), GetWidget()->client_view()->GetPreferredSize(), adjust_if_offscreen_ && !anchor_minimized && has_anchor); } ax::mojom::Role BubbleDialogDelegate::GetAccessibleWindowRole() { const ax::mojom::Role accessible_role = WidgetDelegate::GetAccessibleWindowRole(); // If the accessible role has been explicitly set to anything else than its // default, use it. The rest translates kWindow to kDialog or kAlertDialog. if (accessible_role != ax::mojom::Role::kWindow) return accessible_role; // If something in the dialog has initial focus, use the dialog role. // Screen readers understand what to announce when focus moves within one. if (GetInitiallyFocusedView()) return ax::mojom::Role::kDialog; // Otherwise, return |ax::mojom::Role::kAlertDialog| which will make screen // readers announce the contents of the bubble dialog as soon as it appears, // as long as we also fire |ax::mojom::Event::kAlert|. return ax::mojom::Role::kAlertDialog; } gfx::Size BubbleDialogDelegateView::GetMinimumSize() const { // Note that although BubbleDialogFrameView will never invoke this, a subclass // may override CreateNonClientFrameView() to provide a NonClientFrameView // that does. See http://crbug.com/844359. return gfx::Size(); } gfx::Size BubbleDialogDelegateView::GetMaximumSize() const { return gfx::Size(); } void BubbleDialogDelegate::SetAnchorView(View* anchor_view) { if (anchor_view && anchor_view->GetWidget()) { anchor_widget_observer_ = std::make_unique<AnchorWidgetObserver>(this, anchor_view->GetWidget()); } else { anchor_widget_observer_.reset(); } if (GetAnchorView()) { if (GetAnchorView()->GetProperty(kAnchoredDialogKey) == this) GetAnchorView()->ClearProperty(kAnchoredDialogKey); anchor_view_observer_.reset(); } // When the anchor view gets set the associated anchor widget might // change as well. if (!anchor_view || anchor_widget() != anchor_view->GetWidget()) { if (anchor_widget()) { if (GetWidget() && GetWidget()->IsVisible()) UpdateHighlightedButton(false); anchor_widget_ = nullptr; } if (anchor_view) { anchor_widget_ = anchor_view->GetWidget(); if (anchor_widget_) { const bool visible = GetWidget() && GetWidget()->IsVisible(); UpdateHighlightedButton(visible); } } } if (anchor_view) { anchor_view_observer_ = std::make_unique<AnchorViewObserver>(this, anchor_view); // Do not update anchoring for NULL views; this could indicate // that our NativeWindow is being destroyed, so it would be // dangerous for us to update our anchor bounds at that // point. (It's safe to skip this, since if we were to update the // bounds when |anchor_view| is NULL, the bubble won't move.) OnAnchorBoundsChanged(); SetAnchoredDialogKey(); } } void BubbleDialogDelegate::SetAnchorRect(const gfx::Rect& rect) { anchor_rect_ = rect; if (GetWidget()) OnAnchorBoundsChanged(); } void BubbleDialogDelegate::SizeToContents() { gfx::Rect bubble_bounds = GetBubbleBounds(); #if BUILDFLAG(IS_MAC) // GetBubbleBounds() doesn't take the Mac NativeWindow's style mask into // account, so we need to adjust the size. gfx::Size actual_size = GetWindowSizeForClientSize(GetWidget(), bubble_bounds.size()); bubble_bounds.set_size(actual_size); #endif GetWidget()->SetBounds(bubble_bounds); } std::u16string BubbleDialogDelegate::GetSubtitle() const { return subtitle_; } void BubbleDialogDelegate::SetSubtitle(const std::u16string& subtitle) { if (subtitle_ == subtitle) return; subtitle_ = subtitle; BubbleFrameView* frame_view = GetBubbleFrameView(); if (frame_view) frame_view->UpdateSubtitle(); } void BubbleDialogDelegate::UpdateColorsFromTheme() { View* const contents_view = GetContentsView(); DCHECK(contents_view); if (!color_explicitly_set()) { set_color_internal(contents_view->GetColorProvider()->GetColor( ui::kColorBubbleBackground)); } BubbleFrameView* frame_view = GetBubbleFrameView(); if (frame_view) frame_view->SetBackgroundColor(color()); // When there's an opaque layer, the bubble border background won't show // through, so explicitly paint a background color. const bool contents_layer_opaque = contents_view->layer() && contents_view->layer()->fills_bounds_opaquely(); contents_view->SetBackground(contents_layer_opaque || force_create_contents_background_ ? CreateSolidBackground(color()) : nullptr); } void BubbleDialogDelegate::OnBubbleWidgetVisibilityChanged(bool visible) { UpdateHighlightedButton(visible); // Fire ax::mojom::Event::kAlert for bubbles marked as // ax::mojom::Role::kAlertDialog; this instructs accessibility tools to read // the bubble in its entirety rather than just its title and initially focused // view. See http://crbug.com/474622 for details. if (visible && ui::IsAlert(GetAccessibleWindowRole())) { GetWidget()->GetRootView()->NotifyAccessibilityEvent( ax::mojom::Event::kAlert, true); } } void BubbleDialogDelegate::OnDeactivate() { if (ShouldCloseOnDeactivate() && GetWidget()) GetWidget()->CloseWithReason(views::Widget::ClosedReason::kLostFocus); } void BubbleDialogDelegate::NotifyAnchoredBubbleIsPrimary() { const bool visible = GetWidget() && GetWidget()->IsVisible(); UpdateHighlightedButton(visible); SetAnchoredDialogKey(); } void BubbleDialogDelegate::SetAnchoredDialogKey() { auto* anchor_view = GetAnchorView(); DCHECK(anchor_view); if (focus_traversable_from_anchor_view_) { // Make sure that focus can move into here from the anchor view (but not // out, focus will cycle inside the dialog once it gets here). // It is possible that a view anchors more than one widgets, // but among them there should be at most one widget that is focusable. auto* old_anchored_dialog = anchor_view->GetProperty(kAnchoredDialogKey); if (old_anchored_dialog && old_anchored_dialog != this) DLOG(WARNING) << "|anchor_view| has already anchored a focusable widget."; anchor_view->SetProperty(kAnchoredDialogKey, static_cast<DialogDelegate*>(this)); } } void BubbleDialogDelegate::UpdateHighlightedButton(bool highlighted) { Button* button = Button::AsButton(highlighted_button_tracker_.view()); button = button ? button : Button::AsButton(GetAnchorView()); if (button && highlight_button_when_shown_) { if (highlighted) { button_anchor_higlight_ = button->AddAnchorHighlight(); } else { button_anchor_higlight_.reset(); } } } BEGIN_METADATA(BubbleDialogDelegateView, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_delegate_view.cc
C++
unknown
35,830
// 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_BUBBLE_BUBBLE_DIALOG_DELEGATE_VIEW_H_ #define UI_VIEWS_BUBBLE_BUBBLE_DIALOG_DELEGATE_VIEW_H_ #include <memory> #include <utility> #include "base/gtest_prod_util.h" #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 "ui/accessibility/ax_enums.mojom-forward.h" #include "ui/base/class_property.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view_tracker.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" #include "ui/views/window/dialog_delegate.h" #if BUILDFLAG(IS_MAC) #include "ui/base/cocoa/bubble_closer.h" #endif namespace gfx { class Rect; } namespace views { class Button; class VIEWS_EXPORT BubbleDialogDelegate : public DialogDelegate { public: BubbleDialogDelegate( View* anchor_view, BubbleBorder::Arrow arrow, BubbleBorder::Shadow shadow = BubbleBorder::DIALOG_SHADOW); BubbleDialogDelegate(const BubbleDialogDelegate& other) = delete; BubbleDialogDelegate& operator=(const BubbleDialogDelegate& other) = delete; ~BubbleDialogDelegate() override; // DialogDelegate: BubbleDialogDelegate* AsBubbleDialogDelegate() override; std::unique_ptr<NonClientFrameView> CreateNonClientFrameView( Widget* widget) override; ClientView* CreateClientView(Widget* widget) override; ax::mojom::Role GetAccessibleWindowRole() final; // Create and initialize the bubble Widget with proper bounds. static Widget* CreateBubble( std::unique_ptr<BubbleDialogDelegate> bubble_delegate); ////////////////////////////////////////////////////////////////////////////// // The anchor view and rectangle: // // The anchor view takes priority over the anchor rectangle. // If the anchor moves, BubbleDialogDelegate will move its Widget to maintain // the same position relative to its anchor. If an anchor view is used this // happens automatically; if an anchor rect is used, the new anchor rect needs // to be supplied via SetAnchorRect(). void SetAnchorView(View* view); View* GetAnchorView() const; void SetMainImage(ui::ImageModel main_image); const ui::ImageModel& GetMainImage() const { return main_image_; } // GetAnchorRect() takes into account the presence of an anchor view, while // anchor_rect() always returns the configured anchor rect, regardless of // whether there is also an anchor view. While it is possible to override // GetAnchorRect(), you should not need to do so; if you do, you must remember // to call OnAnchorBoundsChanged() when the return value of GetAnchorRect() // changes. // // TODO(ellyjones): Remove overrides of GetAnchorRect() and make this not // virtual. virtual gfx::Rect GetAnchorRect() const; const absl::optional<gfx::Rect>& anchor_rect() const { return anchor_rect_; } void SetAnchorRect(const gfx::Rect& rect); ////////////////////////////////////////////////////////////////////////////// // The anchor widget: // // The bubble will close when the anchor widget closes. Also, when the anchor // widget moves, the bubble will recompute its location from its anchor view. // The bubble will also cause its anchor widget to paint as active when the // bubble is active, and will optionally resize itself to fit within the // anchor widget if the anchor widget's size changes. // // The anchor widget is implied by the anchor view - bubbles with no anchor // view cannot be anchored to a widget. Widget* anchor_widget() { return anchor_widget_; } ////////////////////////////////////////////////////////////////////////////// // The arrow: // // Each bubble has an "arrow", which describes the relationship between the // bubble's position and the position of its anchor view. The arrow also // supplies the - anchor offset eg, a top-left arrow puts the bubble below and // to the right of the anchor view, and so on. The "arrow" name is a holdover // from an earlier time when the arrow was an actual visual marker on the // bubble's border as well, but these days the arrow has no visual presence. // // The arrow is automatically flipped in RTL locales, and by default is // manually adjusted if necessary to fit the bubble on screen. // Sets the desired arrow for the bubble and updates the bubble's bounds. void SetArrow(BubbleBorder::Arrow arrow); BubbleBorder::Arrow arrow() const { return arrow_; } // Sets the arrow without recalculating or updating bounds. This could be used // before another function call which also sets bounds, so that bounds are // not set multiple times in a row. When animating bounds changes, setting // bounds twice in a row can make the widget position jump. // TODO(crbug.com/982880) It would be good to be able to re-target the // animation rather than expect callers to use SetArrowWithoutResizing if they // are also changing the anchor rect, or similar. void SetArrowWithoutResizing(BubbleBorder::Arrow arrow); // Whether the arrow will be automatically adjusted if needed to fit the // bubble on screen. Has no effect if the bubble has no arrow. bool adjust_if_offscreen() const { return adjust_if_offscreen_; } void set_adjust_if_offscreen(bool adjust) { adjust_if_offscreen_ = adjust; } ////////////////////////////////////////////////////////////////////////////// // Shadows: // // Bubbles may optionally have a shadow. Only some platforms support drawing // custom shadows on a bubble. BubbleBorder::Shadow GetShadow() const; void set_shadow(BubbleBorder::Shadow shadow) { shadow_ = shadow; } // Call this method to inform BubbleDialogDelegate that the return value of // GetAnchorRect() has changed. You only need to do this if you have // overridden GetAnchorRect() - if you are using an anchor view or anchor rect // normally, do not call this. void OnAnchorBoundsChanged(); // Call this method to update view shown time stamp of underneath input // protectors. void UpdateInputProtectorsTimeStamp(); ////////////////////////////////////////////////////////////////////////////// // Subtitle: // // Bubbles have an optional a Subtitle label under the Title. // This subtitle label is represented in BubbleFrameView. // This method is virtual for BubbleFrameViewUnitTest purposes. // Not intended to be overridden in production. virtual std::u16string GetSubtitle() const; void SetSubtitle(const std::u16string& subtitle); ////////////////////////////////////////////////////////////////////////////// // Miscellaneous bubble behaviors: // // Represents a pin that prevents a widget from closing on deactivation, even // if `close_on_deactivate` is set to true. Prevents closing on deactivation // until its destruction; if it outlives the widget it does nothing. class VIEWS_EXPORT CloseOnDeactivatePin { public: virtual ~CloseOnDeactivatePin(); CloseOnDeactivatePin(const CloseOnDeactivatePin&) = delete; void operator=(const CloseOnDeactivatePin&) = delete; private: class Pins; friend class BubbleDialogDelegate; explicit CloseOnDeactivatePin(base::WeakPtr<Pins> pins); const base::WeakPtr<Pins> pins_; }; // Whether the bubble closes when it ceases to be the active window. void set_close_on_deactivate(bool close) { close_on_deactivate_ = close; } // Returns whether the bubble should close on deactivation. May not match // `close_on_deactivate` if PreventCloseOnDeactivate() has been called. bool ShouldCloseOnDeactivate() const; // Prevents close-on-deactivate for the duration of the lifetime of the pin // that is returned. The pin does nothing after the widget is closed. std::unique_ptr<CloseOnDeactivatePin> PreventCloseOnDeactivate(); // Explicitly set the button to automatically highlight when the bubble is // shown. By default the anchor is highlighted, if it is a button. // // TODO(ellyjones): Is there ever a situation where this is the right thing to // do UX-wise? It seems very odd to highlight something other than the anchor // view. void SetHighlightedButton(Button* highlighted_button); // The bubble's parent window - this can only be usefully set before creating // the bubble's widget. If there is one, the bubble will be stacked above it, // and it will become the Views parent window for the bubble. // // TODO(ellyjones): // - When does one actually need to call this? // - Why is it separate from the anchor widget? // - Why do most bubbles seem to work fine without this? gfx::NativeView parent_window() const { return parent_window_; } void set_parent_window(gfx::NativeView window) { parent_window_ = window; } bool has_parent() { return has_parent_; } void set_has_parent(bool has_parent) { has_parent_ = has_parent; } // Whether the bubble accepts mouse events or not. bool accept_events() const { return accept_events_; } void set_accept_events(bool accept_events) { accept_events_ = accept_events; } // Whether focus can traverse from the anchor view into the bubble. Only // meaningful if there is an anchor view. // TODO(pbos): See if this can be inferred from if the bubble is activatable // or if there's anything focusable within the dialog. This is currently used // for bubbles that should never receive focus and we should be able have // focus go through a bubble if nothing's focusable within it. Without this // set to `false`, the existence of an InfoBubble in the QR reader bubble will // break focus order in the parent dialog. This is a bug for which // set_focus_traversable_from_anchor_view(false) is used as a workaround. See // if fixing that bug removes the need for this for other dialogs. void set_focus_traversable_from_anchor_view(bool focusable) { focus_traversable_from_anchor_view_ = focusable; } // If this is true and either: // - The anchor View is a Button, or // - The highlighted Button is set, // then BubbleDialogDelegate will ask the anchor View / highlighted button to // highlight itself when the BubbleDialogDelegate's Widget is shown. void set_highlight_button_when_shown(bool highlight) { highlight_button_when_shown_ = highlight; } ////////////////////////////////////////////////////////////////////////////// // Layout & colors: // // In general you shouldn't need to call any setters. If the default bubble // look and feel does not work for your use case, BubbleDialogDelegate may not // be a good fit for the UI you are building. // Ensures the bubble's background color is up-to-date, then returns it. SkColor GetBackgroundColor(); // Direct access to the background color. Only use the getter when you know // you don't need to worry about the color being out-of-date due to a recent // theme update. SkColor color() const { return color_; } void set_color(SkColor color) { color_ = color; color_explicitly_set_ = true; } void set_force_create_contents_background( bool force_create_contents_background) { force_create_contents_background_ = force_create_contents_background; } void set_title_margins(const gfx::Insets& title_margins) { title_margins_ = title_margins; } gfx::Insets footnote_margins() const { return footnote_margins_; } void set_footnote_margins(const gfx::Insets& footnote_margins) { footnote_margins_ = footnote_margins; } // Sets whether or not CreateClientView() returns a Layer backed ClientView. // TODO(pbos): Remove all calls to this, then remove `paint_client_to_layer_`. // See comment around `paint_client_to_layer_`. void SetPaintClientToLayer(bool paint_client_to_layer); // Sets the content margins to a default picked for smaller bubbles. void UseCompactMargins(); // Override to configure the layer type of the bubble widget. virtual ui::LayerType GetLayerType() const; // Override to provide custom parameters before widget initialization. virtual void OnBeforeBubbleWidgetInit(Widget::InitParams* params, Widget* widget) const {} // Get the maximum available screen space to place a bubble anchored to // |anchor_view| at |arrow|. If offscreen adjustment is on, this would return // the max space corresponding to the possible arrow positions of the bubble. static gfx::Size GetMaxAvailableScreenSpaceToPlaceBubble( View* anchor_view, BubbleBorder::Arrow arrow, bool adjust_if_offscreen, BubbleFrameView::PreferredArrowAdjustment arrow_adjustment); // Get the available space to place a bubble anchored to |anchor_rect| at // |arrow| inside |screen_rect|. static gfx::Size GetAvailableSpaceToPlaceBubble(BubbleBorder::Arrow arrow, gfx::Rect anchor_rect, gfx::Rect screen_rect); // Resize the bubble to fit its contents, and maybe move it if needed to keep // it anchored properly. This does not need to be invoked normally. This // should be called only if you need to force update the bounds of the widget // and/or position of the bubble, for example if the size of the bubble's // content view changed. void SizeToContents(); protected: // Override this method if you want to position the bubble regardless of its // anchor, while retaining the other anchor view logic. virtual gfx::Rect GetBubbleBounds(); // Override this to perform initialization after the Widget is created but // before it is shown. // TODO(pbos): Turn this into a (Once?)Callback and add set_init(cb). virtual void Init() {} // TODO(ellyjones): Replace uses of this with uses of set_color(), and/or // otherwise get rid of this function. void set_color_internal(SkColor color) { color_ = color; } bool color_explicitly_set() const { return color_explicitly_set_; } // Redeclarations of virtuals that BubbleDialogDelegate used to inherit from // WidgetObserver. These should not exist; do not add new overrides of them. // They exist to allow the WidgetObserver helper classes inside // BubbleDialogDelegate (AnchorWidgetObserver and BubbleWidgetObserver) to // forward specific events to BubbleDialogDelegate subclasses that were // overriding WidgetObserver methods from BubbleDialogDelegate. Whether they // are called for the anchor widget or the bubble widget and when is // deliberately unspecified. // // TODO(ellyjones): Get rid of these. virtual void OnWidgetClosing(Widget* widget) {} virtual void OnWidgetDestroying(Widget* widget) {} virtual void OnWidgetActivationChanged(Widget* widget, bool active) {} virtual void OnWidgetDestroyed(Widget* widget) {} virtual void OnWidgetBoundsChanged(Widget* widget, const gfx::Rect& bounds) {} virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible) {} private: class AnchorViewObserver; class AnchorWidgetObserver; class BubbleWidgetObserver; class ThemeObserver; FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, VisibleWidgetShowsInkDropOnAttaching); FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, AttachedWidgetShowsInkDropWhenVisible); FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, MultipleBubbleAnchorHighlightTestInOrder); FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, MultipleBubbleAnchorHighlightTestOutOfOrder); friend class AnchorViewObserver; friend class AnchorWidgetObserver; friend class BubbleWidgetObserver; friend class ThemeObserver; friend class BubbleBorderDelegate; friend class BubbleWindowTargeter; // Notify the BubbleDialogDelegate about changes in the anchor Widget. You do // not need to call these yourself. void OnAnchorWidgetDestroying(); void OnAnchorWidgetBoundsChanged(); // Notify the BubbleDialogDelegate about changes in the bubble Widget. You do // not need to call these yourself. void OnBubbleWidgetClosing(); void OnBubbleWidgetVisibilityChanged(bool visible); void OnBubbleWidgetActivationChanged(bool active); void OnBubbleWidgetPaintAsActiveChanged(); void OnDeactivate(); // Update the bubble color from the NativeTheme unless it was explicitly set. void UpdateColorsFromTheme(); // Notify this bubble that it is now the primary anchored bubble. When a new // bubble becomes the primary anchor, the previous primary silently loses its // primary status. This method is only called when this bubble becomes primary // after losing it. void NotifyAnchoredBubbleIsPrimary(); void UpdateHighlightedButton(bool highlight); void SetAnchoredDialogKey(); gfx::Insets title_margins_; gfx::Insets footnote_margins_; BubbleBorder::Arrow arrow_ = BubbleBorder::NONE; BubbleBorder::Shadow shadow_; SkColor color_ = gfx::kPlaceholderColor; bool color_explicitly_set_ = false; raw_ptr<Widget, DanglingUntriaged> anchor_widget_ = nullptr; std::unique_ptr<AnchorViewObserver> anchor_view_observer_; std::unique_ptr<AnchorWidgetObserver> anchor_widget_observer_; std::unique_ptr<BubbleWidgetObserver> bubble_widget_observer_; std::unique_ptr<ThemeObserver> theme_observer_; bool adjust_if_offscreen_ = true; bool focus_traversable_from_anchor_view_ = true; ViewTracker highlighted_button_tracker_; ui::ImageModel main_image_; std::u16string subtitle_; // A flag controlling bubble closure on deactivation. bool close_on_deactivate_ = true; std::unique_ptr<CloseOnDeactivatePin::Pins> close_on_deactivate_pins_; // Whether the |anchor_widget_| (or the |highlighted_button_tracker_|, when // provided) should be highlighted when this bubble is shown. bool highlight_button_when_shown_ = true; mutable absl::optional<gfx::Rect> anchor_rect_; bool accept_events_ = true; gfx::NativeView parent_window_ = nullptr; // By default, all BubbleDialogDelegates have parent windows. bool has_parent_ = true; // Pointer to this bubble's ClientView. raw_ptr<ClientView> client_view_ = nullptr; // A BubbleFrameView will apply a masking path to its ClientView to ensure // contents are appropriately clipped to the frame's rounded corners. If the // bubble uses layers in its views hierarchy, these will not be clipped to // the client mask unless the ClientView is backed by a textured ui::Layer. // This flag tracks whether or not to to create a layer backed ClientView. // // TODO(tluk): Fix all cases where bubble transparency is used and have bubble // ClientViews always paint to a layer. // TODO(tluk): Flip this to true for all bubbles. bool paint_client_to_layer_ = false; // If true, contents view will be forced to create a solid color background in // UpdateColorsFromTheme(). bool force_create_contents_background_ = false; #if BUILDFLAG(IS_MAC) // Special handler for close_on_deactivate() on Mac. Window (de)activation is // suppressed by the WindowServer when clicking rapidly, so the bubble must // monitor clicks as well for the desired behavior. std::unique_ptr<ui::BubbleCloser> mac_bubble_closer_; #endif // Used to ensure the button remains anchored while this dialog is open. absl::optional<Button::ScopedAnchorHighlight> button_anchor_higlight_; }; // BubbleDialogDelegateView is a BubbleDialogDelegate that is also a View. // Prefer using a BubbleDialogDelegate that sets a separate View as its contents // view. // TODO(pbos): Migrate existing uses of BubbleDialogDelegateView to directly // inherit or use BubbleDialogDelegate. class VIEWS_EXPORT BubbleDialogDelegateView : public BubbleDialogDelegate, public View { public: METADATA_HEADER(BubbleDialogDelegateView); // Create and initialize the bubble Widget(s) with proper bounds. static Widget* CreateBubble( std::unique_ptr<BubbleDialogDelegateView> delegate); static Widget* CreateBubble(BubbleDialogDelegateView* bubble_delegate); BubbleDialogDelegateView(); // |shadow| usually doesn't need to be explicitly set, just uses the default // argument. Unless on Mac when the bubble needs to use Views base shadow, // override it with suitable bubble border type. BubbleDialogDelegateView( View* anchor_view, BubbleBorder::Arrow arrow, BubbleBorder::Shadow shadow = BubbleBorder::DIALOG_SHADOW); BubbleDialogDelegateView(const BubbleDialogDelegateView&) = delete; BubbleDialogDelegateView& operator=(const BubbleDialogDelegateView&) = delete; ~BubbleDialogDelegateView() override; // BubbleDialogDelegate: View* GetContentsView() override; // View: Widget* GetWidget() override; const Widget* GetWidget() const override; protected: // Disallow overrides of GetMinimumSize and GetMaximumSize(). These would only // be called by the FrameView, but the BubbleFrameView ignores these. Bubbles // are not user-sizable and always size to their preferred size (plus any // border / frame). // View: gfx::Size GetMinimumSize() const final; gfx::Size GetMaximumSize() const final; private: FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, CreateDelegate); FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, NonClientHitTest); }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, BubbleDialogDelegateView, View) VIEW_BUILDER_PROPERTY(ax::mojom::Role, AccessibleWindowRole) VIEW_BUILDER_PROPERTY(std::u16string, AccessibleTitle) VIEW_BUILDER_PROPERTY(bool, CanMaximize) VIEW_BUILDER_PROPERTY(bool, CanMinimize) VIEW_BUILDER_PROPERTY(bool, CanResize) VIEW_BUILDER_VIEW_TYPE_PROPERTY(views::View, ExtraView) VIEW_BUILDER_VIEW_TYPE_PROPERTY(views::View, FootnoteView) VIEW_BUILDER_PROPERTY(bool, FocusTraversesOut) VIEW_BUILDER_PROPERTY(bool, EnableArrowKeyTraversal) VIEW_BUILDER_PROPERTY(ui::ImageModel, Icon) VIEW_BUILDER_PROPERTY(ui::ImageModel, AppIcon) VIEW_BUILDER_PROPERTY(ui::ImageModel, MainImage) VIEW_BUILDER_PROPERTY(ui::ModalType, ModalType) VIEW_BUILDER_PROPERTY(bool, OwnedByWidget) VIEW_BUILDER_PROPERTY(bool, ShowCloseButton) VIEW_BUILDER_PROPERTY(bool, ShowIcon) VIEW_BUILDER_PROPERTY(bool, ShowTitle) VIEW_BUILDER_OVERLOAD_METHOD_CLASS(WidgetDelegate, SetTitle, const std::u16string&) VIEW_BUILDER_OVERLOAD_METHOD_CLASS(WidgetDelegate, SetTitle, int) #if defined(USE_AURA) VIEW_BUILDER_PROPERTY(bool, CenterTitle) #endif VIEW_BUILDER_PROPERTY(int, Buttons) VIEW_BUILDER_PROPERTY(int, DefaultButton) VIEW_BUILDER_METHOD(SetButtonLabel, ui::DialogButton, std::u16string) VIEW_BUILDER_METHOD(SetButtonEnabled, ui::DialogButton, bool) VIEW_BUILDER_METHOD(set_margins, gfx::Insets) VIEW_BUILDER_METHOD(set_use_round_corners, bool) VIEW_BUILDER_METHOD(set_corner_radius, int) VIEW_BUILDER_METHOD(set_draggable, bool) VIEW_BUILDER_METHOD(set_use_custom_frame, bool) VIEW_BUILDER_METHOD(set_fixed_width, int) VIEW_BUILDER_METHOD(set_highlight_button_when_shown, bool) VIEW_BUILDER_PROPERTY(base::OnceClosure, AcceptCallback) VIEW_BUILDER_PROPERTY(base::OnceClosure, CancelCallback) VIEW_BUILDER_PROPERTY(base::OnceClosure, CloseCallback) VIEW_BUILDER_PROPERTY(const gfx::Insets&, ButtonRowInsets) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, BubbleDialogDelegateView) #endif // UI_VIEWS_BUBBLE_BUBBLE_DIALOG_DELEGATE_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_delegate_view.h
C++
unknown
23,735
// 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/bubble/bubble_dialog_delegate_view.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" #include "ui/views/buildflags.h" #include "ui/views/test/widget_test.h" #include "ui/views/view.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/native_widget_aura.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(ENABLE_DESKTOP_AURA) #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #endif // BUILDFLAG(ENABLE_DESKTOP_AURA) namespace views { class BubbleDialogDelegateViewInteractiveTest : public test::WidgetTest { public: BubbleDialogDelegateViewInteractiveTest() = default; ~BubbleDialogDelegateViewInteractiveTest() override = default; void SetUp() override { SetUpForInteractiveTests(); test::WidgetTest::SetUp(); original_nw_factory_ = ViewsDelegate::GetInstance()->native_widget_factory(); #if !BUILDFLAG(IS_CHROMEOS_LACROS) ViewsDelegate::GetInstance()->set_native_widget_factory( base::BindRepeating(CreateNativeWidget)); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) } void TearDown() override { ViewsDelegate::GetInstance()->set_native_widget_factory( original_nw_factory_); test::WidgetTest::TearDown(); } private: static NativeWidget* CreateNativeWidget( const Widget::InitParams& params, internal::NativeWidgetDelegate* delegate) { #if BUILDFLAG(ENABLE_DESKTOP_AURA) // Create DesktopNativeWidgetAura for toplevel widgets, NativeWidgetAura // otherwise. if (!params.parent) return new DesktopNativeWidgetAura(delegate); #endif // BUILDFLAG(ENABLE_DESKTOP_AURA) return new NativeWidgetAura(delegate); } ViewsDelegate::NativeWidgetFactory original_nw_factory_; }; TEST_F(BubbleDialogDelegateViewInteractiveTest, BubbleAndParentNotActiveSimultaneously) { WidgetAutoclosePtr anchor_widget(CreateTopLevelNativeWidget()); View* anchor_view = anchor_widget->GetContentsView(); anchor_widget->LayoutRootViewIfNecessary(); test::WidgetActivationWaiter waiter(anchor_widget.get(), true); anchor_widget->Show(); waiter.Wait(); EXPECT_TRUE(anchor_widget->IsActive()); EXPECT_TRUE(anchor_widget->GetNativeWindow()->HasFocus()); auto bubble = std::make_unique<BubbleDialogDelegateView>( anchor_view, BubbleBorder::Arrow::TOP_CENTER); bubble->set_close_on_deactivate(false); WidgetAutoclosePtr bubble_widget( BubbleDialogDelegateView::CreateBubble(std::move(bubble))); bubble_widget->Show(); EXPECT_FALSE(anchor_widget->IsActive()); EXPECT_TRUE(bubble_widget->IsActive()); // TODO(crbug.com/1213139): We are not checking anchor_widget's // aura::Window because it might not get focus. This happens in test // suites that don't use FocusController on NativeWidgetAura. anchor_widget->Activate(); EXPECT_TRUE(anchor_widget->IsActive()); EXPECT_FALSE(bubble_widget->IsActive()); // Check the backing aura::Windows as well. EXPECT_TRUE(anchor_widget->GetNativeWindow()->HasFocus()); EXPECT_FALSE(bubble_widget->GetNativeWindow()->HasFocus()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_delegate_view_interactive_uitest_aura.cc
C++
unknown
3,403
// 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/bubble/bubble_dialog_delegate_view.h" #include <stddef.h> #include <memory> #include <string> #include <utility> #include "base/i18n/rtl.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/base/hit_test.h" #include "ui/display/test/test_screen.h" #include "ui/events/event_utils.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/test/ink_drop_host_test_api.h" #include "ui/views/animation/test/test_ink_drop.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/styled_label.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/button_test_api.h" #include "ui/views/test/test_views.h" #include "ui/views/test/test_widget_observer.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace views { using test::TestInkDrop; namespace { constexpr gfx::Size kContentSize = gfx::Size(200, 200); class TestBubbleDialogDelegateView : public BubbleDialogDelegateView { public: explicit TestBubbleDialogDelegateView(View* anchor_view) : BubbleDialogDelegateView(anchor_view, BubbleBorder::TOP_LEFT) { view_->SetFocusBehavior(FocusBehavior::ALWAYS); AddChildView(view_.get()); } ~TestBubbleDialogDelegateView() override = default; TestBubbleDialogDelegateView(const TestBubbleDialogDelegateView&) = delete; TestBubbleDialogDelegateView& operator=(const TestBubbleDialogDelegateView&) = delete; using BubbleDialogDelegateView::SetAnchorView; // BubbleDialogDelegateView overrides: View* GetInitiallyFocusedView() override { return view_; } gfx::Size CalculatePreferredSize() const override { return kContentSize; } void AddedToWidget() override { if (title_view_) GetBubbleFrameView()->SetTitleView(std::move(title_view_)); } std::u16string GetWindowTitle() const override { return u"TITLE TITLE TITLE"; } bool ShouldShowWindowTitle() const override { return should_show_window_title_; } bool ShouldShowCloseButton() const override { return should_show_close_button_; } template <typename T> T* set_title_view(std::unique_ptr<T> title_view) { T* const ret = title_view.get(); title_view_ = std::move(title_view); return ret; } void show_close_button() { should_show_close_button_ = true; } void hide_buttons() { should_show_close_button_ = false; DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE); } void set_should_show_window_title(bool should_show_window_title) { should_show_window_title_ = should_show_window_title; } using BubbleDialogDelegateView::GetBubbleFrameView; using BubbleDialogDelegateView::SetAnchorRect; using BubbleDialogDelegateView::SizeToContents; private: raw_ptr<View> view_ = new View; std::unique_ptr<View> title_view_; bool should_show_close_button_ = false; bool should_show_window_title_ = true; }; class TestAlertBubbleDialogDelegateView : public TestBubbleDialogDelegateView { public: explicit TestAlertBubbleDialogDelegateView(View* anchor_view) : TestBubbleDialogDelegateView(anchor_view) { SetAccessibleWindowRole(ax::mojom::Role::kAlertDialog); } ~TestAlertBubbleDialogDelegateView() override = default; }; // A Widget that returns something other than null as its ThemeProvider. This // allows us to see whether the theme provider returned by some object came from // this widget. class WidgetWithNonNullThemeProvider : public Widget { public: WidgetWithNonNullThemeProvider() = default; // Widget: const ui::ThemeProvider* GetThemeProvider() const override { return reinterpret_cast<ui::ThemeProvider*>(1); } }; class BubbleDialogDelegateViewTest : public ViewsTestBase { public: BubbleDialogDelegateViewTest() = default; BubbleDialogDelegateViewTest(const BubbleDialogDelegateViewTest&) = delete; BubbleDialogDelegateViewTest& operator=(const BubbleDialogDelegateViewTest&) = delete; ~BubbleDialogDelegateViewTest() override = default; std::unique_ptr<views::Widget> CreateTestWidget( views::Widget::InitParams::Type type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS) override { Widget::InitParams params = CreateParamsForTestWidget(type); auto widget = std::make_unique<WidgetWithNonNullThemeProvider>(); widget->Init(std::move(params)); widget->Show(); return widget; } }; } // namespace TEST_F(BubbleDialogDelegateViewTest, CreateDelegate) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->set_color(SK_ColorGREEN); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); test::TestWidgetObserver bubble_observer(bubble_widget); bubble_widget->Show(); BubbleBorder* border = bubble_delegate->GetBubbleFrameView()->bubble_border_; EXPECT_EQ(bubble_delegate->color(), border->color()); EXPECT_EQ(anchor_widget.get(), bubble_widget->parent()); EXPECT_FALSE(bubble_observer.widget_closed()); bubble_widget->CloseNow(); EXPECT_TRUE(bubble_observer.widget_closed()); } TEST_F(BubbleDialogDelegateViewTest, CloseAnchorWidget) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); // Preventing close on deactivate should not prevent closing with the anchor. bubble_delegate->set_close_on_deactivate(false); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); test::TestWidgetObserver bubble_observer(bubble_widget); EXPECT_FALSE(bubble_observer.widget_closed()); bubble_widget->Show(); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); EXPECT_FALSE(bubble_observer.widget_closed()); // TODO(msw): Remove activation hack to prevent bookkeeping errors in: // aura::test::TestActivationClient::OnWindowDestroyed(). std::unique_ptr<Widget> smoke_and_mirrors_widget = CreateTestWidget(); EXPECT_FALSE(bubble_observer.widget_closed()); // Ensure that closing the anchor widget also closes the bubble itself. anchor_widget->CloseNow(); EXPECT_TRUE(bubble_observer.widget_closed()); } // This test checks that the bubble delegate is capable to handle an early // destruction of the used anchor view. (Animations and delayed closure of the // bubble will call upon the anchor view to get its location). TEST_F(BubbleDialogDelegateViewTest, CloseAnchorViewTest) { // Create an anchor widget and add a view to be used as an anchor view. std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); View* anchor_view = anchor_widget->SetContentsView(std::make_unique<View>()); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_view); // Prevent flakes by avoiding closing on activation changes. bubble_delegate->set_close_on_deactivate(false); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); // Check that the anchor view is correct and set up an anchor view rect. // Make sure that this rect will get ignored (as long as the anchor view is // attached). EXPECT_EQ(anchor_view, bubble_delegate->GetAnchorView()); const gfx::Rect set_anchor_rect = gfx::Rect(10, 10, 100, 100); bubble_delegate->SetAnchorRect(set_anchor_rect); const gfx::Rect view_rect = bubble_delegate->GetAnchorRect(); EXPECT_NE(view_rect.ToString(), set_anchor_rect.ToString()); // Create the bubble. bubble_widget->Show(); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); // Remove now the anchor view and make sure that the original found rect // is still kept, so that the bubble does not jump when the view gets deleted. anchor_view->parent()->RemoveChildViewT(anchor_view); EXPECT_EQ(nullptr, bubble_delegate->GetAnchorView()); EXPECT_EQ(view_rect.ToString(), bubble_delegate->GetAnchorRect().ToString()); } // Testing that a move of the anchor view will lead to new bubble locations. TEST_F(BubbleDialogDelegateViewTest, TestAnchorRectMovesWithViewTest) { // Create an anchor widget and add a view to be used as anchor view. std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); BubbleDialogDelegateView::CreateBubble(bubble_delegate); anchor_widget->GetContentsView()->SetBounds(10, 10, 100, 100); const gfx::Rect view_rect = bubble_delegate->GetAnchorRect(); anchor_widget->GetContentsView()->SetBounds(20, 10, 100, 100); const gfx::Rect view_rect_2 = bubble_delegate->GetAnchorRect(); EXPECT_NE(view_rect.ToString(), view_rect_2.ToString()); } TEST_F(BubbleDialogDelegateViewTest, ResetAnchorWidget) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); // Make sure the bubble widget is parented to a widget other than the anchor // widget so that closing the anchor widget does not close the bubble widget. std::unique_ptr<Widget> parent_widget = CreateTestWidget(); bubble_delegate->set_parent_window(parent_widget->GetNativeView()); // Preventing close on deactivate should not prevent closing with the parent. bubble_delegate->set_close_on_deactivate(false); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); EXPECT_EQ(parent_widget.get(), bubble_widget->parent()); test::TestWidgetObserver bubble_observer(bubble_widget); EXPECT_FALSE(bubble_observer.widget_closed()); // Showing and hiding the bubble widget should have no effect on its anchor. bubble_widget->Show(); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); bubble_widget->Hide(); EXPECT_EQ(anchor_widget.get(), bubble_delegate->anchor_widget()); // Ensure that closing the anchor widget clears the bubble's reference to that // anchor widget, but the bubble itself does not close. anchor_widget->CloseNow(); EXPECT_NE(anchor_widget.get(), bubble_delegate->anchor_widget()); EXPECT_FALSE(bubble_observer.widget_closed()); // TODO(msw): Remove activation hack to prevent bookkeeping errors in: // aura::test::TestActivationClient::OnWindowDestroyed(). std::unique_ptr<Widget> smoke_and_mirrors_widget = CreateTestWidget(); EXPECT_FALSE(bubble_observer.widget_closed()); // Ensure that closing the parent widget also closes the bubble itself. parent_widget->CloseNow(); EXPECT_TRUE(bubble_observer.widget_closed()); } TEST_F(BubbleDialogDelegateViewTest, MultipleBubbleAnchorHighlightTestInOrder) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); LabelButton* button = anchor_widget->SetContentsView(std::make_unique<LabelButton>( Button::PressedCallback(), std::u16string())); TestInkDrop* ink_drop = new TestInkDrop(); test::InkDropHostTestApi(InkDrop::Get(button)) .SetInkDrop(base::WrapUnique(ink_drop)); TestBubbleDialogDelegateView* bubble_delegate_first = new TestBubbleDialogDelegateView(button); bubble_delegate_first->set_parent_window(anchor_widget->GetNativeView()); bubble_delegate_first->set_close_on_deactivate(false); Widget* bubble_widget_first = BubbleDialogDelegateView::CreateBubble(bubble_delegate_first); bubble_widget_first->Show(); bubble_delegate_first->OnBubbleWidgetVisibilityChanged(true); ASSERT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); TestBubbleDialogDelegateView* bubble_delegate_second = new TestBubbleDialogDelegateView(button); bubble_delegate_second->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget_second = BubbleDialogDelegateView::CreateBubble(bubble_delegate_second); bubble_widget_second->Show(); bubble_delegate_second->OnBubbleWidgetVisibilityChanged(true); ASSERT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_delegate_second->OnBubbleWidgetVisibilityChanged(false); bubble_widget_second->CloseNow(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_widget_first->Close(); bubble_delegate_first->OnBubbleWidgetVisibilityChanged(false); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(BubbleDialogDelegateViewTest, MultipleBubbleAnchorHighlightTestOutOfOrder) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); LabelButton* button = anchor_widget->SetContentsView(std::make_unique<LabelButton>( Button::PressedCallback(), std::u16string())); TestInkDrop* ink_drop = new TestInkDrop(); test::InkDropHostTestApi(InkDrop::Get(button)) .SetInkDrop(base::WrapUnique(ink_drop)); TestBubbleDialogDelegateView* bubble_delegate_first = new TestBubbleDialogDelegateView(button); bubble_delegate_first->set_parent_window(anchor_widget->GetNativeView()); bubble_delegate_first->set_close_on_deactivate(false); Widget* bubble_widget_first = BubbleDialogDelegateView::CreateBubble(bubble_delegate_first); bubble_widget_first->Show(); bubble_delegate_first->OnBubbleWidgetVisibilityChanged(true); ASSERT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); TestBubbleDialogDelegateView* bubble_delegate_second = new TestBubbleDialogDelegateView(button); bubble_delegate_second->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget_second = BubbleDialogDelegateView::CreateBubble(bubble_delegate_second); bubble_widget_second->Show(); bubble_delegate_second->OnBubbleWidgetVisibilityChanged(true); ASSERT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_widget_first->CloseNow(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_widget_second->Close(); bubble_delegate_second->OnBubbleWidgetVisibilityChanged(false); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(BubbleDialogDelegateViewTest, NoParentWidget) { test_views_delegate()->set_use_desktop_native_widgets(true); #if BUILDFLAG(IS_CHROMEOS) test_views_delegate()->set_context(GetContext()); #endif BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(nullptr); bubble_delegate->set_has_parent(false); WidgetAutoclosePtr bubble_widget( BubbleDialogDelegateView::CreateBubble(bubble_delegate)); EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); EXPECT_EQ(bubble_widget.get(), bubble_delegate->GetWidget()); EXPECT_EQ(nullptr, bubble_widget->parent()); } TEST_F(BubbleDialogDelegateViewTest, InitiallyFocusedView) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); EXPECT_EQ(bubble_delegate->GetInitiallyFocusedView(), bubble_widget->GetFocusManager()->GetFocusedView()); bubble_widget->CloseNow(); } TEST_F(BubbleDialogDelegateViewTest, NonClientHitTest) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); BubbleDialogDelegateView::CreateBubble(bubble_delegate); BubbleFrameView* frame = bubble_delegate->GetBubbleFrameView(); struct { const int point; const int hit; } kTestCases[] = { {0, HTTRANSPARENT}, {60, HTCLIENT}, {1000, HTNOWHERE}, }; for (const auto& test_case : kTestCases) { gfx::Point point(test_case.point, test_case.point); EXPECT_EQ(test_case.hit, frame->NonClientHitTest(point)) << " at point " << test_case.point; } } TEST_F(BubbleDialogDelegateViewTest, VisibleWhenAnchorWidgetBoundsChanged) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); test::TestWidgetObserver bubble_observer(bubble_widget); EXPECT_FALSE(bubble_observer.widget_closed()); bubble_widget->Show(); EXPECT_TRUE(bubble_widget->IsVisible()); anchor_widget->SetBounds(gfx::Rect(10, 10, 100, 100)); EXPECT_TRUE(bubble_widget->IsVisible()); } TEST_F(BubbleDialogDelegateViewTest, GetPrimaryWindowWidget) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); EXPECT_EQ(anchor_widget.get(), anchor_widget->GetPrimaryWindowWidget()); EXPECT_EQ(anchor_widget.get(), bubble_widget->GetPrimaryWindowWidget()); } // Test that setting WidgetDelegate::SetCanActivate() to false makes the // widget created via BubbleDialogDelegateView::CreateBubble() not activatable. TEST_F(BubbleDialogDelegateViewTest, NotActivatable) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->SetCanActivate(false); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); EXPECT_FALSE(bubble_widget->CanActivate()); } TEST_F(BubbleDialogDelegateViewTest, CloseMethods) { { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->set_close_on_deactivate(true); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); anchor_widget->Activate(); EXPECT_TRUE(bubble_widget->IsClosed()); } { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); ui::KeyEvent escape_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, ui::EF_NONE); bubble_widget->OnKeyEvent(&escape_event); EXPECT_TRUE(bubble_widget->IsClosed()); } { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); BubbleFrameView* frame_view = bubble_delegate->GetBubbleFrameView(); frame_view->ResetViewShownTimeStampForTesting(); Button* close_button = frame_view->close_; ASSERT_TRUE(close_button); test::ButtonTestApi(close_button) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE)); EXPECT_TRUE(bubble_widget->IsClosed()); } } TEST_F(BubbleDialogDelegateViewTest, PinBlocksCloseOnDeactivate) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->set_close_on_deactivate(true); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); // Pin the bubble so it does not go away on loss of focus. auto pin = bubble_delegate->PreventCloseOnDeactivate(); bubble_widget->Show(); anchor_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); // Unpin the window. The next time the bubble loses activation, it should // close as expected. pin.reset(); bubble_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); anchor_widget->Activate(); EXPECT_TRUE(bubble_widget->IsClosed()); } TEST_F(BubbleDialogDelegateViewTest, CloseOnDeactivatePinCanOutliveBubble) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->set_close_on_deactivate(true); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); // Pin the bubble so it does not go away on loss of focus. auto pin = bubble_delegate->PreventCloseOnDeactivate(); bubble_widget->Show(); anchor_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); bubble_widget->CloseNow(); pin.reset(); } TEST_F(BubbleDialogDelegateViewTest, MultipleCloseOnDeactivatePins) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); BubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); bubble_delegate->set_close_on_deactivate(true); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); // Pin the bubble so it does not go away on loss of focus. auto pin = bubble_delegate->PreventCloseOnDeactivate(); auto pin2 = bubble_delegate->PreventCloseOnDeactivate(); bubble_widget->Show(); anchor_widget->Activate(); // Unpinning one pin does not reset the state; both must be unpinned. pin.reset(); bubble_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); anchor_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); // Fully unpin the window. The next time the bubble loses activation, // it should close as expected. pin2.reset(); bubble_widget->Activate(); EXPECT_FALSE(bubble_widget->IsClosed()); anchor_widget->Activate(); EXPECT_TRUE(bubble_widget->IsClosed()); } TEST_F(BubbleDialogDelegateViewTest, CustomTitle) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); constexpr int kTitleHeight = 20; View* title_view = bubble_delegate->set_title_view( std::make_unique<StaticSizedView>(gfx::Size(10, kTitleHeight))); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); BubbleFrameView* bubble_frame = static_cast<BubbleFrameView*>( bubble_widget->non_client_view()->frame_view()); EXPECT_EQ(title_view, bubble_frame->title()); View* title_container = title_view->parent(); EXPECT_EQ(bubble_frame, title_container->parent()); // Title takes up the whole bubble width when there's no icon or close button. EXPECT_EQ(bubble_delegate->width(), title_view->size().width()); EXPECT_EQ(kTitleHeight, title_view->size().height()); bubble_delegate->show_close_button(); bubble_frame->ResetWindowControls(); bubble_frame->InvalidateLayout(); views::test::RunScheduledLayout(bubble_frame); Button* close_button = bubble_frame->GetCloseButtonForTesting(); // Title moves over for the close button. EXPECT_EQ(close_button->x() - LayoutProvider::Get()->GetDistanceMetric( DISTANCE_CLOSE_BUTTON_MARGIN), title_container->bounds().right()); LayoutProvider* provider = LayoutProvider::Get(); const gfx::Insets content_margins = provider->GetDialogInsetsForContentType( views::DialogContentType::kText, views::DialogContentType::kText); const gfx::Insets title_margins = provider->GetInsetsMetric(INSETS_DIALOG_TITLE); EXPECT_EQ(content_margins, bubble_delegate->margins()); // Note there is no title_margins() accessor (it should not be customizable). // To perform checks on the precise size, first hide the dialog buttons so the // calculations are simpler (e.g. platform font discrepancies can be ignored). bubble_delegate->hide_buttons(); bubble_frame->ResetWindowControls(); bubble_delegate->DialogModelChanged(); bubble_delegate->SizeToContents(); // Use GetContentsBounds() to exclude the bubble border, which can change per // platform. gfx::Rect frame_size = bubble_frame->GetContentsBounds(); EXPECT_EQ(content_margins.height() + kContentSize.height() + title_margins.height() + kTitleHeight, frame_size.height()); EXPECT_EQ(content_margins.width() + kContentSize.width(), frame_size.width()); // Set the title preferred size to 0. The bubble frame makes fewer assumptions // about custom title views, so there should still be margins for it while the // WidgetDelegate says it should be shown, even if its preferred size is zero. title_view->SetPreferredSize(gfx::Size()); bubble_widget->UpdateWindowTitle(); bubble_delegate->SizeToContents(); frame_size = bubble_frame->GetContentsBounds(); EXPECT_EQ( content_margins.height() + kContentSize.height() + title_margins.height(), frame_size.height()); EXPECT_EQ(content_margins.width() + kContentSize.width(), frame_size.width()); // Now hide the title properly. The margins should also disappear. bubble_delegate->set_should_show_window_title(false); bubble_widget->UpdateWindowTitle(); bubble_delegate->SizeToContents(); frame_size = bubble_frame->GetContentsBounds(); EXPECT_EQ(content_margins.height() + kContentSize.height(), frame_size.height()); EXPECT_EQ(content_margins.width() + kContentSize.width(), frame_size.width()); } // Ensure the BubbleFrameView correctly resizes when the title is provided by a // StyledLabel. TEST_F(BubbleDialogDelegateViewTest, StyledLabelTitle) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); StyledLabel* title_view = bubble_delegate->set_title_view(std::make_unique<StyledLabel>()); title_view->SetText(u"123"); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); const gfx::Size size_before_new_title = bubble_widget->GetWindowBoundsInScreen().size(); title_view->SetText(u"12"); bubble_delegate->SizeToContents(); // A shorter title should change nothing, since both will be within the // minimum dialog width. EXPECT_EQ(size_before_new_title, bubble_widget->GetWindowBoundsInScreen().size()); title_view->SetText(base::UTF8ToUTF16(std::string(200, '0'))); bubble_delegate->SizeToContents(); // A (much) longer title should increase the height, but not the width. EXPECT_EQ(size_before_new_title.width(), bubble_widget->GetWindowBoundsInScreen().width()); EXPECT_LT(size_before_new_title.height(), bubble_widget->GetWindowBoundsInScreen().height()); } // Ensure associated buttons are highlighted or unhighlighted when the bubble // widget is shown or hidden respectively. TEST_F(BubbleDialogDelegateViewTest, AttachedWidgetShowsInkDropWhenVisible) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); LabelButton* button = anchor_widget->SetContentsView(std::make_unique<LabelButton>( Button::PressedCallback(), std::u16string())); TestInkDrop* ink_drop = new TestInkDrop(); test::InkDropHostTestApi(InkDrop::Get(button)) .SetInkDrop(base::WrapUnique(ink_drop)); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(nullptr); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_delegate->SetHighlightedButton(button); bubble_widget->Show(); // Explicitly calling OnWidgetVisibilityChanging to test functionality for // OS_WIN. Outside of the test environment this happens automatically by way // of HWNDMessageHandler. bubble_delegate->OnBubbleWidgetVisibilityChanged(true); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_widget->Close(); bubble_delegate->OnBubbleWidgetVisibilityChanged(false); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } // Ensure associated buttons are highlighted or unhighlighted when the bubble // widget is shown or hidden respectively when highlighted button is set after // widget is shown. TEST_F(BubbleDialogDelegateViewTest, VisibleWidgetShowsInkDropOnAttaching) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); LabelButton* button = anchor_widget->SetContentsView(std::make_unique<LabelButton>( Button::PressedCallback(), std::u16string())); TestInkDrop* ink_drop = new TestInkDrop(); test::InkDropHostTestApi(InkDrop::Get(button)) .SetInkDrop(base::WrapUnique(ink_drop)); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(nullptr); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); // Explicitly calling OnWidgetVisibilityChanged to test functionality for // OS_WIN. Outside of the test environment this happens automatically by way // of HWNDMessageHandler. bubble_delegate->OnBubbleWidgetVisibilityChanged(true); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); bubble_delegate->SetHighlightedButton(button); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); bubble_widget->Close(); bubble_delegate->OnBubbleWidgetVisibilityChanged(false); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(BubbleDialogDelegateViewTest, VisibleAnchorChanges) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(nullptr); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); EXPECT_TRUE(anchor_widget->ShouldPaintAsActive()); bubble_widget->Hide(); } TEST_F(BubbleDialogDelegateViewTest, GetThemeProvider_FromAnchorWidget) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(); TestBubbleDialogDelegateView* bubble_delegate = new TestBubbleDialogDelegateView(nullptr); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_delegate); bubble_widget->Show(); EXPECT_NE(bubble_widget->GetThemeProvider(), anchor_widget->GetThemeProvider()); bubble_delegate->SetAnchorView(anchor_widget->GetRootView()); EXPECT_EQ(bubble_widget->GetThemeProvider(), anchor_widget->GetThemeProvider()); } const int kScreenWidth = 1024; const int kScreenHeight = 768; struct ArrowTestParameters { views::BubbleBorder::Arrow arrow; bool adjust_if_offscreen; gfx::Rect anchor_rect; views::BubbleBorder::Arrow expected_arrow; gfx::Size ExpectedSpace() const { gfx::Rect adjusted_anchor_rect = anchor_rect; adjusted_anchor_rect.Offset( 0, ViewsTestBase::GetSystemReservedHeightAtTopOfScreen()); gfx::Rect screen_rect = gfx::Rect(0, 0, kScreenWidth, kScreenHeight); return BubbleDialogDelegate::GetAvailableSpaceToPlaceBubble( expected_arrow, adjusted_anchor_rect, screen_rect); } }; class BubbleDialogDelegateViewArrowTest : public BubbleDialogDelegateViewTest, public testing::WithParamInterface<ArrowTestParameters> { public: BubbleDialogDelegateViewArrowTest() { SetUpTestScreen(); } BubbleDialogDelegateViewArrowTest(const BubbleDialogDelegateViewArrowTest&) = delete; BubbleDialogDelegateViewArrowTest& operator=( const BubbleDialogDelegateViewArrowTest&) = delete; ~BubbleDialogDelegateViewArrowTest() override { display::Screen::SetScreenInstance(nullptr); } private: void SetUpTestScreen() { DCHECK(!display::test::TestScreen::Get()); test_screen_ = std::make_unique<display::test::TestScreen>(); display::Screen::SetScreenInstance(test_screen_.get()); const display::Display test_display = test_screen_->GetPrimaryDisplay(); display::Display display(test_display); display.set_id(0x2); display.set_bounds(gfx::Rect(0, 0, kScreenWidth, kScreenHeight)); display.set_work_area(gfx::Rect(0, 0, kScreenWidth, kScreenHeight)); test_screen_->display_list().RemoveDisplay(test_display.id()); test_screen_->display_list().AddDisplay( display, display::DisplayList::Type::PRIMARY); } std::unique_ptr<display::test::TestScreen> test_screen_; }; TEST_P(BubbleDialogDelegateViewArrowTest, AvailableScreenSpaceTest) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); auto* bubble_delegate = new TestBubbleDialogDelegateView(anchor_widget->GetContentsView()); BubbleDialogDelegateView::CreateBubble(bubble_delegate); EXPECT_EQ(bubble_delegate->adjust_if_offscreen(), PlatformStyle::kAdjustBubbleIfOffscreen); const ArrowTestParameters kParam = GetParam(); bubble_delegate->SetArrow(kParam.arrow); bubble_delegate->set_adjust_if_offscreen(kParam.adjust_if_offscreen); anchor_widget->GetContentsView()->SetBounds( kParam.anchor_rect.x(), kParam.anchor_rect.y(), kParam.anchor_rect.width(), kParam.anchor_rect.height()); gfx::Size available_space = BubbleDialogDelegate::GetMaxAvailableScreenSpaceToPlaceBubble( bubble_delegate->GetAnchorView(), bubble_delegate->arrow(), bubble_delegate->adjust_if_offscreen(), BubbleFrameView::PreferredArrowAdjustment::kMirror); EXPECT_EQ(available_space, kParam.ExpectedSpace()); } const int kAnchorFarRightX = 840; const int kAnchorFarLeftX = 75; const int kAnchorFarTopY = 57; const int kAnchorFarBottomY = 730; const int kAnchorLength = 28; // When the anchor rect is positioned at different places Rect(x, y, // kAnchorLength, kAnchorLength) with (x,y) set to far corners of the screen, // available space to position the bubble should vary acc. to // |adjust_if_offscreen_|. const ArrowTestParameters kAnchorAtFarScreenCornersParams[] = { // Arrow at Top Right, no arrow adjustment needed {views::BubbleBorder::Arrow::TOP_RIGHT, true, gfx::Rect(kAnchorFarRightX, kAnchorFarTopY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::TOP_RIGHT}, // Max size available when arrow is changed to Bottom Right {views::BubbleBorder::Arrow::TOP_RIGHT, true, gfx::Rect(kAnchorFarRightX, kAnchorFarBottomY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::BOTTOM_RIGHT}, // Max size available when arrow is changed to Bottom Left {views::BubbleBorder::Arrow::TOP_RIGHT, true, gfx::Rect(kAnchorFarLeftX, kAnchorFarBottomY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::BOTTOM_LEFT}, // Max size available when arrow is changed to Top Left {views::BubbleBorder::Arrow::TOP_RIGHT, true, gfx::Rect(kAnchorFarLeftX, kAnchorFarTopY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::TOP_LEFT}, // Offscreen adjustment is off, available size is per Bottom Left // arrow {views::BubbleBorder::Arrow::BOTTOM_LEFT, false, gfx::Rect(kAnchorFarRightX, kAnchorFarTopY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::BOTTOM_LEFT}, // Offscreen adjustment is off, available size is per Top Left arrow {views::BubbleBorder::Arrow::TOP_LEFT, false, gfx::Rect(kAnchorFarRightX, kAnchorFarBottomY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::TOP_LEFT}, // Offscreen adjustment is off, available size is per Top Right arrow {views::BubbleBorder::Arrow::TOP_RIGHT, false, gfx::Rect(kAnchorFarLeftX, kAnchorFarBottomY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::TOP_RIGHT}, // Offscreen adjustment is off, available size is per Bottom Right // arrow {views::BubbleBorder::Arrow::BOTTOM_RIGHT, false, gfx::Rect(kAnchorFarLeftX, kAnchorFarTopY, kAnchorLength, kAnchorLength), views::BubbleBorder::Arrow::BOTTOM_RIGHT}}; INSTANTIATE_TEST_SUITE_P(AnchorAtFarScreenCorners, BubbleDialogDelegateViewArrowTest, testing::ValuesIn(kAnchorAtFarScreenCornersParams)); // Tests whether the BubbleDialogDelegateView will create a layer backed // ClientView when SetPaintClientToLayer is set to true. TEST_F(BubbleDialogDelegateViewTest, WithClientLayerTest) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); auto bubble_delegate = std::make_unique<BubbleDialogDelegateView>( nullptr, BubbleBorder::TOP_LEFT); bubble_delegate->SetPaintClientToLayer(true); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); WidgetAutoclosePtr bubble_widget( BubbleDialogDelegateView::CreateBubble(std::move(bubble_delegate))); EXPECT_NE(nullptr, bubble_widget->client_view()->layer()); } // Tests to ensure BubbleDialogDelegateView does not create a layer backed // ClientView when SetPaintClientToLayer is set to false. TEST_F(BubbleDialogDelegateViewTest, WithoutClientLayerTest) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); auto bubble_delegate = std::make_unique<BubbleDialogDelegateView>( nullptr, BubbleBorder::TOP_LEFT); bubble_delegate->SetPaintClientToLayer(false); bubble_delegate->set_parent_window(anchor_widget->GetNativeView()); WidgetAutoclosePtr bubble_widget( BubbleDialogDelegateView::CreateBubble(std::move(bubble_delegate))); EXPECT_EQ(nullptr, bubble_widget->client_view()->layer()); } TEST_F(BubbleDialogDelegateViewTest, AlertAccessibleEvent) { views::test::AXEventCounter counter(views::AXEventManager::Get()); std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); auto bubble_delegate = std::make_unique<TestBubbleDialogDelegateView>( anchor_widget->GetContentsView()); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert)); Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(std::move(bubble_delegate)); bubble_widget->Show(); // Bubbles with kDialog accessible role don't produce this event EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert)); auto alert_bubble_delegate = std::make_unique<TestAlertBubbleDialogDelegateView>( anchor_widget->GetContentsView()); Widget* alert_bubble_widget = BubbleDialogDelegateView::CreateBubble(std::move(alert_bubble_delegate)); alert_bubble_widget->Show(); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kAlert)); } // Anchoring Tests ------------------------------------------------------------- namespace { class AnchorTestBubbleDialogDelegateView : public BubbleDialogDelegateView { public: explicit AnchorTestBubbleDialogDelegateView(View* anchor_view) : BubbleDialogDelegateView(anchor_view, BubbleBorder::TOP_LEFT) {} AnchorTestBubbleDialogDelegateView( const AnchorTestBubbleDialogDelegateView&) = delete; AnchorTestBubbleDialogDelegateView& operator=( const AnchorTestBubbleDialogDelegateView&) = delete; ~AnchorTestBubbleDialogDelegateView() override = default; // DialogDelegate: // Avoid engaging the AX focus system on bubble activation. The AX focus // system is not fully initialized for these tests and can cause crashes. View* GetInitiallyFocusedView() override { return nullptr; } using BubbleDialogDelegateView::SetAnchorView; }; // Provides functionality for testing bubble anchoring logic. // Deriving from widget test provides some nice out-of-the-box functionality for // creating and managing widgets. class BubbleDialogDelegateViewAnchorTest : public test::WidgetTest { public: BubbleDialogDelegateViewAnchorTest() = default; BubbleDialogDelegateViewAnchorTest( const BubbleDialogDelegateViewAnchorTest&) = delete; BubbleDialogDelegateViewAnchorTest& operator=( const BubbleDialogDelegateViewAnchorTest&) = delete; ~BubbleDialogDelegateViewAnchorTest() override = default; // Anchors a bubble widget to another widget. void Anchor(Widget* bubble_widget, Widget* anchor_to) { Widget::ReparentNativeView(bubble_widget->GetNativeView(), anchor_to->GetNativeView()); static_cast<AnchorTestBubbleDialogDelegateView*>( bubble_widget->widget_delegate()) ->SetAnchorView(GetAnchorView(anchor_to)); } // Creates a test bubble dialog widget. If |anchor_to| is not specified, uses // dummy_widget(). Widget* CreateBubble(Widget* anchor_to = nullptr) { if (!anchor_to) anchor_to = dummy_widget(); View* const anchor_view = anchor_to ? GetAnchorView(anchor_to) : nullptr; auto* bubble_delegate = new AnchorTestBubbleDialogDelegateView(anchor_view); bubble_delegate->set_close_on_deactivate(false); return BubbleDialogDelegateView::CreateBubble(bubble_delegate); } WidgetAutoclosePtr CreateTopLevelWidget() { return WidgetAutoclosePtr(CreateTopLevelPlatformWidget()); } // test::WidgetTest: void SetUp() override { WidgetTest::SetUp(); dummy_widget_.reset(CreateTopLevelPlatformWidget()); dummy_widget_->Show(); } void TearDown() override { dummy_widget_.reset(); WidgetTest::TearDown(); } protected: // Provides a widget that can be used to anchor bubbles or take focus away // from the widgets actually being used in each test. Widget* dummy_widget() const { return dummy_widget_.get(); } private: View* GetAnchorView(Widget* widget) { View* const contents_view = widget->GetContentsView(); DCHECK(contents_view); return contents_view; } WidgetAutoclosePtr dummy_widget_; }; } // namespace TEST_F(BubbleDialogDelegateViewAnchorTest, AnchoredToWidgetShouldPaintAsActive) { auto widget = CreateTopLevelWidget(); widget->ShowInactive(); EXPECT_FALSE(widget->ShouldPaintAsActive()); auto* bubble = CreateBubble(); bubble->Show(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); Anchor(bubble, widget.get()); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, AnchoredToWidgetBecomesActiveWhenBubbleIsShown) { auto widget = CreateTopLevelWidget(); widget->ShowInactive(); EXPECT_FALSE(widget->ShouldPaintAsActive()); auto* bubble = CreateBubble(widget.get()); bubble->Show(); EXPECT_TRUE(bubble->ShouldPaintAsActive()); EXPECT_TRUE(widget->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, ActiveStatePersistsAcrossAnchorWidgetAndBubbleActivation) { auto widget = CreateTopLevelWidget(); widget->ShowInactive(); auto* bubble = CreateBubble(widget.get()); bubble->ShowInactive(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); // Toggle activation back and forth between widgets. bubble->Activate(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); widget->Activate(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); bubble->Activate(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); dummy_widget()->Show(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, AnchoringAlreadyActiveBubbleChangesAnchorWidgetState) { auto widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(); widget->Show(); bubble->ShowInactive(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); Anchor(bubble, widget.get()); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); bubble->Close(); EXPECT_TRUE(widget->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, ActivationPassesToRemainingWidgetOnBubbleClose) { auto widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(); widget->ShowInactive(); bubble->Show(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); Anchor(bubble, widget.get()); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); widget->Activate(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); bubble->Close(); EXPECT_TRUE(widget->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, ActivationPassesToOtherWidgetOnReanchor) { auto widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(); widget->Show(); bubble->ShowInactive(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); Anchor(bubble, widget.get()); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); bubble->Activate(); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); Anchor(bubble, dummy_widget()); EXPECT_FALSE(widget->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, ActivationPassesAcrossChainOfAnchoredBubbles) { auto widget = CreateTopLevelWidget(); auto other_widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(); auto* bubble2 = CreateBubble(); widget->ShowInactive(); // Initially, both bubbles are parented to dummy_widget(). bubble->ShowInactive(); bubble2->Show(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); EXPECT_TRUE(bubble2->ShouldPaintAsActive()); // Change the bubble's parent to |widget|. Anchor(bubble, widget.get()); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); EXPECT_TRUE(bubble2->ShouldPaintAsActive()); Anchor(bubble2, bubble); EXPECT_TRUE(widget->ShouldPaintAsActive()); EXPECT_TRUE(bubble->ShouldPaintAsActive()); EXPECT_TRUE(bubble2->ShouldPaintAsActive()); other_widget->Show(); EXPECT_FALSE(widget->ShouldPaintAsActive()); EXPECT_FALSE(bubble->ShouldPaintAsActive()); EXPECT_FALSE(bubble2->ShouldPaintAsActive()); } TEST_F(BubbleDialogDelegateViewAnchorTest, DestroyingAnchoredToWidgetDoesNotCrash) { auto widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(widget.get()); widget->Show(); bubble->Show(); widget.reset(); } TEST_F(BubbleDialogDelegateViewAnchorTest, DestroyingMiddleWidgetOfAnchorChainDoesNotCrash) { auto widget = CreateTopLevelWidget(); auto* bubble = CreateBubble(); auto* bubble2 = CreateBubble(); widget->Show(); bubble->ShowInactive(); bubble2->Show(); Anchor(bubble, widget.get()); Anchor(bubble2, bubble); bubble->Close(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_delegate_view_unittest.cc
C++
unknown
49,362
// 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/bubble/bubble_dialog_model_host.h" #include <utility> #include "base/memory/raw_ptr.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/class_property.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/models/combobox_model.h" #include "ui/base/models/dialog_model.h" #include "ui/base/models/dialog_model_field.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/separator.h" #include "ui/views/controls/styled_label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/theme_tracking_image_view.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_provider.h" #include "ui/views/style/typography.h" #include "ui/views/view_class_properties.h" namespace views { namespace { // Extra margin to be added to contents view when it's inside a scroll view. constexpr int kScrollViewVerticalMargin = 2; BubbleDialogModelHost::ContentsView* SetAndGetContentsView( BubbleDialogModelHost* parent, ui::ModalType modal_type) { const bool is_modal_dialog = modal_type != ui::MODAL_TYPE_NONE; auto contents_view_unique = std::make_unique<BubbleDialogModelHost::ContentsView>(parent, is_modal_dialog); BubbleDialogModelHost::ContentsView* contents_view = contents_view_unique.get(); // TODO(crbug.com/1348165): Non modal dialogs size is not dependent on its // content. Thus, the content has to be manually set by the view inside a // scroll view. Modal dialogs handle their own size via constrained windows, // so we can add a scroll view to the DialogModel directly. if (is_modal_dialog) { constexpr int kMaxDialogHeight = 448; auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->ClipHeightTo(0, kMaxDialogHeight); scroll_view->SetHorizontalScrollBarMode( views::ScrollView::ScrollBarMode::kDisabled); scroll_view->SetContents(std::move(contents_view_unique)); parent->SetContentsView(std::move(scroll_view)); } else { parent->SetContentsView(std::move(contents_view_unique)); } return contents_view; } BubbleDialogModelHost::FieldType GetFieldTypeForField( ui::DialogModelField* field, base::PassKey<ui::DialogModelHost> pass_key) { DCHECK(field); switch (field->type(pass_key)) { case ui::DialogModelField::kButton: return BubbleDialogModelHost::FieldType::kControl; case ui::DialogModelField::kParagraph: return BubbleDialogModelHost::FieldType::kText; case ui::DialogModelField::kCheckbox: return BubbleDialogModelHost::FieldType::kControl; case ui::DialogModelField::kTextfield: return BubbleDialogModelHost::FieldType::kControl; case ui::DialogModelField::kCombobox: return BubbleDialogModelHost::FieldType::kControl; case ui::DialogModelField::kMenuItem: return BubbleDialogModelHost::FieldType::kMenuItem; case ui::DialogModelField::kSeparator: return BubbleDialogModelHost::FieldType::kMenuItem; case ui::DialogModelField::kCustom: return static_cast<BubbleDialogModelHost::CustomView*>( field->AsCustomField(pass_key)->field(pass_key)) ->field_type(); } } int GetFieldTopMargin(LayoutProvider* layout_provider, const BubbleDialogModelHost::FieldType& field_type, const BubbleDialogModelHost::FieldType& last_field_type) { DCHECK(layout_provider); // Menu item preceded by non-menu item should have margin if (field_type == BubbleDialogModelHost::FieldType::kMenuItem && last_field_type == BubbleDialogModelHost::FieldType::kMenuItem) { return 0; } if (field_type == BubbleDialogModelHost::FieldType::kControl && last_field_type == BubbleDialogModelHost::FieldType::kControl) { // TODO(pbos): Move DISTANCE_CONTROL_LIST_VERTICAL to views::LayoutProvider // and replace "12" here. return 12; } return layout_provider->GetDistanceMetric( DISTANCE_UNRELATED_CONTROL_VERTICAL); } int GetDialogTopMargins(LayoutProvider* layout_provider, ui::DialogModelField* first_field, base::PassKey<ui::DialogModelHost> pass_key) { const BubbleDialogModelHost::FieldType field_type = first_field ? GetFieldTypeForField(first_field, pass_key) : BubbleDialogModelHost::FieldType::kControl; switch (field_type) { case BubbleDialogModelHost::FieldType::kMenuItem: return 0; case BubbleDialogModelHost::FieldType::kControl: return layout_provider->GetDistanceMetric( DISTANCE_DIALOG_CONTENT_MARGIN_TOP_CONTROL); case BubbleDialogModelHost::FieldType::kText: return layout_provider->GetDistanceMetric( DISTANCE_DIALOG_CONTENT_MARGIN_TOP_TEXT); } } int GetDialogBottomMargins(LayoutProvider* layout_provider, ui::DialogModelField* last_field, bool has_buttons, base::PassKey<ui::DialogModelHost> pass_key) { const BubbleDialogModelHost::FieldType field_type = last_field ? GetFieldTypeForField(last_field, pass_key) : BubbleDialogModelHost::FieldType::kControl; switch (field_type) { case BubbleDialogModelHost::FieldType::kMenuItem: return has_buttons ? layout_provider->GetDistanceMetric( DISTANCE_DIALOG_CONTENT_MARGIN_BOTTOM_CONTROL) : 0; case BubbleDialogModelHost::FieldType::kControl: return layout_provider->GetDistanceMetric( DISTANCE_DIALOG_CONTENT_MARGIN_BOTTOM_CONTROL); case BubbleDialogModelHost::FieldType::kText: return layout_provider->GetDistanceMetric( DISTANCE_DIALOG_CONTENT_MARGIN_BOTTOM_TEXT); } } // A subclass of Checkbox that allows using an external Label/StyledLabel view // instead of LabelButton's internal label. This is required for the // Label/StyledLabel to be clickable, while supporting Links which requires a // StyledLabel. class CheckboxControl : public Checkbox { public: METADATA_HEADER(CheckboxControl); CheckboxControl(std::unique_ptr<View> label, int label_line_height) : label_line_height_(label_line_height) { auto* layout = SetLayoutManager(std::make_unique<BoxLayout>()); layout->set_between_child_spacing(LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_LABEL_HORIZONTAL)); layout->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kStart); // TODO(accessibility): There is no `SetAccessibilityProperties` which takes // a labelling view to set the accessible name. SetAccessibleName(label.get()); AddChildView(std::move(label)); } void Layout() override { // Skip LabelButton to use LayoutManager. View::Layout(); } gfx::Size CalculatePreferredSize() const override { // Skip LabelButton to use LayoutManager. return View::CalculatePreferredSize(); } int GetHeightForWidth(int width) const override { // Skip LabelButton to use LayoutManager. return View::GetHeightForWidth(width); } void OnThemeChanged() override { Checkbox::OnThemeChanged(); // This offsets the image to align with the first line of text. See // LabelButton::Layout(). image()->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR( (label_line_height_ - image()->GetPreferredSize().height()) / 2, 0, 0, 0))); } const int label_line_height_; }; BEGIN_METADATA(CheckboxControl, Checkbox) END_METADATA } // namespace BubbleDialogModelHost::CustomView::CustomView(std::unique_ptr<View> view, FieldType field_type) : view_(std::move(view)), field_type_(field_type) {} BubbleDialogModelHost::CustomView::~CustomView() = default; std::unique_ptr<View> BubbleDialogModelHost::CustomView::TransferView() { DCHECK(view_); return std::move(view_); } // TODO(pbos): Migrate most code that calls contents_view_->(some View method) // into this class. This was done in steps to limit the size of the diff. class BubbleDialogModelHost::ContentsView : public BoxLayoutView { public: ContentsView(BubbleDialogModelHost* parent, bool is_modal_dialog) : parent_(parent) { // Note that between-child spacing is manually handled using kMarginsKey. SetOrientation(views::BoxLayout::Orientation::kVertical); // Margins are added directly in the dialog. When the dialog is modal, these // contents are wrapped by a scroll view and margins are added outside of it // (instead of outside this contents). This causes some items (e.g // emphasized buttons) to be cut by the scroll view margins (see // crbug.com/1360772). Since we do want the margins outside the scroll view // (so they are always present when scrolling), we add // `kScrollViewVerticalMargin` inside the contents view and later remove it // from the dialog margins. // TODO(crbug.com/1348165): Remove this workaround when contents view // directly supports a scroll view. if (is_modal_dialog) SetInsideBorderInsets(gfx::Insets::VH(kScrollViewVerticalMargin, 0)); } void OnThemeChanged() override { View::OnThemeChanged(); if (!parent_->ShouldShowWindowIcon()) return; const ui::ImageModel dark_mode_icon = parent_->model_->dark_mode_icon(parent_->GetPassKey()); if (!dark_mode_icon.IsEmpty() && color_utils::IsDark(parent_->GetBackgroundColor())) { parent_->SetIcon(dark_mode_icon); return; } parent_->SetIcon(parent_->model_->icon(GetPassKey())); } private: const raw_ptr<BubbleDialogModelHost, DanglingUntriaged> parent_; }; class BubbleDialogModelHost::LayoutConsensusView : public View { public: METADATA_HEADER(LayoutConsensusView); LayoutConsensusView(LayoutConsensusGroup* group, std::unique_ptr<View> view) : group_(group) { group->AddView(this); SetLayoutManager(std::make_unique<FillLayout>()); AddChildView(std::move(view)); } ~LayoutConsensusView() override { group_->RemoveView(this); } gfx::Size CalculatePreferredSize() const override { const gfx::Size group_preferred_size = group_->GetMaxPreferredSize(); DCHECK_EQ(1u, children().size()); const gfx::Size child_preferred_size = children()[0]->GetPreferredSize(); // TODO(pbos): This uses the max width, but could be configurable to use // either direction. return gfx::Size(group_preferred_size.width(), child_preferred_size.height()); } gfx::Size GetMinimumSize() const override { const gfx::Size group_minimum_size = group_->GetMaxMinimumSize(); DCHECK_EQ(1u, children().size()); const gfx::Size child_minimum_size = children()[0]->GetMinimumSize(); // TODO(pbos): This uses the max width, but could be configurable to use // either direction. return gfx::Size(group_minimum_size.width(), child_minimum_size.height()); } private: const raw_ptr<LayoutConsensusGroup> group_; }; BEGIN_METADATA(BubbleDialogModelHost, LayoutConsensusView, View) END_METADATA BubbleDialogModelHost::LayoutConsensusGroup::LayoutConsensusGroup() = default; BubbleDialogModelHost::LayoutConsensusGroup::~LayoutConsensusGroup() { DCHECK(children_.empty()); } void BubbleDialogModelHost::LayoutConsensusGroup::AddView( LayoutConsensusView* view) { children_.insert(view); // Because this may change the max preferred/min size, invalidate all child // layouts. for (auto* child : children_) child->InvalidateLayout(); } void BubbleDialogModelHost::LayoutConsensusGroup::RemoveView( LayoutConsensusView* view) { children_.erase(view); } gfx::Size BubbleDialogModelHost::LayoutConsensusGroup::GetMaxPreferredSize() const { gfx::Size size; for (auto* child : children_) { DCHECK_EQ(1u, child->children().size()); size.SetToMax(child->children().front()->GetPreferredSize()); } return size; } gfx::Size BubbleDialogModelHost::LayoutConsensusGroup::GetMaxMinimumSize() const { gfx::Size size; for (auto* child : children_) { DCHECK_EQ(1u, child->children().size()); size.SetToMax(child->children().front()->GetMinimumSize()); } return size; } BubbleDialogModelHost::BubbleDialogModelHost( std::unique_ptr<ui::DialogModel> model, View* anchor_view, BubbleBorder::Arrow arrow) : BubbleDialogModelHost(base::PassKey<BubbleDialogModelHost>(), std::move(model), anchor_view, arrow, ui::ModalType::MODAL_TYPE_NONE) {} BubbleDialogModelHost::BubbleDialogModelHost( base::PassKey<BubbleDialogModelHost>, std::unique_ptr<ui::DialogModel> model, View* anchor_view, BubbleBorder::Arrow arrow, ui::ModalType modal_type) : BubbleDialogDelegate(anchor_view, arrow), model_(std::move(model)), contents_view_(SetAndGetContentsView(this, modal_type)) { model_->set_host(GetPassKey(), this); // Note that this needs to be called before IsModalDialog() is called later in // this constructor. SetModalType(modal_type); // Dialog callbacks can safely refer to |model_|, they can't be called after // Widget::Close() calls WidgetWillClose() synchronously so there shouldn't // be any dangling references after model removal. SetAcceptCallback(base::BindOnce(&ui::DialogModel::OnDialogAcceptAction, base::Unretained(model_.get()), GetPassKey())); SetCancelCallback(base::BindOnce(&ui::DialogModel::OnDialogCancelAction, base::Unretained(model_.get()), GetPassKey())); SetCloseCallback(base::BindOnce(&ui::DialogModel::OnDialogCloseAction, base::Unretained(model_.get()), GetPassKey())); // WindowClosingCallback happens on native widget destruction which is after // |model_| reset. Hence routing this callback through |this| so that we only // forward the call to DialogModel::OnWindowClosing if we haven't already been // closed. RegisterWindowClosingCallback(base::BindOnce( &BubbleDialogModelHost::OnWindowClosing, base::Unretained(this))); int button_mask = ui::DIALOG_BUTTON_NONE; auto* ok_button = model_->ok_button(GetPassKey()); if (ok_button) { button_mask |= ui::DIALOG_BUTTON_OK; if (!ok_button->label(GetPassKey()).empty()) SetButtonLabel(ui::DIALOG_BUTTON_OK, ok_button->label(GetPassKey())); } auto* cancel_button = model_->cancel_button(GetPassKey()); if (cancel_button) { button_mask |= ui::DIALOG_BUTTON_CANCEL; if (!cancel_button->label(GetPassKey()).empty()) SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, cancel_button->label(GetPassKey())); } // TODO(pbos): Consider refactoring ::SetExtraView() so it can be called after // the Widget is created and still be picked up. Moving this to // OnWidgetInitialized() will not work until then. if (ui::DialogModelButton* extra_button = model_->extra_button(GetPassKey())) { DCHECK(!model_->extra_link(GetPassKey())); SetExtraView(std::make_unique<MdTextButton>( base::BindRepeating(&ui::DialogModelButton::OnPressed, base::Unretained(extra_button), GetPassKey()), extra_button->label(GetPassKey()))); } else if (ui::DialogModelLabel::TextReplacement* extra_link = model_->extra_link(GetPassKey())) { DCHECK(extra_link->callback().has_value()); auto link = std::make_unique<views::Link>(extra_link->text()); link->SetCallback(extra_link->callback().value()); SetExtraView(std::move(link)); } SetButtons(button_mask); if (model_->override_default_button(GetPassKey())) SetDefaultButton(model_->override_default_button(GetPassKey()).value()); SetTitle(model_->title(GetPassKey())); if (!model_->accessible_title(GetPassKey()).empty()) { SetAccessibleTitle(model_->accessible_title(GetPassKey())); } SetSubtitle(model_->subtitle(GetPassKey())); if (!model_->main_image(GetPassKey()).IsEmpty()) SetMainImage(model_->main_image(GetPassKey())); if (model_->override_show_close_button(GetPassKey())) { SetShowCloseButton(*model_->override_show_close_button(GetPassKey())); } else { SetShowCloseButton(!IsModalDialog()); } if (!model_->icon(GetPassKey()).IsEmpty()) { SetIcon(model_->icon(GetPassKey())); SetShowIcon(true); } if (model_->is_alert_dialog(GetPassKey())) { #if BUILDFLAG(IS_WIN) // This is taken from LocationBarBubbleDelegateView. See // GetAccessibleRoleForReason(). crbug.com/1125118: Windows ATs only // announce these bubbles if the alert role is used, despite it not being // the most appropriate choice. // TODO(accessibility): review the role mappings for alerts and dialogs, // making sure they are translated to the best candidate in each flatform // without resorting to hacks like this. SetAccessibleWindowRole(ax::mojom::Role::kAlert); #else SetAccessibleWindowRole(ax::mojom::Role::kAlertDialog); #endif } set_internal_name(model_->internal_name(GetPassKey())); set_close_on_deactivate(model_->close_on_deactivate(GetPassKey())); // TODO(pbos): Reconsider this for dialogs which have no actions (look like // menus). This is probably too wide for the TabGroupEditorBubbleView which is // currently being converted. set_fixed_width(LayoutProvider::Get()->GetDistanceMetric( anchor_view ? DISTANCE_BUBBLE_PREFERRED_WIDTH : DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH)); AddInitialFields(); } BubbleDialogModelHost::~BubbleDialogModelHost() { // Remove children as they may refer to the soon-to-be-destructed model. contents_view_->RemoveAllChildViews(); } std::unique_ptr<BubbleDialogModelHost> BubbleDialogModelHost::CreateModal( std::unique_ptr<ui::DialogModel> model, ui::ModalType modal_type) { DCHECK_NE(modal_type, ui::MODAL_TYPE_NONE); return std::make_unique<BubbleDialogModelHost>( base::PassKey<BubbleDialogModelHost>(), std::move(model), nullptr, BubbleBorder::Arrow::NONE, modal_type); } View* BubbleDialogModelHost::GetInitiallyFocusedView() { // TODO(pbos): Migrate this override to use // WidgetDelegate::SetInitiallyFocusedView() in constructor once it exists. // TODO(pbos): Try to prevent uses of GetInitiallyFocusedView() after Close() // and turn this in to a DCHECK for |model_| existence. This should fix // https://crbug.com/1130181 for now. if (!model_) return BubbleDialogDelegate::GetInitiallyFocusedView(); // TODO(pbos): Reconsider the uniqueness requirement, maybe this should select // the first one? If so add corresponding GetFirst query to DialogModel. ui::ElementIdentifier unique_id = model_->initially_focused_field(GetPassKey()); if (!unique_id) return BubbleDialogDelegate::GetInitiallyFocusedView(); return GetTargetView( FindDialogModelHostField(model_->GetFieldByUniqueId(unique_id))); } void BubbleDialogModelHost::OnWidgetInitialized() { // Dialog buttons are added on dialog initialization. if (GetOkButton()) { AddDialogModelHostFieldForExistingView( {model_->ok_button(GetPassKey()), GetOkButton(), nullptr}); } if (GetCancelButton()) { AddDialogModelHostFieldForExistingView( {model_->cancel_button(GetPassKey()), GetCancelButton(), nullptr}); } if (model_->extra_button(GetPassKey())) { DCHECK(GetExtraView()); AddDialogModelHostFieldForExistingView( {model_->extra_button(GetPassKey()), GetExtraView(), nullptr}); } if (const ui::ImageModel& banner = model_->banner(GetPassKey()); !banner.IsEmpty()) { const ui::ImageModel& dark_mode_banner = model_->dark_mode_banner(GetPassKey()); auto banner_view = std::make_unique<ThemeTrackingImageView>( banner.Rasterize(contents_view_->GetColorProvider()), (dark_mode_banner.IsEmpty() ? banner : dark_mode_banner) .Rasterize(contents_view_->GetColorProvider()), base::BindRepeating(&views::BubbleDialogDelegate::GetBackgroundColor, base::Unretained(this))); // The banner is supposed to be purely decorative. banner_view->GetViewAccessibility().OverrideIsIgnored(true); GetBubbleFrameView()->SetHeaderView(std::move(banner_view)); SizeToContents(); } } View* BubbleDialogModelHost::GetContentsViewForTesting() { return contents_view_; } void BubbleDialogModelHost::Close() { DCHECK(model_); DCHECK(GetWidget()); GetWidget()->Close(); // Synchronously destroy |model_|. Widget::Close() being asynchronous should // not be observable by the model or client code. // Notify the model of window closing before destroying it (as if // Widget::Close) model_->OnDialogDestroying(GetPassKey()); // TODO(pbos): Consider turning this into for-each-field remove field. // TODO(pbos): Move this into a better-named call inside contents_view_ to // make it clear that the model_ is about to be destroyed. contents_view_->RemoveAllChildViews(); fields_.clear(); model_.reset(); } void BubbleDialogModelHost::OnFieldAdded(ui::DialogModelField* field) { switch (field->type(GetPassKey())) { case ui::DialogModelField::kButton: // TODO(pbos): Add support for buttons that are part of content area. NOTREACHED_NORETURN(); case ui::DialogModelField::kParagraph: AddOrUpdateParagraph(field->AsParagraph(GetPassKey())); break; case ui::DialogModelField::kCheckbox: AddOrUpdateCheckbox(field->AsCheckbox(GetPassKey())); break; case ui::DialogModelField::kCombobox: AddOrUpdateCombobox(field->AsCombobox(GetPassKey())); break; case ui::DialogModelField::kMenuItem: AddOrUpdateMenuItem(field->AsMenuItem(GetPassKey())); break; case ui::DialogModelField::kSeparator: AddOrUpdateSeparator(field); break; case ui::DialogModelField::kTextfield: AddOrUpdateTextfield(field->AsTextfield(GetPassKey())); break; case ui::DialogModelField::kCustom: std::unique_ptr<View> view = static_cast<CustomView*>( field->AsCustomField(GetPassKey())->field(GetPassKey())) ->TransferView(); DCHECK(view); view->SetProperty(kElementIdentifierKey, field->id(GetPassKey())); DialogModelHostField info{field, view.get(), nullptr}; AddDialogModelHostField(std::move(view), info); break; } UpdateSpacingAndMargins(); if (GetBubbleFrameView()) SizeToContents(); } void BubbleDialogModelHost::AddInitialFields() { DCHECK(contents_view_->children().empty()) << "This should only be called once."; const auto& fields = model_->fields(GetPassKey()); for (const auto& field : fields) OnFieldAdded(field.get()); } void BubbleDialogModelHost::UpdateSpacingAndMargins() { LayoutProvider* const layout_provider = LayoutProvider::Get(); gfx::Insets dialog_side_insets = layout_provider->GetInsetsMetric(InsetsMetric::INSETS_DIALOG); dialog_side_insets.set_top(0); dialog_side_insets.set_bottom(0); ui::DialogModelField* first_field = nullptr; ui::DialogModelField* last_field = nullptr; auto* scroll_view = views::ScrollView::GetScrollViewForContents(contents_view_); const views::View::Views& children = scroll_view ? scroll_view->contents()->children() : contents_view_->children(); for (View* const view : children) { ui::DialogModelField* const field = FindDialogModelHostField(view).dialog_model_field; FieldType field_type = GetFieldTypeForField(field, GetPassKey()); gfx::Insets side_insets = field_type == FieldType::kMenuItem ? gfx::Insets() : dialog_side_insets; if (!first_field) { first_field = field; view->SetProperty(kMarginsKey, side_insets); } else { DCHECK(last_field); FieldType last_field_type = GetFieldTypeForField(last_field, GetPassKey()); side_insets.set_top( GetFieldTopMargin(layout_provider, field_type, last_field_type)); view->SetProperty(kMarginsKey, side_insets); } last_field = field; } contents_view_->InvalidateLayout(); // Set margins based on the first and last item. Note that we remove margins // that were already added to contents view at construction. // TODO(crbug.com/1348165): Remove the extra margin workaround when contents // view directly supports a scroll view. const int extra_margin = scroll_view ? kScrollViewVerticalMargin : 0; const int top_margin = GetDialogTopMargins(layout_provider, first_field, GetPassKey()) - extra_margin; const int bottom_margin = GetDialogBottomMargins(layout_provider, last_field, GetDialogButtons() != ui::DIALOG_BUTTON_NONE, GetPassKey()) - extra_margin; set_margins(gfx::Insets::TLBR(top_margin >= 0 ? top_margin : 0, 0, bottom_margin >= 0 ? bottom_margin : 0, 0)); } void BubbleDialogModelHost::OnWindowClosing() { // If the model has been removed we have already notified it of closing on the // ::Close() stack. if (!model_) return; model_->OnDialogDestroying(GetPassKey()); // TODO(pbos): Do we need to reset `model_` and destroy contents? See Close(). } void BubbleDialogModelHost::AddOrUpdateParagraph( ui::DialogModelParagraph* model_field) { // TODO(pbos): Handle updating existing field. std::unique_ptr<View> view = model_field->header(GetPassKey()).empty() ? CreateViewForLabel(model_field->label(GetPassKey())) : CreateViewForParagraphWithHeader(model_field->label(GetPassKey()), model_field->header(GetPassKey())); DialogModelHostField info{model_field, view.get(), nullptr}; view->SetProperty(kElementIdentifierKey, model_field->id(GetPassKey())); AddDialogModelHostField(std::move(view), info); } void BubbleDialogModelHost::AddOrUpdateCheckbox( ui::DialogModelCheckbox* model_field) { // TODO(pbos): Handle updating existing field. std::unique_ptr<CheckboxControl> checkbox; if (DialogModelLabelRequiresStyledLabel(model_field->label(GetPassKey()))) { auto label = CreateStyledLabelForDialogModelLabel(model_field->label(GetPassKey())); const int line_height = label->GetLineHeight(); checkbox = std::make_unique<CheckboxControl>(std::move(label), line_height); } else { auto label = CreateLabelForDialogModelLabel(model_field->label(GetPassKey())); const int line_height = label->GetLineHeight(); checkbox = std::make_unique<CheckboxControl>(std::move(label), line_height); } checkbox->SetChecked(model_field->is_checked()); checkbox->SetCallback(base::BindRepeating( [](ui::DialogModelCheckbox* model_field, base::PassKey<DialogModelHost> pass_key, Checkbox* checkbox, const ui::Event& event) { model_field->OnChecked(pass_key, checkbox->GetChecked()); }, model_field, GetPassKey(), checkbox.get())); DialogModelHostField info{model_field, checkbox.get(), nullptr}; AddDialogModelHostField(std::move(checkbox), info); } void BubbleDialogModelHost::AddOrUpdateCombobox( ui::DialogModelCombobox* model_field) { // TODO(pbos): Handle updating existing field. auto combobox = std::make_unique<Combobox>(model_field->combobox_model()); combobox->SetAccessibleName(model_field->accessible_name(GetPassKey()).empty() ? model_field->label(GetPassKey()) : model_field->accessible_name(GetPassKey())); combobox->SetCallback(base::BindRepeating( [](ui::DialogModelCombobox* model_field, base::PassKey<DialogModelHost> pass_key, Combobox* combobox) { model_field->OnPerformAction(pass_key); }, model_field, GetPassKey(), combobox.get())); combobox->SetSelectedIndex(model_field->selected_index()); property_changed_subscriptions_.push_back( combobox->AddSelectedIndexChangedCallback(base::BindRepeating( [](ui::DialogModelCombobox* model_field, base::PassKey<DialogModelHost> pass_key, Combobox* combobox) { model_field->OnSelectedIndexChanged( pass_key, combobox->GetSelectedIndex().value()); }, model_field, GetPassKey(), combobox.get()))); const gfx::FontList& font_list = combobox->GetFontList(); AddViewForLabelAndField(model_field, model_field->label(GetPassKey()), std::move(combobox), font_list); } void BubbleDialogModelHost::AddOrUpdateMenuItem( ui::DialogModelMenuItem* model_field) { // TODO(pbos): Handle updating existing field. // TODO(crbug.com/1324298): Implement this for enabled items. Sorry! DCHECK(!model_field->is_enabled(GetPassKey())); auto item = std::make_unique<LabelButton>( base::BindRepeating( [](base::PassKey<ui::DialogModelHost> pass_key, ui::DialogModelMenuItem* model_field, const ui::Event& event) { model_field->OnActivated(pass_key, event.flags()); }, GetPassKey(), model_field), model_field->label(GetPassKey())); item->SetImageModel(Button::STATE_NORMAL, model_field->icon(GetPassKey())); // TODO(pbos): Move DISTANCE_CONTROL_LIST_VERTICAL to // views::LayoutProvider and replace "12" here. See below for another "12" use // that also needs to be replaced. item->SetBorder(views::CreateEmptyBorder( gfx::Insets::VH(12 / 2, LayoutProvider::Get()->GetDistanceMetric( DISTANCE_BUTTON_HORIZONTAL_PADDING)))); item->SetEnabled(model_field->is_enabled(GetPassKey())); item->SetProperty(kElementIdentifierKey, model_field->id(GetPassKey())); DialogModelHostField info{model_field, item.get(), nullptr}; AddDialogModelHostField(std::move(item), info); } void BubbleDialogModelHost::AddOrUpdateSeparator( ui::DialogModelField* model_field) { DCHECK_EQ(ui::DialogModelField::Type::kSeparator, model_field->type(GetPassKey())); // TODO(pbos): Support updates to the existing model. auto separator = std::make_unique<Separator>(); DialogModelHostField info{model_field, separator.get(), nullptr}; AddDialogModelHostField(std::move(separator), info); } void BubbleDialogModelHost::AddOrUpdateTextfield( ui::DialogModelTextfield* model_field) { // TODO(pbos): Support updates to the existing model. auto textfield = std::make_unique<Textfield>(); textfield->SetAccessibleName( model_field->accessible_name(GetPassKey()).empty() ? model_field->label(GetPassKey()) : model_field->accessible_name(GetPassKey())); textfield->SetText(model_field->text()); // If this textfield is initially focused the text should be initially // selected as well. // TODO(pbos): Fix this for non-unique IDs. This should not select all text // for all textfields with that ID. ui::ElementIdentifier initially_focused_field_id = model_->initially_focused_field(GetPassKey()); if (initially_focused_field_id && model_field->id(GetPassKey()) == initially_focused_field_id) { textfield->SelectAll(true); } property_changed_subscriptions_.push_back( textfield->AddTextChangedCallback(base::BindRepeating( [](ui::DialogModelTextfield* model_field, base::PassKey<DialogModelHost> pass_key, Textfield* textfield) { model_field->OnTextChanged(pass_key, textfield->GetText()); }, model_field, GetPassKey(), textfield.get()))); const gfx::FontList& font_list = textfield->GetFontList(); AddViewForLabelAndField(model_field, model_field->label(GetPassKey()), std::move(textfield), font_list); } void BubbleDialogModelHost::AddViewForLabelAndField( ui::DialogModelField* model_field, const std::u16string& label_text, std::unique_ptr<View> field, const gfx::FontList& field_font) { auto box_layout = std::make_unique<BoxLayoutView>(); box_layout->SetBetweenChildSpacing(LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_CONTROL_HORIZONTAL)); DialogModelHostField info{model_field, box_layout.get(), field.get()}; auto label = std::make_unique<Label>(label_text, style::CONTEXT_LABEL, style::STYLE_PRIMARY); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); box_layout->AddChildView(std::make_unique<LayoutConsensusView>( &textfield_first_column_group_, std::move(label))); box_layout->SetFlexForView( box_layout->AddChildView(std::make_unique<LayoutConsensusView>( &textfield_second_column_group_, std::move(field))), 1); AddDialogModelHostField(std::move(box_layout), info); } void BubbleDialogModelHost::AddDialogModelHostField( std::unique_ptr<View> view, const DialogModelHostField& field_view_info) { DCHECK_EQ(view.get(), field_view_info.field_view); contents_view_->AddChildView(std::move(view)); AddDialogModelHostFieldForExistingView(field_view_info); } void BubbleDialogModelHost::AddDialogModelHostFieldForExistingView( const DialogModelHostField& field_view_info) { DCHECK(field_view_info.dialog_model_field); DCHECK(field_view_info.field_view); DCHECK(contents_view_->Contains(field_view_info.field_view) || field_view_info.field_view == GetOkButton() || field_view_info.field_view == GetCancelButton() || field_view_info.field_view == GetExtraView()); #if DCHECK_IS_ON() // Make sure none of the info is already in use. for (const auto& info : fields_) { DCHECK_NE(info.field_view, field_view_info.field_view); DCHECK_NE(info.dialog_model_field, field_view_info.dialog_model_field); if (info.focusable_view) DCHECK_NE(info.focusable_view, field_view_info.focusable_view); } #endif // DCHECK_IS_ON() fields_.push_back(field_view_info); View* const target = GetTargetView(field_view_info); target->SetProperty(kElementIdentifierKey, field_view_info.dialog_model_field->id(GetPassKey())); for (const auto& accelerator : field_view_info.dialog_model_field->accelerators(GetPassKey())) { target->AddAccelerator(accelerator); } } BubbleDialogModelHost::DialogModelHostField BubbleDialogModelHost::FindDialogModelHostField(ui::DialogModelField* field) { for (const auto& info : fields_) { if (info.dialog_model_field == field) return info; } // TODO(pbos): `field` could correspond to a button. return {}; } BubbleDialogModelHost::DialogModelHostField BubbleDialogModelHost::FindDialogModelHostField(View* view) { for (const auto& info : fields_) { if (info.field_view == view) return info; } NOTREACHED_NORETURN(); } View* BubbleDialogModelHost::GetTargetView( const DialogModelHostField& field_view_info) { return field_view_info.focusable_view ? field_view_info.focusable_view.get() : field_view_info.field_view.get(); } bool BubbleDialogModelHost::DialogModelLabelRequiresStyledLabel( const ui::DialogModelLabel& dialog_label) { return !dialog_label.replacements(GetPassKey()).empty(); } std::unique_ptr<View> BubbleDialogModelHost::CreateViewForLabel( const ui::DialogModelLabel& dialog_label) { if (DialogModelLabelRequiresStyledLabel(dialog_label)) return CreateStyledLabelForDialogModelLabel(dialog_label); return CreateLabelForDialogModelLabel(dialog_label); } std::unique_ptr<StyledLabel> BubbleDialogModelHost::CreateStyledLabelForDialogModelLabel( const ui::DialogModelLabel& dialog_label) { DCHECK(DialogModelLabelRequiresStyledLabel(dialog_label)); const std::vector<ui::DialogModelLabel::TextReplacement>& replacements = dialog_label.replacements(GetPassKey()); // Retrieve the replacements strings to create the text. std::vector<std::u16string> string_replacements; for (auto replacement : replacements) { string_replacements.push_back(replacement.text()); } std::vector<size_t> offsets; const std::u16string text = l10n_util::GetStringFUTF16( dialog_label.message_id(GetPassKey()), string_replacements, &offsets); auto styled_label = std::make_unique<StyledLabel>(); styled_label->SetText(text); styled_label->SetDefaultTextStyle(dialog_label.is_secondary(GetPassKey()) ? style::STYLE_SECONDARY : style::STYLE_PRIMARY); // Style the replacements as needed. DCHECK_EQ(string_replacements.size(), offsets.size()); for (size_t i = 0; i < replacements.size(); ++i) { auto replacement = replacements[i]; // No styling needed if replacement is neither a link nor emphasized text. if (!replacement.callback().has_value() && !replacement.is_emphasized()) continue; StyledLabel::RangeStyleInfo style_info; if (replacement.callback().has_value()) { style_info = StyledLabel::RangeStyleInfo::CreateForLink( replacement.callback().value()); style_info.accessible_name = replacement.accessible_name().value(); } else if (replacement.is_emphasized()) { style_info.text_style = views::style::STYLE_EMPHASIZED; } auto offset = offsets[i]; styled_label->AddStyleRange( gfx::Range(offset, offset + replacement.text().length()), style_info); } return styled_label; } std::unique_ptr<Label> BubbleDialogModelHost::CreateLabelForDialogModelLabel( const ui::DialogModelLabel& dialog_label) { DCHECK(!DialogModelLabelRequiresStyledLabel(dialog_label)); auto text_label = std::make_unique<Label>( dialog_label.GetString(GetPassKey()), style::CONTEXT_DIALOG_BODY_TEXT, dialog_label.is_secondary(GetPassKey()) ? style::STYLE_SECONDARY : style::STYLE_PRIMARY); text_label->SetMultiLine(true); text_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); return text_label; } std::unique_ptr<View> BubbleDialogModelHost::CreateViewForParagraphWithHeader( const ui::DialogModelLabel& dialog_label, const std::u16string header) { auto view = std::make_unique<BoxLayoutView>(); view->SetOrientation(BoxLayout::Orientation::kVertical); auto* header_label = view->AddChildView(std::make_unique<Label>( header, style::CONTEXT_DIALOG_BODY_TEXT, style::STYLE_PRIMARY)); header_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); view->AddChildView(CreateViewForLabel(dialog_label)); return view; } bool BubbleDialogModelHost::IsModalDialog() const { return GetModalType() != ui::MODAL_TYPE_NONE; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_model_host.cc
C++
unknown
39,800
// 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_BUBBLE_BUBBLE_DIALOG_MODEL_HOST_H_ #define UI_VIEWS_BUBBLE_BUBBLE_DIALOG_MODEL_HOST_H_ #include <memory> #include <vector> #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "base/types/pass_key.h" #include "ui/base/models/dialog_model.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/view.h" namespace views { class Label; class StyledLabel; // BubbleDialogModelHost is a views implementation of ui::DialogModelHost which // hosts a ui::DialogModel as a BubbleDialogDelegate. This exposes such as // SetAnchorView(), SetArrow() and SetHighlightedButton(). For methods that are // reflected in ui::DialogModelHost (such as ::Close()), prefer using the // ui::DialogModelHost to avoid platform-specific code (GetWidget()->Close()) // where unnecessary. For those methods, note that this can be retrieved as a // ui::DialogModelHost through DialogModel::host(). This helps minimize // platform-specific code from platform-agnostic model-delegate code. class VIEWS_EXPORT BubbleDialogModelHost : public BubbleDialogDelegate, public ui::DialogModelHost { public: enum class FieldType { kText, kControl, kMenuItem }; class ContentsView; class VIEWS_EXPORT CustomView : public ui::DialogModelCustomField::Field { public: CustomView(std::unique_ptr<View> view, FieldType field_type); CustomView(const CustomView&) = delete; CustomView& operator=(const CustomView&) = delete; ~CustomView() override; std::unique_ptr<View> TransferView(); FieldType field_type() const { return field_type_; } private: // `view` is intended to be moved into the View hierarchy. std::unique_ptr<View> view_; const FieldType field_type_; }; // Constructs a BubbleDialogModelHost, which for most purposes is to used as a // BubbleDialogDelegate. The BubbleDialogDelegate is nominally handed to // BubbleDialogDelegate::CreateBubble() which returns a Widget that has taken // ownership of the bubble. Widget::Show() finally shows the bubble. BubbleDialogModelHost(std::unique_ptr<ui::DialogModel> model, View* anchor_view, BubbleBorder::Arrow arrow); // "Private" constructor (uses base::PassKey), use another constructor or // ::CreateModal(). BubbleDialogModelHost(base::PassKey<BubbleDialogModelHost>, std::unique_ptr<ui::DialogModel> model, View* anchor_view, BubbleBorder::Arrow arrow, ui::ModalType modal_type); ~BubbleDialogModelHost() override; static std::unique_ptr<BubbleDialogModelHost> CreateModal( std::unique_ptr<ui::DialogModel> model, ui::ModalType modal_type); // BubbleDialogDelegate: // TODO(pbos): Populate initparams with initial view instead of overriding // GetInitiallyFocusedView(). View* GetInitiallyFocusedView() override; void OnWidgetInitialized() override; View* GetContentsViewForTesting(); // ui::DialogModelHost: void Close() override; void OnFieldAdded(ui::DialogModelField* field) override; private: // TODO(pbos): Consider externalizing this functionality into a different // format that could feasibly be adopted by LayoutManagers. This is used for // BoxLayouts (but could be others) to agree on columns' preferred width as a // replacement for using GridLayout. class LayoutConsensusView; class LayoutConsensusGroup { public: LayoutConsensusGroup(); ~LayoutConsensusGroup(); void AddView(LayoutConsensusView* view); void RemoveView(LayoutConsensusView* view); void InvalidateChildren(); // Get the union of all preferred sizes within the group. gfx::Size GetMaxPreferredSize() const; // Get the union of all minimum sizes within the group. gfx::Size GetMaxMinimumSize() const; private: base::flat_set<View*> children_; }; struct DialogModelHostField { raw_ptr<ui::DialogModelField> dialog_model_field; // View representing the entire field. raw_ptr<View, DanglingUntriaged> field_view; // Child view to |field_view|, if any, that's used for focus. For instance, // a textfield row would be a container that contains both a // views::Textfield and a descriptive label. In this case |focusable_view| // would refer to the views::Textfield which is also what would gain focus. raw_ptr<View, DanglingUntriaged> focusable_view; }; void OnWindowClosing(); void AddInitialFields(); void AddOrUpdateParagraph(ui::DialogModelParagraph* model_field); void AddOrUpdateCheckbox(ui::DialogModelCheckbox* model_field); void AddOrUpdateCombobox(ui::DialogModelCombobox* model_field); void AddOrUpdateMenuItem(ui::DialogModelMenuItem* model_field); void AddOrUpdateSeparator(ui::DialogModelField* model_field); void AddOrUpdateTextfield(ui::DialogModelTextfield* model_field); void UpdateSpacingAndMargins(); void AddViewForLabelAndField(ui::DialogModelField* model_field, const std::u16string& label_text, std::unique_ptr<views::View> field, const gfx::FontList& field_font); static bool DialogModelLabelRequiresStyledLabel( const ui::DialogModelLabel& dialog_label); std::unique_ptr<View> CreateViewForLabel( const ui::DialogModelLabel& dialog_label); std::unique_ptr<StyledLabel> CreateStyledLabelForDialogModelLabel( const ui::DialogModelLabel& dialog_label); std::unique_ptr<Label> CreateLabelForDialogModelLabel( const ui::DialogModelLabel& dialog_label); std::unique_ptr<View> CreateViewForParagraphWithHeader( const ui::DialogModelLabel& dialog_label, const std::u16string header); void AddDialogModelHostField(std::unique_ptr<View> view, const DialogModelHostField& field_view_info); void AddDialogModelHostFieldForExistingView( const DialogModelHostField& field_view_info); DialogModelHostField FindDialogModelHostField( ui::DialogModelField* model_field); DialogModelHostField FindDialogModelHostField(View* view); static View* GetTargetView(const DialogModelHostField& field_view_info); bool IsModalDialog() const; std::unique_ptr<ui::DialogModel> model_; const raw_ptr<ContentsView> contents_view_; std::vector<DialogModelHostField> fields_; std::vector<base::CallbackListSubscription> property_changed_subscriptions_; LayoutConsensusGroup textfield_first_column_group_; LayoutConsensusGroup textfield_second_column_group_; }; } // namespace views #endif // UI_VIEWS_BUBBLE_BUBBLE_DIALOG_MODEL_HOST_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_model_host.h
C++
unknown
6,881
// 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/bubble/bubble_dialog_model_host.h" #include <memory> #include <utility> #include "base/functional/callback_helpers.h" #include "base/test/gtest_util.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/interaction/element_tracker_views.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/widget_test.h" #include "ui/views/view_class_properties.h" namespace views { using BubbleDialogModelHostTest = ViewsTestBase; // TODO(pbos): Consider moving tests from this file into a test base for // DialogModel that can be instantiated by any DialogModelHost implementation to // check its compliance. namespace { // WeakPtrs to this delegate is used to infer when DialogModel is destroyed. class WeakDialogModelDelegate : public ui::DialogModelDelegate { public: base::WeakPtr<WeakDialogModelDelegate> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: base::WeakPtrFactory<WeakDialogModelDelegate> weak_ptr_factory_{this}; }; } // namespace TEST_F(BubbleDialogModelHostTest, CloseIsSynchronousAndCallsWindowClosing) { std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); auto delegate = std::make_unique<WeakDialogModelDelegate>(); auto weak_delegate = delegate->GetWeakPtr(); int window_closing_count = 0; auto host = std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder(std::move(delegate)) .SetDialogDestroyingCallback(base::BindOnce(base::BindOnce( [](int* window_closing_count) { ++(*window_closing_count); }, &window_closing_count))) .Build(), anchor_widget->GetContentsView(), BubbleBorder::Arrow::TOP_RIGHT); auto* host_ptr = host.get(); Widget* bubble_widget = BubbleDialogDelegate::CreateBubble(std::move(host)); test::WidgetDestroyedWaiter waiter(bubble_widget); EXPECT_EQ(0, window_closing_count); DCHECK_EQ(host_ptr, weak_delegate->dialog_model()->host()); weak_delegate->dialog_model()->host()->Close(); EXPECT_EQ(1, window_closing_count); // The model (and hence delegate) should destroy synchronously, so the // WeakPtr should disappear before waiting for the views Widget to close. EXPECT_FALSE(weak_delegate); waiter.Wait(); } TEST_F(BubbleDialogModelHostTest, ElementIDsReportedCorrectly) { DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kMenuItemId); DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kOkButtonId); DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kExtraButtonId); constexpr char16_t kMenuItemText[] = u"Menu Item"; constexpr char16_t kOkButtonText[] = u"OK"; constexpr char16_t kExtraButtonText[] = u"Button"; std::unique_ptr<Widget> anchor_widget = CreateTestWidget(Widget::InitParams::TYPE_WINDOW); anchor_widget->Show(); const auto context = views::ElementTrackerViews::GetContextForWidget(anchor_widget.get()); ui::DialogModelMenuItem::Params menu_item_params; menu_item_params.SetId(kMenuItemId); // TODO(crbug.com/1324298): Remove after addressing this issue. menu_item_params.SetIsEnabled(false); ui::DialogModelButton::Params ok_button_params; ok_button_params.SetId(kOkButtonId); ok_button_params.SetLabel(kOkButtonText); ui::DialogModelButton::Params extra_button_params; extra_button_params.SetId(kExtraButtonId); extra_button_params.SetLabel(kExtraButtonText); auto host = std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder() .AddMenuItem(ui::ImageModel(), kMenuItemText, base::DoNothing(), menu_item_params) .AddOkButton(base::DoNothing(), ok_button_params) .AddExtraButton(base::DoNothing(), extra_button_params) .Build(), anchor_widget->GetContentsView(), BubbleBorder::Arrow::TOP_RIGHT); Widget* const bubble_widget = BubbleDialogDelegate::CreateBubble(std::move(host)); test::WidgetVisibleWaiter waiter(bubble_widget); bubble_widget->Show(); waiter.Wait(); ASSERT_TRUE(bubble_widget->IsVisible()); EXPECT_NE(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kMenuItemId, context)); EXPECT_NE(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kOkButtonId, context)); EXPECT_NE(nullptr, ui::ElementTracker::GetElementTracker()->GetUniqueElement( kExtraButtonId, context)); bubble_widget->CloseNow(); } TEST_F(BubbleDialogModelHostTest, OverrideDefaultButton) { auto host = std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder() .AddCancelButton(base::OnceClosure()) .OverrideDefaultButton(ui::DialogButton::DIALOG_BUTTON_CANCEL) .Build(), /*anchor_view=*/nullptr, BubbleBorder::Arrow::TOP_RIGHT); EXPECT_EQ(host->GetDefaultDialogButton(), ui::DialogButton::DIALOG_BUTTON_CANCEL); } TEST_F(BubbleDialogModelHostTest, OverrideDefaultButtonDeathTest) { EXPECT_DCHECK_DEATH(std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder() .AddCancelButton(base::OnceClosure()) .OverrideDefaultButton(ui::DialogButton::DIALOG_BUTTON_OK) .Build(), /*anchor_view=*/nullptr, BubbleBorder::Arrow::TOP_RIGHT)) << "Cannot override the default button with a button which does not " "exist."; } TEST_F(BubbleDialogModelHostTest, SetInitiallyFocusedViewOverridesDefaultButtonFocus) { DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kFocusedField); auto host = std::make_unique<BubbleDialogModelHost>( ui::DialogModel::Builder() .AddCancelButton(base::OnceClosure()) .OverrideDefaultButton(ui::DialogButton::DIALOG_BUTTON_CANCEL) .AddTextfield(kFocusedField, u"label", u"text") .SetInitiallyFocusedField(kFocusedField) .Build(), /*anchor_view=*/nullptr, BubbleBorder::Arrow::TOP_RIGHT); EXPECT_EQ(host->GetDefaultDialogButton(), ui::DialogButton::DIALOG_BUTTON_CANCEL); EXPECT_EQ(host->GetInitiallyFocusedView()->GetProperty(kElementIdentifierKey), kFocusedField); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_dialog_model_host_unittest.cc
C++
unknown
6,390
// 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/bubble/bubble_frame_view.h" #include <algorithm> #include <utility> #include "build/build_config.h" #include "components/vector_icons/vector_icons.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/default_style.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/layer.h" #include "ui/compositor/paint_recorder.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/resources/grit/ui_resources.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/bubble/footnote_container_view.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/image_button_factory.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/image_view.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/paint_info.h" #include "ui/views/resources/grit/views_resources.h" #include "ui/views/style/typography.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/window/client_view.h" #include "ui/views/window/dialog_delegate.h" #include "ui/views/window/vector_icons/vector_icons.h" namespace views { namespace { // Get the |vertical| or horizontal amount that |available_bounds| overflows // |window_bounds|. int GetOverflowLength(const gfx::Rect& available_bounds, const gfx::Rect& window_bounds, bool vertical) { if (available_bounds.IsEmpty() || available_bounds.Contains(window_bounds)) return 0; // window_bounds // +---------------------------------+ // | top | // | +------------------+ | // | left | available_bounds | right | // | +------------------+ | // | bottom | // +---------------------------------+ if (vertical) return std::max(0, available_bounds.y() - window_bounds.y()) + std::max(0, window_bounds.bottom() - available_bounds.bottom()); return std::max(0, available_bounds.x() - window_bounds.x()) + std::max(0, window_bounds.right() - available_bounds.right()); } // The height of the progress indicator shown at the top of the bubble frame // view. constexpr int kProgressIndicatorHeight = 4; } // namespace BubbleFrameView::BubbleFrameView(const gfx::Insets& title_margins, const gfx::Insets& content_margins) : title_margins_(title_margins), content_margins_(content_margins), footnote_margins_(content_margins_), title_icon_(AddChildView(std::make_unique<ImageView>())), main_image_(AddChildView(std::make_unique<ImageView>())), title_container_(AddChildView(std::make_unique<views::BoxLayoutView>())), default_title_(title_container_->AddChildView( CreateDefaultTitleLabel(std::u16string()))), subtitle_(title_container_->AddChildView( CreateLabelWithContextAndStyle(std::u16string(), style::CONTEXT_LABEL, style::STYLE_SECONDARY))) { title_container_->SetOrientation(BoxLayout::Orientation::kVertical); default_title_->SetVisible(false); main_image_->SetVisible(false); subtitle_->SetVisible(false); auto close = CreateCloseButton(base::BindRepeating( [](BubbleFrameView* view, const ui::Event& event) { if (view->input_protector_.IsPossiblyUnintendedInteraction(event)) return; view->GetWidget()->CloseWithReason( Widget::ClosedReason::kCloseButtonClicked); }, this)); close->SetVisible(false); close_ = AddChildView(std::move(close)); auto minimize = CreateMinimizeButton(base::BindRepeating( [](BubbleFrameView* view, const ui::Event& event) { if (view->input_protector_.IsPossiblyUnintendedInteraction(event)) return; view->GetWidget()->Minimize(); }, this)); minimize->SetVisible(false); minimize_ = AddChildView(std::move(minimize)); auto progress_indicator = std::make_unique<ProgressBar>( kProgressIndicatorHeight, /*allow_round_corner=*/false); progress_indicator->SetBackgroundColor(SK_ColorTRANSPARENT); progress_indicator->SetVisible(false); progress_indicator->GetViewAccessibility().OverrideIsIgnored(true); progress_indicator_ = AddChildView(std::move(progress_indicator)); } BubbleFrameView::~BubbleFrameView() = default; // static std::unique_ptr<Label> BubbleFrameView::CreateDefaultTitleLabel( const std::u16string& title_text) { return CreateLabelWithContextAndStyle(title_text, style::CONTEXT_DIALOG_TITLE, style::STYLE_PRIMARY); } // static std::unique_ptr<Button> BubbleFrameView::CreateCloseButton( Button::PressedCallback callback) { auto close_button = CreateVectorImageButtonWithNativeTheme( std::move(callback), vector_icons::kCloseRoundedIcon); close_button->SetTooltipText(l10n_util::GetStringUTF16(IDS_APP_CLOSE)); close_button->SetAccessibleName(l10n_util::GetStringUTF16(IDS_APP_CLOSE)); close_button->SizeToPreferredSize(); InstallCircleHighlightPathGenerator(close_button.get()); return close_button; } // static std::unique_ptr<Button> BubbleFrameView::CreateMinimizeButton( Button::PressedCallback callback) { auto minimize_button = CreateVectorImageButtonWithNativeTheme( std::move(callback), kWindowControlMinimizeIcon); minimize_button->SetTooltipText( l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MINIMIZE)); minimize_button->SetAccessibleName( l10n_util::GetStringUTF16(IDS_APP_ACCNAME_MINIMIZE)); minimize_button->SizeToPreferredSize(); InstallCircleHighlightPathGenerator(minimize_button.get()); return minimize_button; } gfx::Rect BubbleFrameView::GetBoundsForClientView() const { // When NonClientView asks for this, the size of the frame view has been set // (i.e. |this|), but not the client view bounds. gfx::Rect client_bounds = GetContentsBounds(); client_bounds.Inset(GetClientInsetsForFrameWidth(client_bounds.width())); // Only account for footnote_container_'s height if it's visible, because // content_margins_ adds extra padding even if all child views are invisible. if (footnote_container_ && footnote_container_->GetVisible()) { client_bounds.set_height(client_bounds.height() - footnote_container_->height()); } return client_bounds; } gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Size size(GetFrameSizeForClientSize(client_bounds.size())); return bubble_border_->GetBounds(gfx::Rect(), size); } bool BubbleFrameView::GetClientMask(const gfx::Size& size, SkPath* path) const { // NonClientView calls this after setting the client view size from the return // of GetBoundsForClientView(); feeding it back in |size|. DCHECK_EQ(GetBoundsForClientView().size(), size); DCHECK_EQ(GetWidget()->client_view()->size(), size); // BubbleFrameView only returns a SkPath for the purpose of clipping the // client view's corners so that it fits within the borders of its rounded // frame. If a client view is painted to a layer the rounding is handled by // the |SetRoundedCornerRadius()| layer API, so we return false here. if (GetWidget()->client_view()->layer()) { return false; } const gfx::RoundedCornersF corner_radii = GetClientCornerRadii(); // If corner radii are all zero we do not need to apply a mask. if (corner_radii.IsEmpty()) return false; // Format is upper-left x, upper-left y, upper-right x, and so forth, // clockwise around the boundary. SkScalar radii[]{corner_radii.upper_left(), corner_radii.upper_left(), corner_radii.upper_right(), corner_radii.upper_right(), corner_radii.lower_right(), corner_radii.lower_right(), corner_radii.lower_left(), corner_radii.lower_left()}; path->addRoundRect(SkRect::MakeIWH(size.width(), size.height()), radii); return true; } int BubbleFrameView::NonClientHitTest(const gfx::Point& point) { if (!bounds().Contains(point)) return HTNOWHERE; if (hit_test_transparent_) return HTTRANSPARENT; #if !BUILDFLAG(IS_WIN) // Windows will automatically create a tooltip for the button based on // the HTCLOSE or the HTMINBUTTON if (close_->GetVisible() && close_->GetMirroredBounds().Contains(point)) return HTCLOSE; if (minimize_->GetVisible() && minimize_->GetMirroredBounds().Contains(point)) return HTMINBUTTON; #endif // Convert to RRectF to accurately represent the rounded corners of the // dialog and allow events to pass through the shadows. gfx::RRectF round_contents_bounds(gfx::RectF(GetContentsBounds()), bubble_border_->corner_radius()); if (bubble_border_->shadow() != BubbleBorder::NO_SHADOW) round_contents_bounds.Outset(BubbleBorder::kBorderThicknessDip); gfx::RectF rectf_point(point.x(), point.y(), 1, 1); if (!round_contents_bounds.Contains(rectf_point)) return HTTRANSPARENT; if (point.y() < title_container_->bounds().bottom()) { auto* dialog_delegate = GetWidget()->widget_delegate()->AsDialogDelegate(); if (dialog_delegate && dialog_delegate->draggable()) { return HTCAPTION; } } return GetWidget()->client_view()->NonClientHitTest(point); } void BubbleFrameView::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { if (bubble_border_->shadow() != BubbleBorder::STANDARD_SHADOW && bubble_border_->shadow() != BubbleBorder::NO_SHADOW) return; // We don't return a mask for windows with arrows unless they use // BubbleBorder::NO_SHADOW. if (bubble_border_->shadow() != BubbleBorder::NO_SHADOW && bubble_border_->arrow() != BubbleBorder::NONE && bubble_border_->arrow() != BubbleBorder::FLOAT) return; // Use a window mask roughly matching the border in the image assets. const int kBorderStrokeSize = bubble_border_->shadow() == BubbleBorder::NO_SHADOW ? 0 : 1; const SkScalar kCornerRadius = SkIntToScalar(bubble_border_->corner_radius()); const gfx::Insets border_insets = bubble_border_->GetInsets(); SkRect rect = { SkIntToScalar(border_insets.left() - kBorderStrokeSize), SkIntToScalar(border_insets.top() - kBorderStrokeSize), SkIntToScalar(size.width() - border_insets.right() + kBorderStrokeSize), SkIntToScalar(size.height() - border_insets.bottom() + kBorderStrokeSize)}; if (bubble_border_->shadow() == BubbleBorder::NO_SHADOW) { window_mask->addRoundRect(rect, kCornerRadius, kCornerRadius); } else { static const int kBottomBorderShadowSize = 2; rect.fBottom += SkIntToScalar(kBottomBorderShadowSize); window_mask->addRect(rect); } } void BubbleFrameView::ResetWindowControls() { // If the close button is not visible, marking it as "ignored" will cause it // to be removed from the accessibility tree. bool close_is_visible = GetWidget()->widget_delegate()->ShouldShowCloseButton(); close_->SetVisible(close_is_visible); close_->GetViewAccessibility().OverrideIsIgnored(!close_is_visible); // If the minimize button is not visible, marking it as "ignored" will cause // it to be removed from the accessibility tree. bool minimize_is_visible = GetWidget()->widget_delegate()->CanMinimize(); minimize_->SetVisible(minimize_is_visible); minimize_->GetViewAccessibility().OverrideIsIgnored(!minimize_is_visible); } void BubbleFrameView::UpdateWindowIcon() { DCHECK(GetWidget()); gfx::ImageSkia image; if (GetWidget()->widget_delegate()->ShouldShowWindowIcon()) { image = GetWidget()->widget_delegate()->GetWindowIcon().Rasterize( GetColorProvider()); } title_icon_->SetImage(&image); } void BubbleFrameView::UpdateWindowTitle() { if (default_title_) { const WidgetDelegate* delegate = GetWidget()->widget_delegate(); default_title_->SetVisible(delegate->ShouldShowWindowTitle() && !delegate->GetWindowTitle().empty()); default_title_->SetText(delegate->GetWindowTitle()); UpdateSubtitle(); } // custom_title_'s updates are handled by its creator. InvalidateLayout(); } void BubbleFrameView::SizeConstraintsChanged() {} void BubbleFrameView::InsertClientView(ClientView* client_view) { // Place the client view before any footnote view for focus order. footnote_container_ ? AddChildViewAt(client_view, GetIndexOf(footnote_container_).value()) : AddChildView(client_view); } void BubbleFrameView::SetTitleView(std::unique_ptr<View> title_view) { DCHECK(title_view); delete default_title_; default_title_ = nullptr; delete custom_title_; custom_title_ = title_view.get(); title_container_->AddChildViewAt(title_view.release(), 0); } void BubbleFrameView::UpdateSubtitle() { if (!subtitle_) return; views::BubbleDialogDelegate* const bubble_delegate = GetWidget()->widget_delegate()->AsBubbleDialogDelegate(); if (!bubble_delegate) return; // Subtitle anchors and margins rely heavily on Title being visible. subtitle_->SetVisible(!bubble_delegate->GetSubtitle().empty() && default_title_->GetVisible()); subtitle_->SetText(bubble_delegate->GetSubtitle()); InvalidateLayout(); } void BubbleFrameView::UpdateMainImage() { views::BubbleDialogDelegate* const bubble_delegate = GetWidget()->widget_delegate()->AsBubbleDialogDelegate(); if (!bubble_delegate) return; const ui::ImageModel& model = bubble_delegate->GetMainImage(); if (model.IsEmpty()) { main_image_->SetVisible(false); } else { // This max increase is the difference between the 448 and 320 snapping // points in ChromeLayoutProvider, but they are not publicly visible in that // API. We set the size of the main image so that the dialog increases in // size exactly one snapping point. At the point of writing this means that // we are using a 112x112px image. // Ideally this would be handled inside the ImageView, but we do cropping // and scaling outside (through ScaleAspectRatioAndCropCenter). We should // consider moving that functionality into ImageView or ImageModel without // having to specify an external size before painting. constexpr int kMainImageDialogWidthIncrease = 128; constexpr int kBorderInsets = 16; constexpr int kMainImageDimension = kMainImageDialogWidthIncrease - kBorderInsets; constexpr int kBorderStrokeThickness = 1; const int border_radius = LayoutProvider::Get()->GetCornerRadiusMetric( Emphasis::kHigh, gfx::Size()); main_image_->SetImage( gfx::ImageSkiaOperations::CreateCroppedCenteredRoundRectImage( gfx::Size(kMainImageDimension, kMainImageDimension), border_radius - 2 * kBorderStrokeThickness, model.GetImage().AsImageSkia())); main_image_->SetBorder(views::CreateRoundedRectBorder( kBorderStrokeThickness, border_radius, gfx::Insets(kBorderInsets - kBorderStrokeThickness), GetColorProvider() ? GetColorProvider()->GetColor(ui::kColorBubbleBorder) : gfx::kPlaceholderColor)); main_image_->SetVisible(true); } } void BubbleFrameView::SetProgress(absl::optional<double> progress) { bool visible = progress.has_value(); progress_indicator_->SetVisible(visible); progress_indicator_->GetViewAccessibility().OverrideIsIgnored(!visible); if (progress) progress_indicator_->SetValue(progress.value()); } absl::optional<double> BubbleFrameView::GetProgress() const { if (progress_indicator_->GetVisible()) return progress_indicator_->GetValue(); return absl::nullopt; } gfx::Size BubbleFrameView::CalculatePreferredSize() const { // Get the preferred size of the client area. gfx::Size client_size = GetWidget()->client_view()->GetPreferredSize(); // Expand it to include the bubble border and space for the arrow. return GetWindowBoundsForClientBounds(gfx::Rect(client_size)).size(); } gfx::Size BubbleFrameView::GetMinimumSize() const { // Get the minimum size of the client area. gfx::Size client_size = GetWidget()->client_view()->GetMinimumSize(); // Expand it to include the bubble border and space for the arrow. return GetWindowBoundsForClientBounds(gfx::Rect(client_size)).size(); } gfx::Size BubbleFrameView::GetMaximumSize() const { #if BUILDFLAG(IS_WIN) // On Windows, this causes problems, so do not set a maximum size (it doesn't // take the drop shadow area into account, resulting in a too-small window; // see http://crbug.com/506206). This isn't necessary on Windows anyway, since // the OS doesn't give the user controls to resize a bubble. return gfx::Size(); #else #if BUILDFLAG(IS_MAC) // Allow BubbleFrameView dialogs to be resizable on Mac. if (GetWidget()->widget_delegate()->CanResize()) { gfx::Size client_size = GetWidget()->client_view()->GetMaximumSize(); if (client_size.IsEmpty()) return client_size; return GetWindowBoundsForClientBounds(gfx::Rect(client_size)).size(); } #endif // BUILDFLAG(IS_MAC) // Non-dialog bubbles should be non-resizable, so its max size is its // preferred size. return GetPreferredSize(); #endif } void BubbleFrameView::Layout() { // The title margins may not be set, but make sure that's only the case when // there's no title. DCHECK(!title_margins_.IsEmpty() || (!custom_title_ && !default_title_->GetVisible())); const gfx::Rect contents_bounds = GetContentsBounds(); progress_indicator_->SetBounds(contents_bounds.x(), contents_bounds.y(), contents_bounds.width(), kProgressIndicatorHeight); gfx::Rect bounds = contents_bounds; bounds.Inset(title_margins_); int header_bottom = 0; int header_height = GetHeaderHeightForFrameWidth(contents_bounds.width()); if (header_height > 0) { header_view_->SetBounds(contents_bounds.x(), contents_bounds.y(), contents_bounds.width(), header_height); bounds.Inset(gfx::Insets::TLBR(header_height, 0, 0, 0)); header_bottom = header_view_->bounds().bottom(); } // Only account for footnote_container_'s height if it's visible, because // content_margins_ adds extra padding even if all child views are invisible. if (footnote_container_ && footnote_container_->GetVisible()) { const int width = contents_bounds.width(); const int height = footnote_container_->GetHeightForWidth(width); footnote_container_->SetBounds( contents_bounds.x(), contents_bounds.bottom() - height, width, height); } NonClientFrameView::Layout(); if (bounds.IsEmpty()) { return; } // The buttons are positioned somewhat closer to the edge of the bubble. const int close_margin = LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); const int button_y = contents_bounds.y() + close_margin; int button_right = contents_bounds.right() - close_margin; int title_label_right = bounds.right(); for (Button* button : {close_, minimize_}) { if (!button->GetVisible()) continue; button->SetPosition(gfx::Point(button_right - button->width(), button_y)); button_right -= button->width(); button_right -= LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_BUTTON_HORIZONTAL); // Only reserve space if the button extends over the header. if (button->bounds().bottom() > header_bottom) { title_label_right = std::min(title_label_right, button->x() - close_margin); } } gfx::Size title_icon_pref_size(title_icon_->GetPreferredSize()); const int title_icon_padding = title_icon_pref_size.width() > 0 ? title_margins_.left() : 0; const int title_label_x = bounds.x() + title_icon_pref_size.width() + title_icon_padding + GetMainImageLeftInsets(); // TODO(tapted): Layout() should skip more surrounding code when !HasTitle(). // Currently DCHECKs fail since title_insets is 0 when there is no title. if (DCHECK_IS_ON() && HasTitle()) { const gfx::Insets title_insets = GetTitleLabelInsetsFromFrame() + GetInsets(); DCHECK_EQ(title_insets.left(), title_label_x); DCHECK_EQ(title_insets.right(), width() - title_label_right); } const int title_available_width = std::max(1, title_label_right - title_label_x); const int title_preferred_height = title_container_->GetHeightForWidth(title_available_width); const int title_height = std::max(title_icon_pref_size.height(), title_preferred_height); title_container_->SetBounds( title_label_x, bounds.y() + (title_height - title_preferred_height) / 2, title_available_width, title_preferred_height); title_icon_->SetBounds(bounds.x(), bounds.y(), title_icon_pref_size.width(), title_height); main_image_->SetBounds(0, 0, main_image_->GetPreferredSize().width(), main_image_->GetPreferredSize().height()); } void BubbleFrameView::OnThemeChanged() { NonClientFrameView::OnThemeChanged(); UpdateWindowTitle(); UpdateSubtitle(); ResetWindowControls(); UpdateWindowIcon(); UpdateMainImage(); UpdateClientViewBackground(); SchedulePaint(); } void BubbleFrameView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) UpdateClientLayerCornerRadius(); // We need to update the client view's corner radius whenever the header or // footer are added/removed from the bubble frame so that the client view // sits flush with both. if (details.parent == this) UpdateClientLayerCornerRadius(); if (!details.is_add && details.parent == footnote_container_ && footnote_container_->children().size() == 1 && details.child == footnote_container_->children().front()) { // Setting the footnote_container_ to be hidden and null it. This will // remove update the bubble to have no placeholder for the footnote and // enable the destructor to delete the footnote_container_ later. footnote_container_->SetVisible(false); footnote_container_ = nullptr; } } void BubbleFrameView::VisibilityChanged(View* starting_from, bool is_visible) { NonClientFrameView::VisibilityChanged(starting_from, is_visible); input_protector_.VisibilityChanged(is_visible); } void BubbleFrameView::OnPaint(gfx::Canvas* canvas) { OnPaintBackground(canvas); // Border comes after children. } void BubbleFrameView::PaintChildren(const PaintInfo& paint_info) { NonClientFrameView::PaintChildren(paint_info); ui::PaintCache paint_cache; ui::PaintRecorder recorder( paint_info.context(), paint_info.paint_recording_size(), paint_info.paint_recording_scale_x(), paint_info.paint_recording_scale_y(), &paint_cache); OnPaintBorder(recorder.canvas()); } void BubbleFrameView::SetBubbleBorder(std::unique_ptr<BubbleBorder> border) { bubble_border_ = border.get(); if (footnote_container_) footnote_container_->SetCornerRadius(border->corner_radius()); SetBorder(std::move(border)); // Update the background, which relies on the border. SetBackground(std::make_unique<views::BubbleBackground>(bubble_border_)); } void BubbleFrameView::SetContentMargins(const gfx::Insets& content_margins) { content_margins_ = content_margins; OnPropertyChanged(&content_margins_, kPropertyEffectsPreferredSizeChanged); } gfx::Insets BubbleFrameView::GetContentMargins() const { return content_margins_; } void BubbleFrameView::SetHeaderView(std::unique_ptr<View> view) { if (header_view_) { delete header_view_; header_view_ = nullptr; } if (view) header_view_ = AddChildViewAt(std::move(view), 0); InvalidateLayout(); } void BubbleFrameView::SetFootnoteView(std::unique_ptr<View> view) { // Remove the old footnote container. delete footnote_container_; footnote_container_ = nullptr; if (view) { int radius = bubble_border_ ? bubble_border_->corner_radius() : 0; footnote_container_ = AddChildView(std::make_unique<FootnoteContainerView>( footnote_margins_, std::move(view), radius)); } InvalidateLayout(); } View* BubbleFrameView::GetFootnoteView() const { if (!footnote_container_) return nullptr; DCHECK_EQ(1u, footnote_container_->children().size()); return footnote_container_->children()[0]; } void BubbleFrameView::SetFootnoteMargins(const gfx::Insets& footnote_margins) { footnote_margins_ = footnote_margins; OnPropertyChanged(&footnote_margins_, kPropertyEffectsLayout); } gfx::Insets BubbleFrameView::GetFootnoteMargins() const { return footnote_margins_; } void BubbleFrameView::SetPreferredArrowAdjustment( BubbleFrameView::PreferredArrowAdjustment adjustment) { preferred_arrow_adjustment_ = adjustment; // Changing |preferred_arrow_adjustment| will affect window bounds. Therefore // this effect is handled during window resizing. OnPropertyChanged(&preferred_arrow_adjustment_, kPropertyEffectsNone); } BubbleFrameView::PreferredArrowAdjustment BubbleFrameView::GetPreferredArrowAdjustment() const { return preferred_arrow_adjustment_; } void BubbleFrameView::SetCornerRadius(int radius) { bubble_border_->SetCornerRadius(radius); UpdateClientLayerCornerRadius(); } int BubbleFrameView::GetCornerRadius() const { return bubble_border_ ? bubble_border_->corner_radius() : 0; } void BubbleFrameView::SetArrow(BubbleBorder::Arrow arrow) { bubble_border_->set_arrow(arrow); } BubbleBorder::Arrow BubbleFrameView::GetArrow() const { return bubble_border_->arrow(); } void BubbleFrameView::SetDisplayVisibleArrow(bool display_visible_arrow) { bubble_border_->set_visible_arrow(display_visible_arrow); } bool BubbleFrameView::GetDisplayVisibleArrow() const { return bubble_border_->visible_arrow(); } void BubbleFrameView::SetBackgroundColor(SkColor color) { bubble_border_->SetColor(color); UpdateClientViewBackground(); SchedulePaint(); } SkColor BubbleFrameView::GetBackgroundColor() const { return bubble_border_->color(); } void BubbleFrameView::UpdateClientViewBackground() { DCHECK(GetWidget()); DCHECK(GetWidget()->client_view()); // If dealing with a layer backed ClientView we need to update it's color to // match that of the frame view. View* client_view = GetWidget()->client_view(); if (client_view->layer()) { // If the ClientView's background is transparent this could result in visual // artifacts. Make sure this isn't the case. DCHECK_EQ(SK_AlphaOPAQUE, SkColorGetA(GetBackgroundColor())); client_view->SetBackground(CreateSolidBackground(GetBackgroundColor())); client_view->SchedulePaint(); } } gfx::Rect BubbleFrameView::GetUpdatedWindowBounds( const gfx::Rect& anchor_rect, const BubbleBorder::Arrow delegate_arrow, const gfx::Size& client_size, bool adjust_to_fit_available_bounds) { gfx::Size size(GetFrameSizeForClientSize(client_size)); if (adjust_to_fit_available_bounds && BubbleBorder::has_arrow(delegate_arrow)) { // Get the desired bubble bounds without adjustment. bubble_border_->set_arrow_offset(0); bubble_border_->set_arrow(delegate_arrow); // Try to mirror the anchoring if the bubble does not fit in the available // bounds. if (bubble_border_->is_arrow_at_center(delegate_arrow) || preferred_arrow_adjustment_ == PreferredArrowAdjustment::kOffset) { const bool mirror_vertical = BubbleBorder::is_arrow_on_horizontal(delegate_arrow); if (use_anchor_window_bounds_) { MirrorArrowIfOutOfBounds(mirror_vertical, anchor_rect, size, GetAvailableAnchorWindowBounds()); } MirrorArrowIfOutOfBounds(mirror_vertical, anchor_rect, size, GetAvailableScreenBounds(anchor_rect)); if (use_anchor_window_bounds_) { OffsetArrowIfOutOfBounds(anchor_rect, size, GetAvailableAnchorWindowBounds()); } OffsetArrowIfOutOfBounds(anchor_rect, size, GetAvailableScreenBounds(anchor_rect)); } else { if (use_anchor_window_bounds_) { MirrorArrowIfOutOfBounds(true, anchor_rect, size, GetAvailableAnchorWindowBounds()); } MirrorArrowIfOutOfBounds(true, anchor_rect, size, GetAvailableScreenBounds(anchor_rect)); if (use_anchor_window_bounds_) { MirrorArrowIfOutOfBounds(false, anchor_rect, size, GetAvailableAnchorWindowBounds()); } MirrorArrowIfOutOfBounds(false, anchor_rect, size, GetAvailableScreenBounds(anchor_rect)); } } return bubble_border_->GetBounds(anchor_rect, size); } void BubbleFrameView::UpdateInputProtectorTimeStamp() { input_protector_.UpdateViewShownTimeStamp(); } void BubbleFrameView::ResetViewShownTimeStampForTesting() { input_protector_.ResetForTesting(); } gfx::Rect BubbleFrameView::GetAvailableScreenBounds( const gfx::Rect& rect) const { // The bubble attempts to fit within the current screen bounds. return display::Screen::GetScreen() ->GetDisplayNearestPoint(rect.CenterPoint()) .work_area(); } gfx::Rect BubbleFrameView::GetAvailableAnchorWindowBounds() const { views::BubbleDialogDelegate* bubble_delegate_view = GetWidget()->widget_delegate()->AsBubbleDialogDelegate(); if (bubble_delegate_view) { views::View* const anchor_view = bubble_delegate_view->GetAnchorView(); if (anchor_view && anchor_view->GetWidget()) return anchor_view->GetWidget()->GetWindowBoundsInScreen(); } return gfx::Rect(); } bool BubbleFrameView::ExtendClientIntoTitle() const { return false; } bool BubbleFrameView::IsCloseButtonVisible() const { return close_->GetVisible(); } gfx::Rect BubbleFrameView::GetCloseButtonMirroredBounds() const { return close_->GetMirroredBounds(); } gfx::RoundedCornersF BubbleFrameView::GetClientCornerRadii() const { DCHECK(bubble_border_); const int radius = bubble_border_->corner_radius(); const gfx::Insets insets = GetClientInsetsForFrameWidth(GetContentsBounds().width()); // Rounded corners do not need to be applied to the client view if the client // view is sufficiently inset such that its unclipped bounds will not // intersect with the corners of the containing bubble frame view. if ((insets.top() > radius && insets.bottom() > radius) || (insets.left() > radius && insets.right() > radius)) { return gfx::RoundedCornersF(); } // We want to clip the client view to a rounded rect that's consistent with // the bubble's rounded border. However, if there is a header, the top of the // client view should be straight and flush with that. Likewise, if there is // a footer, the client view should be straight and flush with that. Therefore // we set the corner radii separately for top and bottom. gfx::RoundedCornersF corner_radii; corner_radii.set_upper_left(header_view_ ? 0 : radius); corner_radii.set_upper_right(header_view_ ? 0 : radius); corner_radii.set_lower_left(footnote_container_ ? 0 : radius); corner_radii.set_lower_right(footnote_container_ ? 0 : radius); return corner_radii; } void BubbleFrameView::MirrorArrowIfOutOfBounds( bool vertical, const gfx::Rect& anchor_rect, const gfx::Size& client_size, const gfx::Rect& available_bounds) { if (available_bounds.IsEmpty()) return; // Check if the bounds don't fit in the available bounds. gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size)); if (GetOverflowLength(available_bounds, window_bounds, vertical) > 0) { BubbleBorder::Arrow arrow = bubble_border_->arrow(); // Mirror the arrow and get the new bounds. bubble_border_->set_arrow(vertical ? BubbleBorder::vertical_mirror(arrow) : BubbleBorder::horizontal_mirror(arrow)); gfx::Rect mirror_bounds = bubble_border_->GetBounds(anchor_rect, client_size); // Restore the original arrow if mirroring doesn't show more of the bubble. // Otherwise it should invoke parent's Layout() to layout the content based // on the new bubble border. if (GetOverflowLength(available_bounds, mirror_bounds, vertical) >= GetOverflowLength(available_bounds, window_bounds, vertical)) { bubble_border_->set_arrow(arrow); } else { InvalidateLayout(); SchedulePaint(); } } } void BubbleFrameView::OffsetArrowIfOutOfBounds( const gfx::Rect& anchor_rect, const gfx::Size& client_size, const gfx::Rect& available_bounds) { BubbleBorder::Arrow arrow = bubble_border_->arrow(); DCHECK(BubbleBorder::is_arrow_at_center(arrow) || preferred_arrow_adjustment_ == PreferredArrowAdjustment::kOffset); gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size)); if (available_bounds.IsEmpty() || available_bounds.Contains(window_bounds)) return; // Calculate off-screen adjustment. const bool is_horizontal = BubbleBorder::is_arrow_on_horizontal(arrow); int offscreen_adjust = 0; if (is_horizontal) { // If the window bounds are larger than the available bounds then we want to // offset the window to fit as much of it in the available bounds as // possible without exiting the other side of the available bounds. if (window_bounds.width() > available_bounds.width()) { if (window_bounds.x() < available_bounds.x()) offscreen_adjust = available_bounds.right() - window_bounds.right(); else offscreen_adjust = available_bounds.x() - window_bounds.x(); } else if (window_bounds.x() < available_bounds.x()) { offscreen_adjust = available_bounds.x() - window_bounds.x(); } else if (window_bounds.right() > available_bounds.right()) { offscreen_adjust = available_bounds.right() - window_bounds.right(); } } else { if (window_bounds.height() > available_bounds.height()) { if (window_bounds.y() < available_bounds.y()) offscreen_adjust = available_bounds.bottom() - window_bounds.bottom(); else offscreen_adjust = available_bounds.y() - window_bounds.y(); } else if (window_bounds.y() < available_bounds.y()) { offscreen_adjust = available_bounds.y() - window_bounds.y(); } else if (window_bounds.bottom() > available_bounds.bottom()) { offscreen_adjust = available_bounds.bottom() - window_bounds.bottom(); } } // For center arrows, arrows are moved in the opposite direction of // |offscreen_adjust|, e.g. positive |offscreen_adjust| means bubble // window needs to be moved to the right and that means we need to move arrow // to the left, and that means negative offset. bubble_border_->set_arrow_offset(bubble_border_->arrow_offset() - offscreen_adjust); if (offscreen_adjust) SchedulePaint(); } int BubbleFrameView::GetFrameWidthForClientWidth(int client_width) const { // Note that GetMinimumSize() for multiline Labels is typically 0. const int title_bar_width = title()->GetMinimumSize().width() + GetTitleLabelInsetsFromFrame().width(); const int client_area_width = client_width + content_margins_.width(); const int frame_width = std::max(title_bar_width, client_area_width) + GetMainImageLeftInsets(); DialogDelegate* const dialog_delegate = GetWidget()->widget_delegate()->AsDialogDelegate(); bool snapping = dialog_delegate && dialog_delegate->GetDialogButtons() != ui::DIALOG_BUTTON_NONE; return snapping ? LayoutProvider::Get()->GetSnappedDialogWidth(frame_width) : frame_width; } gfx::Size BubbleFrameView::GetFrameSizeForClientSize( const gfx::Size& client_size) const { const int frame_width = GetFrameWidthForClientWidth(client_size.width()); const gfx::Insets client_insets = GetClientInsetsForFrameWidth(frame_width); DCHECK_GE(frame_width, client_size.width()); gfx::Size size(frame_width, client_size.height() + client_insets.height()); // Only account for footnote_container_'s height if it's visible, because // content_margins_ adds extra padding even if all child views are invisible. if (footnote_container_ && footnote_container_->GetVisible()) size.Enlarge(0, footnote_container_->GetHeightForWidth(size.width())); if (main_image_->GetVisible()) { size.set_height( std::max(size.height(), main_image_->GetPreferredSize().height())); } return size; } bool BubbleFrameView::HasTitle() const { return (custom_title_ != nullptr && GetWidget()->widget_delegate()->ShouldShowWindowTitle()) || (default_title_ != nullptr && default_title_->GetPreferredSize().height() > 0) || title_icon_->GetPreferredSize().height() > 0; } gfx::Insets BubbleFrameView::GetTitleLabelInsetsFromFrame() const { int header_height = GetHeaderHeightForFrameWidth(GetContentsBounds().width()); int insets_right = 0; if (GetWidget()->widget_delegate()->ShouldShowCloseButton()) { const int close_margin = LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); // Note: |close_margin| is not applied on the bottom of the icon. int close_height = close_margin + close_->height(); // Only reserve space if the close button extends over the header. if (close_height > header_height) insets_right = 2 * close_margin + close_->width(); } if (!HasTitle()) return gfx::Insets::TLBR(header_height, 0, 0, insets_right); insets_right = std::max(insets_right, title_margins_.right()); const gfx::Size title_icon_pref_size = title_icon_->GetPreferredSize(); const int title_icon_padding = title_icon_pref_size.width() > 0 ? title_margins_.left() : 0; const int insets_left = GetMainImageLeftInsets() + title_margins_.left() + title_icon_pref_size.width() + title_icon_padding; return gfx::Insets::TLBR(header_height + title_margins_.top(), insets_left, title_margins_.bottom(), insets_right); } gfx::Insets BubbleFrameView::GetClientInsetsForFrameWidth( int frame_width) const { int header_height = GetHeaderHeightForFrameWidth(frame_width); int close_height = 0; if (!ExtendClientIntoTitle() && GetWidget()->widget_delegate()->ShouldShowCloseButton()) { const int close_margin = LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); // Note: |close_margin| is not applied on the bottom of the icon. close_height = close_margin + close_->height(); } if (!HasTitle()) { return content_margins_ + gfx::Insets::TLBR(std::max(header_height, close_height), GetMainImageLeftInsets(), 0, 0); } const int icon_height = title_icon_->GetPreferredSize().height(); const int label_height = title_container_->GetHeightForWidth( frame_width - GetTitleLabelInsetsFromFrame().width()); const int title_height = std::max(icon_height, label_height) + title_margins_.height(); return content_margins_ + gfx::Insets::TLBR(std::max(title_height + header_height, close_height), GetMainImageLeftInsets(), 0, 0); } int BubbleFrameView::GetHeaderHeightForFrameWidth(int frame_width) const { return header_view_ && header_view_->GetVisible() ? header_view_->GetHeightForWidth(frame_width) : 0; } void BubbleFrameView::UpdateClientLayerCornerRadius() { // If the ClientView is painted to a layer we need to apply the appropriate // corner radius so that the ClientView and all its child layers are masked // appropriately to fit within the BubbleFrameView. if (GetWidget() && GetWidget()->client_view()->layer()) { GetWidget()->client_view()->layer()->SetRoundedCornerRadius( GetClientCornerRadii()); } } int BubbleFrameView::GetMainImageLeftInsets() const { if (!main_image_->GetVisible()) return 0; return main_image_->GetPreferredSize().width() - main_image_->GetBorder()->GetInsets().right(); } // static std::unique_ptr<Label> BubbleFrameView::CreateLabelWithContextAndStyle( const std::u16string& label_text, style::TextContext text_context, style::TextStyle text_style) { auto label = std::make_unique<Label>(label_text, text_context, text_style); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetCollapseWhenHidden(true); label->SetMultiLine(true); return label; } BEGIN_METADATA(BubbleFrameView, NonClientFrameView) ADD_PROPERTY_METADATA(absl::optional<double>, Progress) ADD_PROPERTY_METADATA(gfx::Insets, ContentMargins) ADD_PROPERTY_METADATA(gfx::Insets, FootnoteMargins) ADD_PROPERTY_METADATA(BubbleFrameView::PreferredArrowAdjustment, PreferredArrowAdjustment) ADD_PROPERTY_METADATA(int, CornerRadius) ADD_PROPERTY_METADATA(BubbleBorder::Arrow, Arrow) ADD_PROPERTY_METADATA(bool, DisplayVisibleArrow) ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_frame_view.cc
C++
unknown
42,261
// 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_BUBBLE_BUBBLE_FRAME_VIEW_H_ #define UI_VIEWS_BUBBLE_BUBBLE_FRAME_VIEW_H_ #include <memory> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/progress_bar.h" #include "ui/views/input_event_activation_protector.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/style/typography.h" #include "ui/views/window/non_client_view.h" namespace gfx { class RoundedCornersF; } namespace views { class FootnoteContainerView; class ImageView; // The non-client frame view of bubble-styled widgets. class VIEWS_EXPORT BubbleFrameView : public NonClientFrameView { public: METADATA_HEADER(BubbleFrameView); enum class PreferredArrowAdjustment { kMirror, kOffset }; BubbleFrameView(const gfx::Insets& title_margins, const gfx::Insets& content_margins); BubbleFrameView(const BubbleFrameView&) = delete; BubbleFrameView& operator=(BubbleFrameView&) = delete; ~BubbleFrameView() override; static std::unique_ptr<Label> CreateDefaultTitleLabel( const std::u16string& title_text); // Creates a close button used in the corner of the dialog. static std::unique_ptr<Button> CreateCloseButton( Button::PressedCallback callback); // Creates a minimize button used in the corner of the dialog. static std::unique_ptr<Button> CreateMinimizeButton( Button::PressedCallback callback); // NonClientFrameView: gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; bool GetClientMask(const gfx::Size& size, SkPath* path) const override; int NonClientHitTest(const gfx::Point& point) override; void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override; void ResetWindowControls() override; void UpdateWindowIcon() override; void UpdateWindowTitle() override; void SizeConstraintsChanged() override; void InsertClientView(ClientView* client_view) override; // Sets a custom view to be the dialog title instead of the |default_title_| // label. If there is an existing title view it will be deleted. void SetTitleView(std::unique_ptr<View> title_view); // Updates the subtitle label from the BubbleDialogDelegate. void UpdateSubtitle(); // Signals that the main image may have changed and needs to be fetched again. void UpdateMainImage(); // Updates the current progress value of |progress_indicator_|. If progress is // absent, hides |the progress_indicator|. void SetProgress(absl::optional<double> progress); // Returns the current progress value of |progress_indicator_| if // |progress_indicator_| is visible. absl::optional<double> GetProgress() const; // View: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; void PaintChildren(const PaintInfo& paint_info) override; void OnThemeChanged() override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; void VisibilityChanged(View* starting_from, bool is_visible) override; // Use SetBubbleBorder() not SetBorder(). void SetBubbleBorder(std::unique_ptr<BubbleBorder> border); const View* title() const { return custom_title_ ? custom_title_.get() : default_title_.get(); } View* title() { return const_cast<View*>( static_cast<const BubbleFrameView*>(this)->title()); } void SetContentMargins(const gfx::Insets& content_margins); gfx::Insets GetContentMargins() const; // Sets a custom header view for the dialog. If there is an existing header // view it will be deleted. The header view will be inserted above the title, // so outside the content bounds. If there is a close button, it will be shown // in front of the header view and will overlap with it. The title will be // shown below the header and / or the close button, depending on which is // lower. An example usage for a header view would be a banner image. void SetHeaderView(std::unique_ptr<View> view); // Sets a custom footnote view for the dialog. If there is an existing // footnote view it will be deleted. The footnote will be rendered at the // bottom of the bubble, after the content view. It is separated by a 1 dip // line and has a solid background by being embedded in a // FootnoteContainerView. An example footnote would be some help text. void SetFootnoteView(std::unique_ptr<View> view); View* GetFootnoteView() const; void SetFootnoteMargins(const gfx::Insets& footnote_margins); gfx::Insets GetFootnoteMargins() const; void SetPreferredArrowAdjustment(PreferredArrowAdjustment adjustment); PreferredArrowAdjustment GetPreferredArrowAdjustment() const; // TODO(crbug.com/1007604): remove this in favor of using // Widget::InitParams::accept_events. In the mean time, don't add new uses of // this flag. bool hit_test_transparent() const { return hit_test_transparent_; } void set_hit_test_transparent(bool hit_test_transparent) { hit_test_transparent_ = hit_test_transparent; } void set_use_anchor_window_bounds(bool use_anchor_window_bounds) { use_anchor_window_bounds_ = use_anchor_window_bounds; } // Set the corner radius of the bubble border. void SetCornerRadius(int radius); int GetCornerRadius() const; // Set the arrow of the bubble border. void SetArrow(BubbleBorder::Arrow arrow); BubbleBorder::Arrow GetArrow() const; // Specify whether the frame should include a visible, caret-shaped arrow. void SetDisplayVisibleArrow(bool display_visible_arrow); bool GetDisplayVisibleArrow() const; // Set the background color of the bubble border. // TODO(b/261653838): Update this function to use color id instead. void SetBackgroundColor(SkColor color); SkColor GetBackgroundColor() const; // For masking reasons, the ClientView may be painted to a textured layer. To // ensure bubbles that rely on the frame background color continue to work as // expected, we must set the background of the ClientView to match that of the // BubbleFrameView. void UpdateClientViewBackground(); // Given the size of the contents and the rect to point at, returns the bounds // of the bubble window. The bubble's arrow location may change if the bubble // does not fit on the monitor or anchor window (if one exists) and // |adjust_to_fit_available_bounds| is true. gfx::Rect GetUpdatedWindowBounds(const gfx::Rect& anchor_rect, const BubbleBorder::Arrow arrow, const gfx::Size& client_size, bool adjust_to_fit_available_bounds); Button* GetCloseButtonForTesting() { return close_; } View* GetHeaderViewForTesting() const { return header_view_; } // Update the |view_shown_time_stamp_| of input protector. A short time // from this point onward, input event will be ignored. void UpdateInputProtectorTimeStamp(); // Resets the time when view has been shown. Tests may need to call this // method if they use events that could be otherwise treated as unintended. // See IsPossiblyUnintendedInteraction(). void ResetViewShownTimeStampForTesting(); BubbleBorder* bubble_border() const { return bubble_border_; } protected: // Returns the available screen bounds if the frame were to show in |rect|. virtual gfx::Rect GetAvailableScreenBounds(const gfx::Rect& rect) const; // Returns the available anchor window bounds in the screen. // This will only be used if `use_anchor_window_bounds_` is true. virtual gfx::Rect GetAvailableAnchorWindowBounds() const; // Override and return true to allow client view to overlap into the title // area when HasTitle() returns false and/or ShouldShowCloseButton() returns // true. Returns false by default. virtual bool ExtendClientIntoTitle() const; bool IsCloseButtonVisible() const; gfx::Rect GetCloseButtonMirroredBounds() const; // Helper function that gives the corner radius values that should be applied // to the BubbleFrameView's client view. These values depend on the amount of // inset present on the client view and the presence of header and footer // views. gfx::RoundedCornersF GetClientCornerRadii() const; private: FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, RemoveFootnoteView); FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, LayoutWithIcon); FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, LayoutWithProgressIndicator); FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksClose); FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksMinimize); FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksAnchorBoundsChanged); FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, CloseReasons); FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, CloseMethods); FRIEND_TEST_ALL_PREFIXES(BubbleDialogDelegateViewTest, CreateDelegate); // Mirrors the bubble's arrow location on the |vertical| or horizontal axis, // if the generated window bounds don't fit in the given available bounds. void MirrorArrowIfOutOfBounds(bool vertical, const gfx::Rect& anchor_rect, const gfx::Size& client_size, const gfx::Rect& available_bounds); // Adjust the bubble's arrow offsets if the generated window bounds don't fit // in the given available bounds. void OffsetArrowIfOutOfBounds(const gfx::Rect& anchor_rect, const gfx::Size& client_size, const gfx::Rect& available_bounds); // The width of the frame for the given |client_width|. The result accounts // for the minimum title bar width and includes all insets and possible // snapping. It does not include the border. int GetFrameWidthForClientWidth(int client_width) const; // Calculates the size needed to accommodate the given client area. gfx::Size GetFrameSizeForClientSize(const gfx::Size& client_size) const; // True if the frame has a title area. This is the area affected by // |title_margins_|, including the icon and title text, but not the close // button. bool HasTitle() const; // The insets of the text portion of the title, based on |title_margins_| and // whether there is an icon and/or close button. Note there may be no title, // in which case only insets required for the close button are returned. gfx::Insets GetTitleLabelInsetsFromFrame() const; // The client_view insets (from the frame view) for the given |frame_width|. gfx::Insets GetClientInsetsForFrameWidth(int frame_width) const; // Gets the height of the |header_view_| given a |frame_width|. Returns zero // if there is no header view or if it is not visible. int GetHeaderHeightForFrameWidth(int frame_width) const; // Updates the corner radius of a layer backed client view for MD rounded // corners. // TODO(tluk): Use this and remove the need for GetClientMask() for clipping // client views to the bubble border's bounds. void UpdateClientLayerCornerRadius(); int GetMainImageLeftInsets() const; // Helper method to create a label with text style static std::unique_ptr<Label> CreateLabelWithContextAndStyle( const std::u16string& label_text, style::TextContext text_context, style::TextStyle text_style); // The bubble border. raw_ptr<BubbleBorder> bubble_border_ = nullptr; // Margins around the title label. const gfx::Insets title_margins_; // Margins between the content and the inside of the border, in pixels. gfx::Insets content_margins_; // Margins between the footnote view and the footnote container. gfx::Insets footnote_margins_; // The optional title icon. raw_ptr<ImageView> title_icon_ = nullptr; // The optional main image. raw_ptr<ImageView> main_image_ = nullptr; raw_ptr<BoxLayoutView> title_container_ = nullptr; // One of these fields is used as the dialog title. If SetTitleView is called // the custom title view is stored in |custom_title_| and this class assumes // ownership. Otherwise |default_title_| is used. raw_ptr<Label, DanglingUntriaged> default_title_ = nullptr; raw_ptr<View, DanglingUntriaged> custom_title_ = nullptr; raw_ptr<Label> subtitle_ = nullptr; // The optional close button (the X). raw_ptr<Button> close_ = nullptr; // The optional minimize button. raw_ptr<Button> minimize_ = nullptr; // The optional progress bar. Used to indicate bubble pending state. By // default it is invisible. raw_ptr<ProgressBar> progress_indicator_ = nullptr; // The optional header view. raw_ptr<View> header_view_ = nullptr; // A view to contain the footnote view, if it exists. raw_ptr<FootnoteContainerView, DanglingUntriaged> footnote_container_ = nullptr; // Set preference for how the arrow will be adjusted if the window is outside // the available bounds. PreferredArrowAdjustment preferred_arrow_adjustment_ = PreferredArrowAdjustment::kMirror; // If true the view is transparent to all hit tested events (i.e. click and // hover). DEPRECATED: See note above set_hit_test_transparent(). bool hit_test_transparent_ = false; // If true the bubble will try to stay inside the bounds returned by // `GetAvailableAnchorWindowBounds`. bool use_anchor_window_bounds_ = true; InputEventActivationProtector input_protector_; }; } // namespace views #endif // UI_VIEWS_BUBBLE_BUBBLE_FRAME_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_frame_view.h
C++
unknown
14,155
// 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/bubble/bubble_frame_view.h" #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.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/text_utils.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/bubble/footnote_container_view.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/metrics.h" #include "ui/views/test/button_test_api.h" #include "ui/views/test/test_layout_provider.h" #include "ui/views/test/test_views.h" #include "ui/views/test/view_metadata_test_utils.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_interactive_uitest_utils.h" #include "ui/views/window/dialog_client_view.h" namespace views { namespace { constexpr BubbleBorder::Arrow kArrow = BubbleBorder::TOP_LEFT; constexpr int kMargin = 6; constexpr gfx::Size kMinimumClientSize = gfx::Size(100, 200); constexpr gfx::Size kPreferredClientSize = gfx::Size(150, 250); constexpr gfx::Size kMaximumClientSize = gfx::Size(300, 300); // These account for non-client areas like the title bar, footnote etc. However // these do not take the bubble border into consideration. gfx::Size AddAdditionalSize(gfx::Size size) { size.Enlarge(12, 12); return size; } class TestBubbleFrameViewWidgetDelegate : public WidgetDelegate { public: explicit TestBubbleFrameViewWidgetDelegate(Widget* widget) : widget_(widget) {} ~TestBubbleFrameViewWidgetDelegate() override = default; // WidgetDelegate: Widget* GetWidget() override { return widget_; } const Widget* GetWidget() const override { return widget_; } View* GetContentsView() override { if (!contents_view_) { StaticSizedView* contents_view = new StaticSizedView(kPreferredClientSize); contents_view->set_minimum_size(kMinimumClientSize); contents_view->set_maximum_size(kMaximumClientSize); contents_view_ = contents_view; } return contents_view_; } bool ShouldShowCloseButton() const override { return should_show_close_; } void SetShouldShowCloseButton(bool should_show_close) { should_show_close_ = should_show_close; } private: const raw_ptr<Widget> widget_; raw_ptr<View> contents_view_ = nullptr; // Owned by |widget_|. bool should_show_close_ = false; }; class TestBubbleFrameView : public BubbleFrameView { public: explicit TestBubbleFrameView(ViewsTestBase* test_base) : BubbleFrameView(gfx::Insets(), gfx::Insets(kMargin)) { SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::STANDARD_SHADOW)); widget_ = std::make_unique<Widget>(); widget_delegate_ = std::make_unique<TestBubbleFrameViewWidgetDelegate>(widget_.get()); Widget::InitParams params = test_base->CreateParams(Widget::InitParams::TYPE_BUBBLE); params.delegate = widget_delegate_.get(); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget_->Init(std::move(params)); } TestBubbleFrameView(const TestBubbleFrameView&) = delete; TestBubbleFrameView& operator=(const TestBubbleFrameView&) = delete; ~TestBubbleFrameView() override = default; void SetAvailableAnchorWindowBounds(gfx::Rect bounds) { available_anchor_window_bounds_ = bounds; } BubbleBorder::Arrow GetBorderArrow() const { return bubble_border()->arrow(); } gfx::Insets GetBorderInsets() const { return bubble_border()->GetInsets(); } // BubbleFrameView: Widget* GetWidget() override { return widget_.get(); } const Widget* GetWidget() const override { return widget_.get(); } gfx::Rect GetAvailableScreenBounds(const gfx::Rect& rect) const override { return available_bounds_; } gfx::Rect GetAvailableAnchorWindowBounds() const override { return available_anchor_window_bounds_; } TestBubbleFrameViewWidgetDelegate* widget_delegate() { return widget_delegate_.get(); } private: const gfx::Rect available_bounds_ = gfx::Rect(0, 0, 1000, 1000); gfx::Rect available_anchor_window_bounds_; std::unique_ptr<TestBubbleFrameViewWidgetDelegate> widget_delegate_; std::unique_ptr<Widget> widget_; }; } // namespace class BubbleFrameViewTest : public ViewsTestBase { public: BubbleFrameViewTest() : views::ViewsTestBase( base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} BubbleFrameViewTest(const BubbleFrameViewTest&) = delete; BubbleFrameViewTest& operator=(const BubbleFrameViewTest&) = delete; ~BubbleFrameViewTest() override = default; }; TEST_F(BubbleFrameViewTest, GetBoundsForClientView) { TestBubbleFrameView frame(this); EXPECT_EQ(kArrow, frame.GetBorderArrow()); const gfx::Insets content_margins = frame.GetContentMargins(); const gfx::Insets insets = frame.GetBorderInsets(); const gfx::Rect client_view_bounds = frame.GetBoundsForClientView(); EXPECT_EQ(insets.left() + content_margins.left(), client_view_bounds.x()); EXPECT_EQ(insets.top() + content_margins.top(), client_view_bounds.y()); } TEST_F(BubbleFrameViewTest, GetBoundsForClientViewWithClose) { TestBubbleFrameView frame(this); frame.widget_delegate()->SetShouldShowCloseButton(true); frame.ResetWindowControls(); EXPECT_EQ(kArrow, frame.GetBorderArrow()); const gfx::Insets content_margins = frame.GetContentMargins(); const gfx::Insets insets = frame.GetBorderInsets(); const int close_margin = frame.GetCloseButtonForTesting()->height() + LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); const gfx::Rect client_view_bounds = frame.GetBoundsForClientView(); EXPECT_EQ(insets.left() + content_margins.left(), client_view_bounds.x()); EXPECT_EQ(insets.top() + content_margins.top() + close_margin, client_view_bounds.y()); } TEST_F(BubbleFrameViewTest, RemoveFootnoteView) { TestBubbleFrameView frame(this); EXPECT_EQ(nullptr, frame.footnote_container_.get()); auto footnote = std::make_unique<StaticSizedView>(gfx::Size(200, 200)); View* footnote_dummy_view = footnote.get(); frame.SetFootnoteView(std::move(footnote)); EXPECT_EQ(footnote_dummy_view->parent(), frame.footnote_container_); frame.SetFootnoteView(nullptr); EXPECT_EQ(nullptr, frame.footnote_container_.get()); } TEST_F(BubbleFrameViewTest, FootnoteContainerViewShouldMatchVisibilityOfFirstChild) { TestBubbleFrameView frame(this); std::unique_ptr<View> footnote = std::make_unique<StaticSizedView>(gfx::Size(200, 200)); footnote->SetVisible(false); View* footnote_dummy_view = footnote.get(); frame.SetFootnoteView(std::move(footnote)); View* footnote_container_view = footnote_dummy_view->parent(); EXPECT_FALSE(footnote_container_view->GetVisible()); footnote_dummy_view->SetVisible(true); EXPECT_TRUE(footnote_container_view->GetVisible()); footnote_dummy_view->SetVisible(false); EXPECT_FALSE(footnote_container_view->GetVisible()); } // Tests that the arrow is mirrored as needed to better fit the screen. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBounds) { TestBubbleFrameView frame(this); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test that the info bubble displays normally when it fits. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on left. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on left or top. frame.SetArrow(BubbleBorder::BOTTOM_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_RIGHT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on top. frame.SetArrow(BubbleBorder::BOTTOM_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on top and right. frame.SetArrow(BubbleBorder::BOTTOM_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 900); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on right. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 100, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 900); EXPECT_EQ(window_bounds.y(), 100); // Test bubble not fitting on bottom and right. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 900, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 900); EXPECT_EQ(window_bounds.bottom(), 900); // Test bubble not fitting at the bottom. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 900, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.bottom(), 900); // Test bubble not fitting at the bottom and left. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 900, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.x(), 100); EXPECT_EQ(window_bounds.bottom(), 900); } // Tests that the arrow is not moved when the info-bubble does not fit the // screen but moving it would make matter worse. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsMirroringFails) { TestBubbleFrameView frame(this); frame.SetArrow(BubbleBorder::TOP_LEFT); frame.GetUpdatedWindowBounds( gfx::Rect(400, 100, 50, 50), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(500, 700), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); } TEST_F(BubbleFrameViewTest, TestMirroringForCenteredArrow) { TestBubbleFrameView frame(this); // Test bubble not fitting above the anchor. frame.SetArrow(BubbleBorder::BOTTOM_CENTER); frame.GetUpdatedWindowBounds( gfx::Rect(100, 100, 50, 50), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_CENTER, // |delegate_arrow| gfx::Size(500, 700), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_CENTER, frame.GetBorderArrow()); // Test bubble not fitting below the anchor. frame.SetArrow(BubbleBorder::TOP_CENTER); frame.GetUpdatedWindowBounds( gfx::Rect(300, 800, 50, 50), // |anchor_rect| BubbleBorder::Arrow::TOP_CENTER, // |delegate_arrow| gfx::Size(500, 200), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.GetBorderArrow()); // Test bubble not fitting to the right of the anchor. frame.SetArrow(BubbleBorder::LEFT_CENTER); frame.GetUpdatedWindowBounds( gfx::Rect(800, 300, 50, 50), // |anchor_rect| BubbleBorder::Arrow::LEFT_CENTER, // |delegate_arrow| gfx::Size(200, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.GetBorderArrow()); // Test bubble not fitting to the left of the anchor. frame.SetArrow(BubbleBorder::RIGHT_CENTER); frame.GetUpdatedWindowBounds( gfx::Rect(100, 300, 50, 50), // |anchor_rect| BubbleBorder::Arrow::RIGHT_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.GetBorderArrow()); } // Test that the arrow will not be mirrored when // |adjust_to_fit_available_bounds| is false. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsDontTryMirror) { TestBubbleFrameView frame(this); frame.SetBubbleBorder(std::make_unique<BubbleBorder>( BubbleBorder::TOP_RIGHT, BubbleBorder::NO_SHADOW)); gfx::Rect window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 900, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(500, 500), // |client_size| false); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); // The coordinates should be pointing to anchor_rect from TOP_RIGHT. EXPECT_EQ(window_bounds.right(), 100); EXPECT_EQ(window_bounds.y(), 900); } // Test that the center arrow is moved as needed to fit the screen. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsCenterArrows) { TestBubbleFrameView frame(this); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Some of these tests may go away once --secondary-ui-md becomes the // default. Under Material Design mode, the BubbleBorder doesn't support all // "arrow" positions. If this changes, then the tests should be updated or // added for MD mode. // Test that the bubble displays normally when it fits. frame.SetArrow(BubbleBorder::BOTTOM_CENTER); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(500, 900, 50, 50), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x() + window_bounds.width() / 2, 525); frame.SetArrow(BubbleBorder::LEFT_CENTER); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 400, 50, 50), // |anchor_rect| BubbleBorder::Arrow::LEFT_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.y() + window_bounds.height() / 2, 425); frame.SetArrow(BubbleBorder::RIGHT_CENTER); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 400, 50, 50), // |anchor_rect| BubbleBorder::Arrow::RIGHT_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.y() + window_bounds.height() / 2, 425); // Test bubble not fitting left screen edge. frame.SetArrow(BubbleBorder::BOTTOM_CENTER); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(100, 900, 50, 50), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 0); // Test bubble not fitting right screen edge. frame.SetArrow(BubbleBorder::BOTTOM_CENTER); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 900, 50, 50), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_CENTER, // |delegate_arrow| gfx::Size(500, 500), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 1000); } // Tests that the arrow is mirrored as needed to better fit the anchor window's // bounds. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsForBubbleWithAnchorWindow) { TestBubbleFrameView frame(this); frame.SetAvailableAnchorWindowBounds(gfx::Rect(100, 100, 500, 500)); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test that the bubble displays normally when it fits. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on left for anchor window displays left aligned // with the left side of the anchor rect. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on left or top displays left and top aligned // with the left and bottom sides of the anchor rect. frame.SetArrow(BubbleBorder::BOTTOM_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_RIGHT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on top displays top aligned with the bottom side of // the anchor rect. frame.SetArrow(BubbleBorder::BOTTOM_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on top and right displays right and top aligned // with the right and bottom sides of the anchor rect. frame.SetArrow(BubbleBorder::BOTTOM_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(500, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::BOTTOM_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 500); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on right display in line with the right edge of // the anchor rect. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(500, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 500); EXPECT_EQ(window_bounds.y(), 200); // Test bubble not fitting on bottom and right displays in line with the right // edge of the anchor rect and the bottom in line with the top of the anchor // rect. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(500, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 500); EXPECT_EQ(window_bounds.bottom(), 500); // Test bubble not fitting at the bottom displays line with the top of the // anchor rect. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.bottom(), 500); // Test bubble not fitting at the bottom and left displays right aligned with // the anchor rect and the bottom in line with the top of the anchor rect. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); EXPECT_EQ(window_bounds.bottom(), 500); } // Tests that the arrow is mirrored as needed to better fit the screen. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsForBubbleWithAnchorWindowExitingScreen) { TestBubbleFrameView frame(this); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test bubble fitting anchor window and not fitting screen on right. // ________________________ // |screen _________________|__________ // | |anchor window ___|___ | // | | |bubble | | // | | |_______| | // | |_________________|__________| // |________________________| frame.SetAvailableAnchorWindowBounds(gfx::Rect(700, 200, 400, 400)); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(800, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.right(), 800); EXPECT_EQ(window_bounds.y(), 300); // Test bubble fitting anchor window and not fitting screen on right and // bottom. // ________________________ // |screen | // | _________________|__________ // | |anchor window ___|___ | // |______|_____________|bubble | | // | |_______| | // |____________________________| frame.SetAvailableAnchorWindowBounds(gfx::Rect(700, 700, 400, 400)); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(800, 800, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.right(), 800); EXPECT_EQ(window_bounds.bottom(), 800); // Test bubble not fitting anchor window on bottom and not fitting screen on // right. // ________________________ // |screen _________________|__________ // | |anchor window | | // | | ___|___ | // | |_____________|bubble |______| // | |_______| // |________________________| frame.SetAvailableAnchorWindowBounds(gfx::Rect(700, 200, 400, 400)); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(800, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.right(), 800); EXPECT_EQ(window_bounds.bottom(), 500); } // Tests that bubbles with `use_anchor_window_bounds_` set to false will not // apply an offset to try to make them fit inside the anchor window bounds. TEST_F(BubbleFrameViewTest, BubbleNotUsingAnchorWindowBounds) { TestBubbleFrameView frame(this); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test bubble not fitting anchor window on bottom and not fitting screen on // right. // ________________________ // |screen _________________|__________ // | |anchor window | | // | | ___|___ | // | |_____________|bubble |______| // | |_______| // |________________________| frame.SetAvailableAnchorWindowBounds(gfx::Rect(700, 200, 400, 400)); frame.set_use_anchor_window_bounds(false); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(800, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.right(), 800); // Bubble will not try to fit inside the anchor window. EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_GT(window_bounds.bottom(), 500); } // Tests that the arrow is mirrored as needed to better fit the anchor window's // bounds. TEST_F(BubbleFrameViewTest, MirroringNotStickyForGetUpdatedWindowBounds) { TestBubbleFrameView frame(this); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test bubble fitting anchor window and not fitting screen on right. frame.SetAvailableAnchorWindowBounds(gfx::Rect(700, 200, 400, 400)); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(800, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.right(), 800); EXPECT_EQ(window_bounds.y(), 300); // Test that the bubble mirrors again if it can fit on screen with its // original anchor. window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(700, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); // The window should be right aligned with the anchor_rect. EXPECT_EQ(window_bounds.x(), 700); EXPECT_EQ(window_bounds.y(), 300); } // Tests that the arrow is offset as needed to better fit the window. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsForBubbleSetToOffset) { TestBubbleFrameView frame(this); frame.SetAvailableAnchorWindowBounds(gfx::Rect(100, 100, 500, 500)); frame.SetPreferredArrowAdjustment( BubbleFrameView::PreferredArrowAdjustment::kOffset); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test that the bubble displays normally when it fits. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); // Test bubble not fitting left window edge displayed against left window // edge. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(200, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 100); // Test bubble not fitting right window edge displays against the right edge // of the anchor window. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(500, 200, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 600); // Test bubble fitting anchor window and not fitting screen on right displays // against the right edge of the screen. frame.SetAvailableAnchorWindowBounds(gfx::Rect(800, 300, 500, 500)); frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(900, 500, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(250, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.right(), 1000); } // Tests that the arrow is offset as needed to better fit the window for // windows larger than the available bounds. TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsForBubbleSetToOffsetLargerThanAvailableBounds) { TestBubbleFrameView frame(this); frame.SetAvailableAnchorWindowBounds(gfx::Rect(200, 200, 500, 500)); frame.SetPreferredArrowAdjustment( BubbleFrameView::PreferredArrowAdjustment::kOffset); gfx::Rect window_bounds; frame.SetBubbleBorder( std::make_unique<BubbleBorder>(kArrow, BubbleBorder::NO_SHADOW)); // Test that the bubble exiting right side of anchor window displays against // left edge of anchor window bounds if larger than anchor window. frame.SetArrow(BubbleBorder::TOP_LEFT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(300, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_LEFT, // |delegate_arrow| gfx::Size(600, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.x(), 200); // Test that the bubble exiting left side of anchor window displays against // right edge of anchor window bounds if larger than anchor window. frame.SetArrow(BubbleBorder::TOP_RIGHT); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(300, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::TOP_RIGHT, // |delegate_arrow| gfx::Size(600, 250), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.GetBorderArrow()); // Check that the right edge of the bubble equals the right edge of the // anchor window. EXPECT_EQ(window_bounds.right(), 700); // Test that the bubble exiting bottom side of anchor window displays against // top edge of anchor window bounds if larger than anchor window. frame.SetArrow(BubbleBorder::LEFT_TOP); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(400, 400, 0, 0), // |anchor_rect| BubbleBorder::Arrow::LEFT_TOP, // |delegate_arrow| gfx::Size(250, 600), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::LEFT_TOP, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.y(), 200); // Test that the bubble exiting top side of anchor window displays against // bottom edge of anchor window bounds if larger than anchor window. frame.SetArrow(BubbleBorder::LEFT_BOTTOM); window_bounds = frame.GetUpdatedWindowBounds( gfx::Rect(300, 300, 0, 0), // |anchor_rect| BubbleBorder::Arrow::LEFT_BOTTOM, // |delegate_arrow| gfx::Size(250, 600), // |client_size| true); // |adjust_to_fit_available_bounds| EXPECT_EQ(BubbleBorder::LEFT_BOTTOM, frame.GetBorderArrow()); EXPECT_EQ(window_bounds.bottom(), 700); } TEST_F(BubbleFrameViewTest, GetPreferredSize) { // Test border/insets. TestBubbleFrameView frame(this); gfx::Rect preferred_rect(frame.GetPreferredSize()); // Expect that a border has been added to the preferred size. preferred_rect.Inset(frame.GetBorderInsets()); gfx::Size expected_size = AddAdditionalSize(kPreferredClientSize); EXPECT_EQ(expected_size, preferred_rect.size()); } TEST_F(BubbleFrameViewTest, GetPreferredSizeWithFootnote) { // Test footnote view: adding a footnote should increase the preferred size, // but only when the footnote is visible. TestBubbleFrameView frame(this); constexpr int kFootnoteHeight = 20; const gfx::Size no_footnote_size = frame.GetPreferredSize(); std::unique_ptr<View> footnote = std::make_unique<StaticSizedView>(gfx::Size(10, kFootnoteHeight)); footnote->SetVisible(false); View* footnote_dummy_view = footnote.get(); frame.SetFootnoteView(std::move(footnote)); EXPECT_EQ(no_footnote_size, frame.GetPreferredSize()); // No change. footnote_dummy_view->SetVisible(true); gfx::Size with_footnote_size = no_footnote_size; constexpr int kFootnoteTopBorderThickness = 1; with_footnote_size.Enlarge(0, kFootnoteHeight + kFootnoteTopBorderThickness + frame.GetContentMargins().height()); EXPECT_EQ(with_footnote_size, frame.GetPreferredSize()); footnote_dummy_view->SetVisible(false); EXPECT_EQ(no_footnote_size, frame.GetPreferredSize()); } TEST_F(BubbleFrameViewTest, GetMinimumSize) { TestBubbleFrameView frame(this); gfx::Rect minimum_rect(frame.GetMinimumSize()); // Expect that a border has been added to the minimum size. minimum_rect.Inset(frame.GetBorderInsets()); gfx::Size expected_size = AddAdditionalSize(kMinimumClientSize); EXPECT_EQ(expected_size, minimum_rect.size()); } TEST_F(BubbleFrameViewTest, GetMaximumSize) { TestBubbleFrameView frame(this); gfx::Rect maximum_rect(frame.GetMaximumSize()); #if BUILDFLAG(IS_WIN) // On Windows, GetMaximumSize causes problems with DWM, so it should just be 0 // (unlimited). See http://crbug.com/506206. EXPECT_EQ(gfx::Size(), maximum_rect.size()); #else maximum_rect.Inset(frame.GetBorderInsets()); // Should ignore the contents view's maximum size and use the preferred size. gfx::Size expected_size = AddAdditionalSize(kPreferredClientSize); EXPECT_EQ(expected_size, maximum_rect.size()); #endif } TEST_F(BubbleFrameViewTest, LayoutWithHeader) { // Test header view: adding a header should increase the preferred size, but // only when the header is visible. TestBubbleFrameView frame(this); constexpr int kHeaderHeight = 20; const gfx::Size no_header_size = frame.GetPreferredSize(); std::unique_ptr<View> header = std::make_unique<StaticSizedView>(gfx::Size(10, kHeaderHeight)); header->SetVisible(false); View* header_raw_pointer = header.get(); frame.SetHeaderView(std::move(header)); EXPECT_EQ(no_header_size, frame.GetPreferredSize()); // No change. header_raw_pointer->SetVisible(true); gfx::Size with_header_size = no_header_size; with_header_size.Enlarge(0, kHeaderHeight); EXPECT_EQ(with_header_size, frame.GetPreferredSize()); header_raw_pointer->SetVisible(false); EXPECT_EQ(no_header_size, frame.GetPreferredSize()); } TEST_F(BubbleFrameViewTest, LayoutWithHeaderAndCloseButton) { // Test header view with close button: the client bounds should be positioned // below the header and close button, whichever is further down. TestBubbleFrameView frame(this); frame.widget_delegate()->SetShouldShowCloseButton(true); const int close_margin = frame.GetCloseButtonForTesting()->height() + LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); const gfx::Insets content_margins = frame.GetContentMargins(); const gfx::Insets insets = frame.GetBorderInsets(); // Header is smaller than close button + margin, expect bounds to be below the // close button. frame.SetHeaderView( std::make_unique<StaticSizedView>(gfx::Size(10, close_margin - 1))); gfx::Rect client_view_bounds = frame.GetBoundsForClientView(); EXPECT_EQ(insets.top() + content_margins.top() + close_margin, client_view_bounds.y()); // Header is larger than close button + margin, expect bounds to be below the // header view. frame.SetHeaderView( std::make_unique<StaticSizedView>(gfx::Size(10, close_margin + 1))); client_view_bounds = frame.GetBoundsForClientView(); EXPECT_EQ(insets.top() + content_margins.top() + close_margin + 1, client_view_bounds.y()); } TEST_F(BubbleFrameViewTest, MetadataTest) { TestBubbleFrameView frame(this); TestBubbleFrameView* frame_pointer = &frame; test::TestViewMetadata(frame_pointer); } namespace { class TestBubbleDialogDelegateView : public BubbleDialogDelegateView { public: TestBubbleDialogDelegateView() : BubbleDialogDelegateView(nullptr, BubbleBorder::NONE) { set_shadow(BubbleBorder::NO_SHADOW); SetAnchorRect(gfx::Rect()); DialogDelegate::SetButtons(ui::DIALOG_BUTTON_OK); } TestBubbleDialogDelegateView(const TestBubbleDialogDelegateView&) = delete; TestBubbleDialogDelegateView& operator=(const TestBubbleDialogDelegateView&) = delete; ~TestBubbleDialogDelegateView() override = default; void ChangeTitle(const std::u16string& title) { title_ = title; // Note UpdateWindowTitle() always does a layout, which will be invalid if // the Widget needs to change size. But also SizeToContents() _only_ does a // layout if the size is actually changing. GetWidget()->UpdateWindowTitle(); SizeToContents(); } void ChangeSubtitle(const std::u16string& subtitle) { subtitle_ = subtitle; GetBubbleFrameView()->UpdateSubtitle(); SizeToContents(); } // BubbleDialogDelegateView: using BubbleDialogDelegateView::SetAnchorView; using BubbleDialogDelegateView::SizeToContents; std::u16string GetWindowTitle() const override { return title_; } std::u16string GetSubtitle() const override { return subtitle_; } bool ShouldShowWindowTitle() const override { return !title_.empty(); } bool ShouldShowCloseButton() const override { return should_show_close_; } void SetShouldShowCloseButton(bool should_show_close) { should_show_close_ = should_show_close; } gfx::Size CalculatePreferredSize() const override { return gfx::Size(200, 200); } BubbleFrameView* GetBubbleFrameView() const { return static_cast<BubbleFrameView*>( GetWidget()->non_client_view()->frame_view()); } private: std::u16string title_; std::u16string subtitle_; bool should_show_close_ = false; }; class TestAnchor { public: explicit TestAnchor(Widget::InitParams params) { params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget_.Init(std::move(params)); widget_.Show(); } TestAnchor(const TestAnchor&) = delete; TestAnchor& operator=(const TestAnchor&) = delete; Widget& widget() { return widget_; } private: Widget widget_; }; // BubbleDialogDelegate with no margins to test width snapping. class TestWidthSnapDelegate : public TestBubbleDialogDelegateView { public: TestWidthSnapDelegate(TestAnchor* anchor, bool should_snap) { DialogDelegate::SetButtons(should_snap ? ui::DIALOG_BUTTON_OK : ui::DIALOG_BUTTON_NONE); SetAnchorView(anchor->widget().GetContentsView()); set_margins(gfx::Insets()); BubbleDialogDelegateView::CreateBubble(this); GetWidget()->Show(); } TestWidthSnapDelegate(const TestWidthSnapDelegate&) = delete; TestWidthSnapDelegate& operator=(const TestWidthSnapDelegate&) = delete; }; } // namespace // This test ensures that if the installed LayoutProvider snaps dialog widths, // BubbleFrameView correctly sizes itself to that width. TEST_F(BubbleFrameViewTest, WidthSnaps) { test::TestLayoutProvider provider; TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); { TestWidthSnapDelegate* const delegate = new TestWidthSnapDelegate(&anchor, true); WidgetAutoclosePtr widget(delegate->GetWidget()); EXPECT_EQ(delegate->GetPreferredSize().width(), delegate->GetWidget()->GetWindowBoundsInScreen().width()); } constexpr int kTestWidth = 300; provider.SetSnappedDialogWidth(kTestWidth); { TestWidthSnapDelegate* const delegate = new TestWidthSnapDelegate(&anchor, true); WidgetAutoclosePtr widget(delegate->GetWidget()); // The Widget's snapped width should exactly match the width returned by the // LayoutProvider. EXPECT_EQ(kTestWidth, delegate->GetWidget()->GetWindowBoundsInScreen().width()); } { // If the DialogDelegate asks not to snap, it should not snap. TestWidthSnapDelegate* const delegate = new TestWidthSnapDelegate(&anchor, false); WidgetAutoclosePtr widget(delegate->GetWidget()); EXPECT_EQ(delegate->GetPreferredSize().width(), delegate->GetWidget()->GetWindowBoundsInScreen().width()); } } // Tests edge cases when the frame's title view starts to wrap text. This is to // ensure that the calculations BubbleFrameView does to determine the Widget // size for a given client view are consistent with the eventual size that the // client view takes after Layout(). TEST_F(BubbleFrameViewTest, LayoutEdgeCases) { test::TestLayoutProvider provider; auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); // Even though the bubble has default margins, the dialog view should have // been given its preferred size. EXPECT_FALSE(delegate->margins().IsEmpty()); EXPECT_EQ(delegate->size(), delegate->GetPreferredSize()); // Starting with a short title. std::u16string title(1, 'i'); delegate->ChangeTitle(title); const int min_bubble_height = bubble->GetWindowBoundsInScreen().height(); EXPECT_LT(delegate->GetPreferredSize().height(), min_bubble_height); // Grow the title incrementally until word wrap is required. There should // never be a point where the BubbleFrameView over- or under-estimates the // size required for the title. If it did, it would cause SizeToContents() to // Widget size requiring the subsequent Layout() to fill the remaining client // area with something other than |delegate|'s preferred size. while (bubble->GetWindowBoundsInScreen().height() == min_bubble_height) { title += ' '; title += 'i'; delegate->ChangeTitle(title); EXPECT_EQ(delegate->GetPreferredSize(), delegate->size()) << title; } // Sanity check that something interesting happened. The bubble should have // grown by "a line" for the wrapped title, and the title should have reached // a length that would have likely caused word wrap. A typical result would be // a +17-20 change in height and title length of 53 characters. const int two_line_height = bubble->GetWindowBoundsInScreen().height(); EXPECT_LT(12, two_line_height - min_bubble_height); EXPECT_GT(25, two_line_height - min_bubble_height); EXPECT_LT(30u, title.size()); EXPECT_GT(80u, title.size()); // Now add dialog snapping. provider.SetSnappedDialogWidth(300); delegate->SizeToContents(); // Height should go back to |min_bubble_height| since the window is wider: // word wrapping should no longer happen. EXPECT_EQ(min_bubble_height, bubble->GetWindowBoundsInScreen().height()); EXPECT_EQ(300, bubble->GetWindowBoundsInScreen().width()); // Now we are allowed to diverge from the client view width, but not height. EXPECT_EQ(delegate->GetPreferredSize().height(), delegate->height()); EXPECT_LT(delegate->GetPreferredSize().width(), delegate->width()); EXPECT_GT(300, delegate->width()); // Greater, since there are margins. const gfx::Size snapped_size = delegate->size(); const size_t old_title_size = title.size(); // Grow the title again with width snapping until word wrapping occurs. while (bubble->GetWindowBoundsInScreen().height() == min_bubble_height) { title += ' '; title += 'i'; delegate->ChangeTitle(title); EXPECT_EQ(snapped_size, delegate->size()) << title; } // Change to the height should have been the same as before. Title should // have grown about 50%. EXPECT_EQ(two_line_height, bubble->GetWindowBoundsInScreen().height()); EXPECT_LT(15u, title.size() - old_title_size); EXPECT_GT(40u, title.size() - old_title_size); // When |anchor| goes out of scope it should take |bubble| with it. } // Tests edge cases when the frame's title view starts to wrap text when a // header view is set. This is to ensure the title leaves enough space for the // close button when there is a header or not. TEST_F(BubbleFrameViewTest, LayoutEdgeCasesWithHeader) { test::TestLayoutProvider provider; auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); delegate->SetShouldShowCloseButton(true); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); BubbleFrameView* frame = delegate->GetBubbleFrameView(); const int close_margin = frame->GetCloseButtonForTesting()->height() + LayoutProvider::Get()->GetDistanceMetric(DISTANCE_CLOSE_BUTTON_MARGIN); // Set a header view that is 1 dip smaller than the close button. frame->SetHeaderView( std::make_unique<StaticSizedView>(gfx::Size(10, close_margin - 1))); // Starting with a short title. std::u16string title(1, 'i'); delegate->ChangeTitle(title); const int min_bubble_height = bubble->GetWindowBoundsInScreen().height(); // Grow the title incrementally until word wrap is required. while (bubble->GetWindowBoundsInScreen().height() == min_bubble_height) { title += ' '; title += 'i'; delegate->ChangeTitle(title); } // Sanity check that something interesting happened. The bubble should have // grown by "a line" for the wrapped title. const int two_line_height = bubble->GetWindowBoundsInScreen().height(); EXPECT_LT(12, two_line_height - min_bubble_height); EXPECT_GT(25, two_line_height - min_bubble_height); // Now grow the header view to be the same size as the close button. This // should allow the text to fit into a single line again as it is now allowed // to grow below the close button. frame->SetHeaderView( std::make_unique<StaticSizedView>(gfx::Size(10, close_margin))); delegate->SizeToContents(); // Height should go back to |min_bubble_height| + 1 since the window is wider: // word wrapping should no longer happen, the 1 dip extra height is caused by // growing the header view. EXPECT_EQ(min_bubble_height + 1, bubble->GetWindowBoundsInScreen().height()); // When |anchor| goes out of scope it should take |bubble| with it. } // Layout tests with Subtitle label. // This will test adding a Subtitle and wrap-around case for Subtitle. TEST_F(BubbleFrameViewTest, LayoutSubtitleEdgeCases) { test::TestLayoutProvider provider; auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); // Even though the bubble has default margins, the dialog view should have // been given its preferred size. EXPECT_FALSE(delegate->margins().IsEmpty()); EXPECT_EQ(delegate->size(), delegate->GetPreferredSize()); // Add title to bubble frame view. delegate->ChangeTitle(u"This is a title"); int min_bubble_height = bubble->GetWindowBoundsInScreen().height(); EXPECT_LT(delegate->GetPreferredSize().height(), min_bubble_height); // Add a short subtitle to guarantee a one-line addition. // Line height can vary depending on the platform so check // boundary where the height diff is between 12 and 18. // (12 < single_line_height < 18) std::u16string subtitle(1, 'j'); delegate->ChangeSubtitle(subtitle); int line_height_diff = bubble->GetWindowBoundsInScreen().height() - min_bubble_height; EXPECT_GT(line_height_diff, 12); EXPECT_LT(line_height_diff, 18); // Set the new min bubble height with a Subtitle added. min_bubble_height = bubble->GetWindowBoundsInScreen().height(); // Grow the subtitle incrementally until word wrap is required. while (bubble->GetWindowBoundsInScreen().height() == min_bubble_height) { subtitle += u" j"; delegate->ChangeSubtitle(subtitle); } // Subtitle wrap should have increased by one line. line_height_diff = bubble->GetWindowBoundsInScreen().height() - min_bubble_height; EXPECT_GT(line_height_diff, 12); EXPECT_LT(line_height_diff, 18); } TEST_F(BubbleFrameViewTest, LayoutWithIcon) { auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); SkBitmap bitmap; bitmap.allocN32Pixels(20, 80); bitmap.eraseColor(SK_ColorYELLOW); delegate->SetIcon(ui::ImageModel::FromImageSkia( gfx::ImageSkia::CreateFrom1xBitmap(bitmap))); delegate->SetShowIcon(true); Widget* widget = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); widget->Show(); delegate->ChangeTitle(u"test title"); BubbleFrameView* frame = delegate->GetBubbleFrameView(); View* icon = frame->title_icon_; View* title = frame->title_container_; // There should be equal amounts of space on the left and right of the icon. EXPECT_EQ(icon->x() * 2 + icon->width(), title->x()); // The title should be vertically centered relative to the icon. EXPECT_LT(title->height(), icon->height()); const int title_offset_y = (icon->height() - title->height()) / 2; EXPECT_EQ(icon->y() + title_offset_y, title->y()); } // Test the size of the bubble allows a |gfx::NO_ELIDE| title to fit, even if // there is no content. TEST_F(BubbleFrameViewTest, NoElideTitle) { test::TestLayoutProvider provider; auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); // Make sure the client area size doesn't interfere with the final size. delegate->SetPreferredSize(gfx::Size()); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); // Before changing the title, get the base width of the bubble when there's no // title or content in it. const int empty_bubble_width = bubble->GetClientAreaBoundsInScreen().width(); std::u16string title = u"This is a title string"; delegate->ChangeTitle(title); Label* title_label = static_cast<Label*>(delegate->GetBubbleFrameView()->title()); // Sanity check: Title labels default to multiline and elide tail. Either of // which result in the Layout system making the title and resulting dialog // very narrow. EXPECT_EQ(gfx::ELIDE_TAIL, title_label->GetElideBehavior()); EXPECT_TRUE(title_label->GetMultiLine()); EXPECT_GT(empty_bubble_width, title_label->size().width()); EXPECT_EQ(empty_bubble_width, bubble->GetClientAreaBoundsInScreen().width()); // Set the title to a non-eliding label. title_label->SetElideBehavior(gfx::NO_ELIDE); title_label->SetMultiLine(false); // Update the bubble size now that some properties of the title have changed. delegate->SizeToContents(); // The title/bubble should now be bigger than in multiline tail-eliding mode. EXPECT_LT(empty_bubble_width, title_label->size().width()); EXPECT_LT(empty_bubble_width, bubble->GetClientAreaBoundsInScreen().width()); // Make sure the bubble is wide enough to fit the title's full size. Frame // sizing is done off the title label's minimum size. But since that label is // set to NO_ELIDE, the minimum size should match the preferred size. EXPECT_GE(bubble->GetClientAreaBoundsInScreen().width(), title_label->GetPreferredSize().width()); EXPECT_LE(title_label->GetPreferredSize().width(), title_label->size().width()); EXPECT_EQ(title, title_label->GetDisplayTextForTesting()); } // Ensures that clicks are ignored for short time after view has been shown. TEST_F(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksClose) { auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); delegate->SetShouldShowCloseButton(true); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); BubbleFrameView* frame = delegate->GetBubbleFrameView(); test::ButtonTestApi(frame->close_) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE)); EXPECT_FALSE(bubble->IsClosed()); test::ButtonTestApi(frame->close_) .NotifyClick(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()), ui::EF_NONE, ui::EF_NONE)); EXPECT_TRUE(bubble->IsClosed()); } // Ensures that clicks are ignored for short time after view has been shown. TEST_F(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksMinimize) { auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); delegate->SetCanMinimize(true); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); BubbleFrameView* frame = delegate->GetBubbleFrameView(); test::ButtonTestApi(frame->minimize_) .NotifyClick(ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE)); EXPECT_FALSE(bubble->IsClosed()); views::test::PropertyWaiter minimize_waiter( base::BindRepeating(&Widget::IsMinimized, base::Unretained(bubble)), true); test::ButtonTestApi(frame->minimize_) .NotifyClick(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()), ui::EF_NONE, ui::EF_NONE)); EXPECT_TRUE(minimize_waiter.Wait()); EXPECT_TRUE(bubble->IsMinimized()); } // Ensures that clicks are ignored for short time after anchor view bounds // changed. TEST_F(BubbleFrameViewTest, IgnorePossiblyUnintendedClicksAnchorBoundsChanged) { auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); delegate->SetCanMinimize(true); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE); BubbleFrameView* frame = delegate->GetBubbleFrameView(); test::ButtonTestApi(frame->minimize_).NotifyClick(mouse_event); auto* widget = delegate->GetWidget(); auto* dialog = delegate->GetDialogClientView(); auto* ok_button = dialog->ok_button(); test::ButtonTestApi(ok_button).NotifyClick(mouse_event); EXPECT_FALSE(bubble->IsMinimized()); EXPECT_FALSE(widget->IsClosed()); task_environment()->FastForwardBy( base::Milliseconds(GetDoubleClickInterval())); anchor.widget().SetBounds(gfx::Rect(10, 10, 100, 100)); ui::MouseEvent mouse_event_1(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE); test::ButtonTestApi(ok_button).NotifyClick(mouse_event_1); test::ButtonTestApi(frame->minimize_).NotifyClick(mouse_event_1); EXPECT_FALSE(widget->IsClosed()); EXPECT_FALSE(bubble->IsMinimized()); test::ButtonTestApi(ok_button).NotifyClick(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow() + base::Milliseconds(GetDoubleClickInterval()), ui::EF_NONE, ui::EF_NONE)); EXPECT_TRUE(widget->IsClosed()); } // Ensures that layout is correct when the progress indicator is visible. TEST_F(BubbleFrameViewTest, LayoutWithProgressIndicator) { auto delegate_unique = std::make_unique<TestBubbleDialogDelegateView>(); TestBubbleDialogDelegateView* const delegate = delegate_unique.get(); TestAnchor anchor(CreateParams(Widget::InitParams::TYPE_WINDOW)); delegate->SetAnchorView(anchor.widget().GetContentsView()); Widget* bubble = BubbleDialogDelegateView::CreateBubble(std::move(delegate_unique)); bubble->Show(); BubbleFrameView* frame = delegate->GetBubbleFrameView(); frame->SetProgress(/*infinite animation*/ -1); View* progress_indicator = frame->progress_indicator_; // Ensures the progress indicator is visible and takes full widget width. EXPECT_TRUE(progress_indicator->GetVisible()); EXPECT_EQ(progress_indicator->x(), 0); EXPECT_EQ(progress_indicator->y(), 0); EXPECT_EQ(progress_indicator->width(), bubble->GetWindowBoundsInScreen().width()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/bubble_frame_view_unittest.cc
C++
unknown
63,446
// 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/bubble/footnote_container_view.h" #include <memory> #include <utility> #include "cc/paint/paint_flags.h" #include "ui/base/metadata/metadata_impl_macros.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/geometry/rect_f.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/layout/box_layout.h" namespace views { namespace { // A solid color background where the bottom two corners are rounded. class HalfRoundedRectBackground : public Background { public: explicit HalfRoundedRectBackground(SkColor color, float radius) : radius_(radius) { SetNativeControlColor(color); } HalfRoundedRectBackground() = delete; HalfRoundedRectBackground(const HalfRoundedRectBackground&) = delete; HalfRoundedRectBackground& operator=(const HalfRoundedRectBackground&) = delete; ~HalfRoundedRectBackground() override = default; // Background: void Paint(gfx::Canvas* canvas, View* view) const override { cc::PaintFlags flags; flags.setAntiAlias(true); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(get_color()); // Draw a rounded rect that spills outside of the clipping area, so that the // rounded corners only show in the bottom 2 corners. gfx::RectF spilling_rect(view->GetLocalBounds()); spilling_rect.set_y(spilling_rect.x() - radius_); spilling_rect.set_height(spilling_rect.height() + radius_); canvas->DrawRoundRect(spilling_rect, radius_, flags); } private: float radius_; }; } // namespace FootnoteContainerView::FootnoteContainerView(const gfx::Insets& margins, std::unique_ptr<View> child_view, float corner_radius) : corner_radius_(corner_radius) { SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, margins, 0)); auto* child_view_ptr = AddChildView(std::move(child_view)); SetVisible(child_view_ptr->GetVisible()); } FootnoteContainerView::~FootnoteContainerView() = default; void FootnoteContainerView::SetCornerRadius(float corner_radius) { corner_radius_ = corner_radius; if (GetWidget()) ResetBackground(); } void FootnoteContainerView::OnThemeChanged() { View::OnThemeChanged(); ResetBorder(); ResetBackground(); } void FootnoteContainerView::ChildVisibilityChanged(View* child) { DCHECK_EQ(1u, children().size()); SetVisible(child->GetVisible()); } void FootnoteContainerView::ResetBackground() { if (!GetWidget()) return; SkColor background_color = GetColorProvider()->GetColor(ui::kColorBubbleFooterBackground); SetBackground(std::make_unique<HalfRoundedRectBackground>(background_color, corner_radius_)); } void FootnoteContainerView::ResetBorder() { if (!GetWidget()) return; SetBorder(CreateSolidSidedBorder( gfx::Insets::TLBR(1, 0, 0, 0), GetColorProvider()->GetColor(ui::kColorBubbleFooterBorder))); } BEGIN_METADATA(FootnoteContainerView, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/footnote_container_view.cc
C++
unknown
3,345
// 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_BUBBLE_FOOTNOTE_CONTAINER_VIEW_H_ #define UI_VIEWS_BUBBLE_FOOTNOTE_CONTAINER_VIEW_H_ #include <memory> #include "ui/views/view.h" namespace views { // A container that changes visibility with its contents, and draws a solid // background with rounded corners at the bottom. class FootnoteContainerView : public View { public: METADATA_HEADER(FootnoteContainerView); FootnoteContainerView() = delete; FootnoteContainerView(const gfx::Insets& margins, std::unique_ptr<View> child_view, float corner_radius); FootnoteContainerView(const FootnoteContainerView&) = delete; FootnoteContainerView& operator=(const FootnoteContainerView&) = delete; ~FootnoteContainerView() override; void SetCornerRadius(float corner_radius); // View: void OnThemeChanged() override; void ChildVisibilityChanged(View* child) override; private: void ResetBackground(); void ResetBorder(); float corner_radius_; }; } // namespace views #endif // UI_VIEWS_BUBBLE_FOOTNOTE_CONTAINER_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/footnote_container_view.h
C++
unknown
1,216
// 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/bubble/info_bubble.h" #include <memory> #include <utility> #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/widget/widget.h" namespace views { namespace { // The visible width of bubble borders (differs from the actual width) in px. constexpr int kBubbleBorderVisibleWidth = 1; } // namespace class InfoBubbleFrame : public BubbleFrameView { public: explicit InfoBubbleFrame(const gfx::Insets& content_margins) : BubbleFrameView(gfx::Insets(), content_margins) {} InfoBubbleFrame(const InfoBubbleFrame&) = delete; InfoBubbleFrame& operator=(const InfoBubbleFrame&) = delete; ~InfoBubbleFrame() override = default; gfx::Rect GetAvailableScreenBounds(const gfx::Rect& rect) const override { return available_bounds_; } void set_available_bounds(const gfx::Rect& available_bounds) { available_bounds_ = available_bounds; } private: // Bounds that this frame should try to keep bubbles within (screen coords). gfx::Rect available_bounds_; }; InfoBubble::InfoBubble(View* anchor, BubbleBorder::Arrow arrow, const std::u16string& message) : BubbleDialogDelegateView(anchor, arrow) { DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE); set_margins(LayoutProvider::Get()->GetInsetsMetric( InsetsMetric::INSETS_TOOLTIP_BUBBLE)); SetCanActivate(false); SetAccessibleWindowRole(ax::mojom::Role::kAlertDialog); // TODO(pbos): This hacks around a bug where focus order in the parent dialog // breaks because it tries to focus InfoBubble without anything focusable in // it. FocusSearch should handle this case and this should be removable. set_focus_traversable_from_anchor_view(false); SetLayoutManager(std::make_unique<FillLayout>()); label_ = AddChildView(std::make_unique<Label>(message)); label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); label_->SetMultiLine(true); } InfoBubble::~InfoBubble() = default; void InfoBubble::Show() { BubbleDialogDelegateView::CreateBubble(this); UpdatePosition(); } void InfoBubble::Hide() { Widget* widget = GetWidget(); if (widget && !widget->IsClosed()) widget->Close(); } std::unique_ptr<NonClientFrameView> InfoBubble::CreateNonClientFrameView( Widget* widget) { DCHECK(!frame_); auto frame = std::make_unique<InfoBubbleFrame>(margins()); frame->set_available_bounds(anchor_widget()->GetWindowBoundsInScreen()); auto border = std::make_unique<BubbleBorder>(arrow(), GetShadow()); border->SetColor(color()); frame->SetBubbleBorder(std::move(border)); frame_ = frame.get(); return frame; } gfx::Size InfoBubble::CalculatePreferredSize() const { if (preferred_width_ == 0) return BubbleDialogDelegateView::CalculatePreferredSize(); int pref_width = preferred_width_; pref_width -= frame_->GetInsets().width(); pref_width -= 2 * kBubbleBorderVisibleWidth; return gfx::Size(pref_width, GetHeightForWidth(pref_width)); } void InfoBubble::OnWidgetBoundsChanged(Widget* widget, const gfx::Rect& new_bounds) { BubbleDialogDelegateView::OnWidgetBoundsChanged(widget, new_bounds); if (anchor_widget() == widget) frame_->set_available_bounds(widget->GetWindowBoundsInScreen()); } void InfoBubble::UpdatePosition() { Widget* const widget = GetWidget(); if (!widget) return; if (anchor_widget()->IsVisible() && !GetAnchorView()->GetVisibleBounds().IsEmpty()) { SizeToContents(); widget->SetVisibilityChangedAnimationsEnabled(true); widget->ShowInactive(); } else { widget->SetVisibilityChangedAnimationsEnabled(false); widget->Hide(); } } BEGIN_METADATA(InfoBubble, BubbleDialogDelegateView) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/info_bubble.cc
C++
unknown
4,218
// 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_BUBBLE_INFO_BUBBLE_H_ #define UI_VIEWS_BUBBLE_INFO_BUBBLE_H_ #include <memory> #include <string> #include "base/memory/raw_ptr.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" namespace views { class InfoBubbleFrame; class Label; // Class to create and manage an information bubble for errors or tooltips. class VIEWS_EXPORT InfoBubble : public BubbleDialogDelegateView { public: METADATA_HEADER(InfoBubble); InfoBubble(View* anchor, BubbleBorder::Arrow arrow, const std::u16string& message); InfoBubble(const InfoBubble&) = delete; InfoBubble& operator=(const InfoBubble&) = delete; ~InfoBubble() override; // Shows the bubble. void Show(); // Hides and closes the bubble. void Hide(); // BubbleDialogDelegateView: std::unique_ptr<NonClientFrameView> CreateNonClientFrameView( Widget* widget) override; gfx::Size CalculatePreferredSize() const override; void OnWidgetBoundsChanged(Widget* widget, const gfx::Rect& new_bounds) override; void set_preferred_width(int preferred_width) { preferred_width_ = preferred_width; } const Label* label_for_testing() const { return label_; } private: // Updates the position of the bubble. void UpdatePosition(); raw_ptr<InfoBubbleFrame> frame_ = nullptr; raw_ptr<Label> label_ = nullptr; // The width this bubble prefers to be. Default is 0 (no preference). int preferred_width_ = 0; }; } // namespace views #endif // UI_VIEWS_BUBBLE_INFO_BUBBLE_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/info_bubble.h
C++
unknown
1,692
// 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/bubble/info_bubble.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/views/controls/label.h" #include "ui/views/test/test_widget_observer.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::test { class InfoBubbleTest : public ViewsTestBase { public: InfoBubbleTest() = default; InfoBubbleTest(const InfoBubbleTest&) = delete; InfoBubbleTest& operator=(const InfoBubbleTest&) = delete; ~InfoBubbleTest() override = default; // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); Widget::InitParams params = CreateParamsForTestWidget(Widget::InitParams::TYPE_WINDOW); anchor_widget_ = std::make_unique<Widget>(); anchor_widget_->Init(std::move(params)); anchor_widget_->Show(); } void TearDown() override { anchor_widget_.reset(); ViewsTestBase::TearDown(); } Widget* anchor_widget() { return anchor_widget_.get(); } private: std::unique_ptr<Widget> anchor_widget_; }; TEST_F(InfoBubbleTest, CreateInfoBubble) { std::u16string text = u"test message"; InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, text); info_bubble->Show(); TestWidgetObserver bubble_observer(info_bubble->GetWidget()); EXPECT_EQ(info_bubble->GetAnchorView(), anchor_widget()->GetContentsView()); EXPECT_EQ(info_bubble->GetAnchorView()->GetWidget(), anchor_widget()); EXPECT_EQ(text, info_bubble->label_for_testing()->GetText()); EXPECT_TRUE(info_bubble->GetVisible()); EXPECT_FALSE(bubble_observer.widget_closed()); info_bubble->Hide(); RunPendingMessages(); EXPECT_TRUE(bubble_observer.widget_closed()); } // Ensure the InfoBubble is still sized if not supplied with a preferred width. TEST_F(InfoBubbleTest, TestPreferredWidthNull) { InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, std::u16string()); auto child = std::make_unique<View>(); child->SetPreferredSize(gfx::Size(50, 50)); info_bubble->AddChildView(std::move(child)); info_bubble->Show(); EXPECT_LT(0, info_bubble->GetLocalBounds().width()); info_bubble->Hide(); RunPendingMessages(); } TEST_F(InfoBubbleTest, TestPreferredWidth) { constexpr int kPreferredWidthLarge = 800; constexpr int kPreferredWidthSmall = 50; InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, std::u16string()); info_bubble->Show(); info_bubble->set_preferred_width(kPreferredWidthLarge); info_bubble->SizeToPreferredSize(); // Test to make sure the resulting |info_bubble| honors the preferred size. // |info_bubble| may be slightly smaller due to having to account for margins // and bubble border size. EXPECT_GE(kPreferredWidthLarge, info_bubble->GetLocalBounds().width()); EXPECT_LT(kPreferredWidthSmall, info_bubble->GetLocalBounds().width()); info_bubble->set_preferred_width(kPreferredWidthSmall); info_bubble->SizeToPreferredSize(); // |info_bubble| should now be at or smaller than the smaller preferred width. EXPECT_GE(kPreferredWidthSmall, info_bubble->GetLocalBounds().width()); info_bubble->Hide(); RunPendingMessages(); } TEST_F(InfoBubbleTest, TestInfoBubbleVisibilityHiddenAnchor) { anchor_widget()->Hide(); InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, std::u16string()); info_bubble->Show(); EXPECT_FALSE(info_bubble->GetWidget()->IsVisible()); info_bubble->Hide(); RunPendingMessages(); } TEST_F(InfoBubbleTest, TestInfoBubbleAnchorBoundsChanged) { InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, u""); info_bubble->Show(); gfx::Rect original_bounds = info_bubble->GetWidget()->GetWindowBoundsInScreen(); anchor_widget()->SetBounds(original_bounds - gfx::Vector2d(5, 5)); EXPECT_NE(original_bounds, info_bubble->GetWidget()->GetWindowBoundsInScreen()); info_bubble->Hide(); RunPendingMessages(); } // Iterate through the metadata for InfoBubble to ensure it all works. TEST_F(InfoBubbleTest, MetadataTest) { InfoBubble* info_bubble = new InfoBubble(anchor_widget()->GetContentsView(), BubbleBorder::Arrow::TOP_LEFT, u""); info_bubble->Show(); test::TestViewMetadata(info_bubble); info_bubble->Hide(); RunPendingMessages(); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/bubble/info_bubble_unittest.cc
C++
unknown
4,932
// 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/bubble/tooltip_icon.h" #include "base/observer_list.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "components/vector_icons/vector_icons.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/bubble/info_bubble.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/mouse_watcher_view_host.h" #include "ui/views/style/platform_style.h" namespace views { TooltipIcon::TooltipIcon(const std::u16string& tooltip, int tooltip_icon_size) : tooltip_(tooltip), tooltip_icon_size_(tooltip_icon_size), bubble_(nullptr) { SetFocusBehavior(PlatformStyle::kDefaultFocusBehavior); set_suppress_default_focus_handling(); FocusRing::Install(this); SetBorder(CreateEmptyBorder( LayoutProvider::Get()->GetInsetsMetric(INSETS_VECTOR_IMAGE_BUTTON))); InstallCircleHighlightPathGenerator(this); // The tooltip icon, despite visually being an icon with no text, actually // opens a bubble whenever the user mouses over it or focuses it, so it's // essentially a text control that hides itself when not in view without // altering the bubble's layout when shown. As such, have it behave like // static text for screenreader users, since that's the role it serves here // anyway. SetAccessibilityProperties(ax::mojom::Role::kStaticText, tooltip_); } TooltipIcon::~TooltipIcon() { for (auto& observer : observers_) observer.OnTooltipIconDestroying(this); HideBubble(); } void TooltipIcon::OnMouseEntered(const ui::MouseEvent& event) { mouse_inside_ = true; show_timer_.Start(FROM_HERE, base::Milliseconds(150), this, &TooltipIcon::ShowBubble); } void TooltipIcon::OnMouseExited(const ui::MouseEvent& event) { show_timer_.Stop(); } bool TooltipIcon::OnMousePressed(const ui::MouseEvent& event) { // Swallow the click so that the parent doesn't process it. return true; } void TooltipIcon::OnFocus() { ShowBubble(); #if BUILDFLAG(IS_WIN) // Tooltip text does not announce on Windows; crbug.com/1245470 NotifyAccessibilityEvent(ax::mojom::Event::kFocus, true); #endif } void TooltipIcon::OnBlur() { HideBubble(); } void TooltipIcon::OnGestureEvent(ui::GestureEvent* event) { if (event->type() == ui::ET_GESTURE_TAP) { ShowBubble(); event->SetHandled(); } } void TooltipIcon::OnThemeChanged() { ImageView::OnThemeChanged(); SetDrawAsHovered(false); } void TooltipIcon::MouseMovedOutOfHost() { if (IsMouseHovered()) { mouse_watcher_->Start(GetWidget()->GetNativeWindow()); return; } mouse_inside_ = false; HideBubble(); } void TooltipIcon::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void TooltipIcon::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void TooltipIcon::SetDrawAsHovered(bool hovered) { SetImage(ui::ImageModel::FromVectorIcon( vector_icons::kInfoOutlineIcon, GetColorProvider()->GetColor(hovered ? ui::kColorHelpIconActive : ui::kColorHelpIconInactive), tooltip_icon_size_)); } void TooltipIcon::ShowBubble() { if (bubble_) return; SetDrawAsHovered(true); bubble_ = new InfoBubble(this, anchor_point_arrow_, tooltip_); bubble_->set_preferred_width(preferred_width_); // When shown due to a gesture event, close on deactivate (i.e. don't use // "focusless"). bubble_->SetCanActivate(!mouse_inside_); bubble_->Show(); observation_.Observe(bubble_->GetWidget()); if (mouse_inside_) { View* frame = bubble_->GetWidget()->non_client_view()->frame_view(); mouse_watcher_ = std::make_unique<MouseWatcher>( std::make_unique<MouseWatcherViewHost>(frame, gfx::Insets()), this); mouse_watcher_->Start(GetWidget()->GetNativeWindow()); } for (auto& observer : observers_) observer.OnTooltipBubbleShown(this); } void TooltipIcon::HideBubble() { if (bubble_) bubble_->Hide(); } void TooltipIcon::OnWidgetDestroyed(Widget* widget) { DCHECK(observation_.IsObservingSource(widget)); observation_.Reset(); SetDrawAsHovered(false); mouse_watcher_.reset(); bubble_ = nullptr; } BEGIN_METADATA(TooltipIcon, ImageView) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/tooltip_icon.cc
C++
unknown
4,675
// 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_BUBBLE_TOOLTIP_ICON_H_ #define UI_VIEWS_BUBBLE_TOOLTIP_ICON_H_ #include <memory> #include <string> #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "base/scoped_observation.h" #include "base/timer/timer.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/image_view.h" #include "ui/views/mouse_watcher.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace views { class InfoBubble; // A tooltip icon that shows a bubble on hover. Looks like (i). class VIEWS_EXPORT TooltipIcon : public ImageView, public MouseWatcherListener, public WidgetObserver { public: class Observer : public base::CheckedObserver { public: // Called when tooltip bubble of the TooltipIcon is shown. virtual void OnTooltipBubbleShown(TooltipIcon* icon) = 0; // Called when the TooltipIcon is being destroyed. virtual void OnTooltipIconDestroying(TooltipIcon* icon) = 0; }; METADATA_HEADER(TooltipIcon); explicit TooltipIcon(const std::u16string& tooltip, int tooltip_icon_size = 16); TooltipIcon(const TooltipIcon&) = delete; TooltipIcon& operator=(const TooltipIcon&) = delete; ~TooltipIcon() override; // ImageView: void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnFocus() override; void OnBlur() override; void OnGestureEvent(ui::GestureEvent* event) override; void OnThemeChanged() override; // MouseWatcherListener: void MouseMovedOutOfHost() override; // WidgetObserver: void OnWidgetDestroyed(Widget* widget) override; void set_bubble_width(int preferred_width) { preferred_width_ = preferred_width; } void set_anchor_point_arrow(BubbleBorder::Arrow arrow) { anchor_point_arrow_ = arrow; } void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); private: // Changes the color to reflect the hover node_data. void SetDrawAsHovered(bool hovered); // Creates and shows |bubble_|. If |bubble_| already exists, just cancels a // potential close timer. void ShowBubble(); // Hides |bubble_| if necessary. void HideBubble(); // The text to show in a bubble when hovered. std::u16string tooltip_; // The size of the tooltip icon, in dip. // Must be set in the constructor, otherwise the pre-hovered icon will show // the default size. int tooltip_icon_size_; // The point at which to anchor the tooltip. BubbleBorder::Arrow anchor_point_arrow_ = BubbleBorder::TOP_RIGHT; // Whether the mouse is inside this tooltip. bool mouse_inside_ = false; // A bubble shown on hover. Weak; owns itself. NULL while hiding. raw_ptr<InfoBubble> bubble_; // The width the tooltip prefers to be. Default is 0 (no preference). int preferred_width_ = 0; // A timer to delay showing |bubble_|. base::OneShotTimer show_timer_; // A watcher that keeps |bubble_| open if the user's mouse enters it. std::unique_ptr<MouseWatcher> mouse_watcher_; base::ScopedObservation<Widget, WidgetObserver> observation_{this}; base::ObserverList<Observer, /*check_empty=*/true> observers_; }; } // namespace views #endif // UI_VIEWS_BUBBLE_TOOLTIP_ICON_H_
Zhao-PengFei35/chromium_src_4
ui/views/bubble/tooltip_icon.h
C++
unknown
3,551
// 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/bubble/tooltip_icon.h" #include <memory> #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/views/test/views_test_base.h" namespace views { using TooltipIconTest = views::ViewsTestBase; TEST_F(TooltipIconTest, AccessibleRoleAndName) { std::u16string tooltip_text = u"Tooltip text"; std::unique_ptr<views::TooltipIcon> tooltip = std::make_unique<views::TooltipIcon>(tooltip_text, 12); ui::AXNodeData data; tooltip->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kStaticText); EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), tooltip_text); EXPECT_EQ(tooltip->GetAccessibleName(), tooltip_text); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/bubble/tooltip_icon_unittest.cc
C++
unknown
913
// 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/button_drag_utils.h" #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/base/models/image_model.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/canvas_painter.h" #include "ui/compositor/compositor.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/resources/grit/ui_resources.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/drag_utils.h" #include "ui/views/paint_info.h" #include "ui/views/widget/widget.h" #include "url/gurl.h" namespace button_drag_utils { // Maximum width of the link drag image in pixels. static constexpr int kLinkDragImageMaxWidth = 150; class ScopedWidget { public: explicit ScopedWidget(views::Widget* widget) : widget_(widget) {} ScopedWidget(const ScopedWidget&) = delete; ScopedWidget& operator=(const ScopedWidget&) = delete; ~ScopedWidget() { if (widget_) widget_->CloseNow(); } views::Widget* operator->() const { return widget_; } views::Widget* get() const { return widget_; } private: raw_ptr<views::Widget, DanglingUntriaged> widget_; }; void SetURLAndDragImage(const GURL& url, const std::u16string& title, const gfx::ImageSkia& icon, const gfx::Point* press_pt, ui::OSExchangeData* data) { DCHECK(url.is_valid()); DCHECK(data); data->SetURL(url, title); SetDragImage(url, title, icon, press_pt, data); } void SetDragImage(const GURL& url, const std::u16string& title, const gfx::ImageSkia& icon, const gfx::Point* press_pt, ui::OSExchangeData* data) { // Create a widget to render the drag image for us. ScopedWidget drag_widget(new views::Widget()); views::Widget::InitParams params(views::Widget::InitParams::TYPE_DRAG); params.accept_events = false; params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET; params.shadow_type = views::Widget::InitParams::ShadowType::kNone; params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; drag_widget->Init(std::move(params)); // Create a button to render the drag image for us. views::LabelButton* button = drag_widget->SetContentsView(std::make_unique<views::LabelButton>( views::Button::PressedCallback(), title.empty() ? base::UTF8ToUTF16(url.spec()) : title)); button->SetTextSubpixelRenderingEnabled(false); const ui::ColorProvider* color_provider = drag_widget->GetColorProvider(); button->SetTextColor(views::Button::STATE_NORMAL, color_provider->GetColor(ui::kColorTextfieldForeground)); SkColor bg_color = color_provider->GetColor(ui::kColorTextfieldBackground); if (drag_widget->IsTranslucentWindowOpacitySupported()) { button->SetTextShadows(gfx::ShadowValues( 10, gfx::ShadowValue(gfx::Vector2d(0, 0), 2.0f, bg_color))); } else { button->SetBackground(views::CreateSolidBackground(bg_color)); button->SetBorder(button->CreateDefaultBorder()); } button->SetMaxSize(gfx::Size(kLinkDragImageMaxWidth, 0)); if (icon.isNull()) { button->SetImageModel(views::Button::STATE_NORMAL, ui::ImageModel::FromResourceId(IDR_DEFAULT_FAVICON)); } else { button->SetImageModel(views::Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(icon)); } gfx::Size size(button->GetPreferredSize()); // drag_widget's size must be set to show the drag image in RTL. // However, on Windows, calling Widget::SetSize() resets // the LabelButton's bounds via OnNativeWidgetSizeChanged(). // Therefore, call button->SetBoundsRect() after drag_widget->SetSize(). drag_widget->SetSize(size); button->SetBoundsRect(gfx::Rect(size)); gfx::Vector2d press_point; if (press_pt) press_point = press_pt->OffsetFromOrigin(); else press_point = gfx::Vector2d(size.width() / 2, size.height() / 2); SkBitmap bitmap; float raster_scale = ScaleFactorForDragFromWidget(drag_widget.get()); SkColor color = SK_ColorTRANSPARENT; button->Paint(views::PaintInfo::CreateRootPaintInfo( ui::CanvasPainter(&bitmap, size, raster_scale, color, true /* is_pixel_canvas */) .context(), size)); gfx::ImageSkia image = gfx::ImageSkia::CreateFromBitmap(bitmap, raster_scale); data->provider().SetDragImage(image, press_point); } } // namespace button_drag_utils
Zhao-PengFei35/chromium_src_4
ui/views/button_drag_utils.cc
C++
unknown
5,029
// 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_BUTTON_DRAG_UTILS_H_ #define UI_VIEWS_BUTTON_DRAG_UTILS_H_ #include <string> #include "ui/views/views_export.h" class GURL; namespace gfx { class ImageSkia; class Point; } // namespace gfx namespace ui { class OSExchangeData; } namespace button_drag_utils { // Sets url and title on data as well as setting a suitable image for dragging. // The image looks like that of the bookmark buttons. |press_pt| is optional // offset; otherwise, it centers the drag image. VIEWS_EXPORT void SetURLAndDragImage(const GURL& url, const std::u16string& title, const gfx::ImageSkia& icon, const gfx::Point* press_pt, ui::OSExchangeData* data); // As above, but only sets the image. VIEWS_EXPORT void SetDragImage(const GURL& url, const std::u16string& title, const gfx::ImageSkia& icon, const gfx::Point* press_pt, ui::OSExchangeData* data); } // namespace button_drag_utils #endif // UI_VIEWS_BUTTON_DRAG_UTILS_H_
Zhao-PengFei35/chromium_src_4
ui/views/button_drag_utils.h
C++
unknown
1,347
// 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/cascading_property.h" #include "ui/base/theme_provider.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/color_utils.h" DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::CascadingProperty<SkColor>*) namespace views { namespace { class CascadingColorProviderColor final : public CascadingProperty<SkColor> { public: explicit CascadingColorProviderColor(ui::ColorId color_id) : color_id_(color_id) {} // CascadingProperty<SkColor>: SkColor GetValue(const View* view) const override { return view->GetColorProvider()->GetColor(color_id_); } private: const ui::ColorId color_id_; }; } // namespace DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(CascadingProperty<SkColor>, kCascadingBackgroundColor, nullptr) void SetCascadingColorProviderColor( views::View* view, const ui::ClassProperty<CascadingProperty<SkColor>*>* property_key, ui::ColorId color_id) { SetCascadingProperty( view, property_key, std::make_unique<views::CascadingColorProviderColor>(color_id)); } SkColor GetCascadingBackgroundColor(View* view) { const absl::optional<SkColor> color = GetCascadingProperty(view, kCascadingBackgroundColor); return color.value_or( view->GetColorProvider()->GetColor(ui::kColorWindowBackground)); } SkColor GetCascadingAccentColor(View* view) { const SkColor default_color = view->GetColorProvider()->GetColor(ui::kColorFocusableBorderFocused); return color_utils::PickGoogleColor( default_color, GetCascadingBackgroundColor(view), color_utils::kMinimumVisibleContrastRatio); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cascading_property.cc
C++
unknown
1,904
// 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_CASCADING_PROPERTY_H_ #define UI_VIEWS_CASCADING_PROPERTY_H_ #include <memory> #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/class_property.h" #include "ui/color/color_id.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { class View; template <typename T> class CascadingProperty { public: CascadingProperty() = default; CascadingProperty(const CascadingProperty&) = delete; CascadingProperty& operator=(const CascadingProperty&) = delete; virtual ~CascadingProperty() = default; virtual T GetValue(const View* view) const = 0; }; template <typename T> const CascadingProperty<T>* GetCascadingPropertyObject( View* view, const ui::ClassProperty<CascadingProperty<T>*>* property_key) { const CascadingProperty<T>* property = view->GetProperty(property_key); if (property != nullptr) return property; if (!view->parent()) return nullptr; return GetCascadingPropertyObject(view->parent(), property_key); } template <typename T> absl::optional<T> GetCascadingProperty( View* view, const ui::ClassProperty<CascadingProperty<T>*>* property_key) { const CascadingProperty<T>* property = GetCascadingPropertyObject(view, property_key); return property ? absl::optional<T>(property->GetValue(view)) : absl::nullopt; } template <typename T, typename K> void SetCascadingProperty( View* view, const ui::ClassProperty<CascadingProperty<T>*>* property_key, std::unique_ptr<K> property) { // TODO(pbos): See if there could be a way to (D)CHECK that property_key is // actually owned. view->SetProperty(property_key, static_cast<CascadingProperty<T>*>(property.release())); } VIEWS_EXPORT void SetCascadingColorProviderColor( View* view, const ui::ClassProperty<CascadingProperty<SkColor>*>* property_key, ui::ColorId color_id); VIEWS_EXPORT extern const ui::ClassProperty<CascadingProperty<SkColor>*>* const kCascadingBackgroundColor; VIEWS_EXPORT SkColor GetCascadingBackgroundColor(View* view); VIEWS_EXPORT SkColor GetCascadingAccentColor(View* view); } // namespace views DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::CascadingProperty<SkColor>*) #endif // UI_VIEWS_CASCADING_PROPERTY_H_
Zhao-PengFei35/chromium_src_4
ui/views/cascading_property.h
C++
unknown
2,530
include_rules = [ "+components/remote_cocoa", "+ui/accelerated_widget_mac", ]
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/DEPS
Python
unknown
82
// 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 "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #import <Cocoa/Cocoa.h> #import "base/mac/mac_util.h" #include "base/run_loop.h" #import "ui/base/cocoa/nswindow_test_util.h" #include "ui/base/hit_test.h" #include "ui/base/test/ui_controls.h" #import "ui/base/test/windowed_nsnotification_observer.h" #import "ui/events/test/cocoa_test_event_utils.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/native_widget_mac.h" #include "ui/views/window/native_frame_view.h" namespace views::test { class BridgedNativeWidgetUITest : public WidgetTest { public: BridgedNativeWidgetUITest() = default; BridgedNativeWidgetUITest(const BridgedNativeWidgetUITest&) = delete; BridgedNativeWidgetUITest& operator=(const BridgedNativeWidgetUITest&) = delete; // testing::Test: void SetUp() override { SetUpForInteractiveTests(); WidgetTest::SetUp(); Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(100, 100, 300, 200); init_params.delegate = new views::WidgetDelegate; init_params.delegate->SetOwnedByWidget(true); // Provide a resizable Widget by default, as macOS doesn't correctly restore // the window size when coming out of fullscreen if the window is not // user-sizable. init_params.delegate->SetCanResize(true); widget_ = std::make_unique<Widget>(); widget_->Init(std::move(init_params)); } void TearDown() override { // Ensures any compositor is removed before ViewsTestBase tears down the // ContextFactory. widget_.reset(); WidgetTest::TearDown(); } NSWindow* test_window() { return widget_->GetNativeWindow().GetNativeNSWindow(); } protected: std::unique_ptr<Widget> widget_; }; // Tests for correct fullscreen tracking, regardless of whether it is initiated // by the Widget code or elsewhere (e.g. by the user). TEST_F(BridgedNativeWidgetUITest, FullscreenSynchronousState) { EXPECT_FALSE(widget_->IsFullscreen()); // Allow user-initiated fullscreen changes on the Window. [test_window() setCollectionBehavior:[test_window() collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary]; ui::NSWindowFullscreenNotificationWaiter waiter(widget_->GetNativeWindow()); const gfx::Rect restored_bounds = widget_->GetRestoredBounds(); // First show the widget. A user shouldn't be able to initiate fullscreen // unless the window is visible in the first place. widget_->Show(); // Simulate a user-initiated fullscreen. Note trying to to this again before // spinning a runloop will cause Cocoa to emit text to stdio and ignore it. [test_window() toggleFullScreen:nil]; EXPECT_TRUE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); // Note there's now an animation running. While that's happening, toggling the // state should work as expected, but do "nothing". widget_->SetFullscreen(false); EXPECT_FALSE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); widget_->SetFullscreen(false); // Same request - should no-op. EXPECT_FALSE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); widget_->SetFullscreen(true); EXPECT_TRUE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); // Always finish out of fullscreen. Otherwise there are 4 NSWindow objects // that Cocoa creates which don't close themselves and will be seen by the Mac // test harness on teardown. Note that the test harness will be waiting until // all animations complete, since these temporary animation windows will not // be removed from the window list until they do. widget_->SetFullscreen(false); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); // Now we must wait for the notifications. Since, if the widget is torn down, // the NSWindowDelegate is removed, and the pending request to take out of // fullscreen is lost. Since a message loop has not yet spun up in this test // we can reliably say there will be one enter and one exit, despite all the // toggling above. Wait only for the exit notification (the enter // notification will be swallowed, because the exit will have been requested // before the enter completes). waiter.WaitForEnterAndExitCount(0, 1); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); } // Test fullscreen without overlapping calls and without changing collection // behavior on the test window. TEST_F(BridgedNativeWidgetUITest, FullscreenEnterAndExit) { ui::NSWindowFullscreenNotificationWaiter waiter(widget_->GetNativeWindow()); EXPECT_FALSE(widget_->IsFullscreen()); const gfx::Rect restored_bounds = widget_->GetRestoredBounds(); EXPECT_FALSE(restored_bounds.IsEmpty()); // Ensure this works without having to change collection behavior as for the // test above. Also check that making a hidden widget fullscreen shows it. EXPECT_FALSE(widget_->IsVisible()); widget_->SetFullscreen(true); EXPECT_TRUE(widget_->IsVisible()); EXPECT_TRUE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); // Should be zero until the runloop spins. EXPECT_EQ(0, waiter.enter_count()); waiter.WaitForEnterAndExitCount(1, 0); // Verify it hasn't exceeded. EXPECT_EQ(1, waiter.enter_count()); EXPECT_EQ(0, waiter.exit_count()); EXPECT_TRUE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); widget_->SetFullscreen(false); EXPECT_FALSE(widget_->IsFullscreen()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); waiter.WaitForEnterAndExitCount(1, 1); EXPECT_EQ(1, waiter.enter_count()); EXPECT_EQ(1, waiter.exit_count()); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); } // Test that Widget::Restore exits fullscreen. TEST_F(BridgedNativeWidgetUITest, FullscreenRestore) { ui::NSWindowFullscreenNotificationWaiter waiter(widget_->GetNativeWindow()); EXPECT_FALSE(widget_->IsFullscreen()); const gfx::Rect restored_bounds = widget_->GetRestoredBounds(); EXPECT_FALSE(restored_bounds.IsEmpty()); widget_->SetFullscreen(true); EXPECT_TRUE(widget_->IsFullscreen()); waiter.WaitForEnterAndExitCount(1, 0); widget_->Restore(); EXPECT_FALSE(widget_->IsFullscreen()); waiter.WaitForEnterAndExitCount(1, 1); EXPECT_EQ(restored_bounds, widget_->GetRestoredBounds()); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/bridged_native_widget_interactive_uitest.mm
Objective-C++
unknown
6,821
// 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 "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #import <Cocoa/Cocoa.h> #include <objc/runtime.h> #include <memory> #include "base/functional/bind.h" #import "base/mac/foundation_util.h" #import "base/mac/mac_util.h" #import "base/mac/scoped_objc_class_swizzler.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" #import "components/remote_cocoa/app_shim/bridged_content_view.h" #import "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h" #import "components/remote_cocoa/app_shim/views_nswindow_delegate.h" #import "testing/gtest_mac.h" #include "ui/base/cocoa/find_pasteboard.h" #import "ui/base/cocoa/window_size_constants.h" #include "ui/base/ime/input_method.h" #import "ui/base/test/cocoa_helper.h" #include "ui/display/screen.h" #include "ui/events/test/cocoa_test_event_utils.h" #import "ui/gfx/mac/coordinate_conversion.h" #import "ui/views/cocoa/native_widget_mac_ns_window_host.h" #import "ui/views/cocoa/text_input_host.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/controls/textfield/textfield_model.h" #include "ui/views/test/test_views_delegate.h" #include "ui/views/view.h" #include "ui/views/widget/native_widget_mac.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" using base::ASCIIToUTF16; using base::SysNSStringToUTF8; using base::SysNSStringToUTF16; using base::SysUTF8ToNSString; using base::SysUTF16ToNSString; #define EXPECT_EQ_RANGE(a, b) \ EXPECT_EQ(a.location, b.location); \ EXPECT_EQ(a.length, b.length); // Helpers to verify an expectation against both the actual toolkit-views // behaviour and the Cocoa behaviour. #define EXPECT_NSEQ_3(expected_literal, expected_cocoa, actual_views) \ EXPECT_NSEQ(expected_literal, actual_views); \ EXPECT_NSEQ(expected_cocoa, actual_views); #define EXPECT_EQ_RANGE_3(expected_literal, expected_cocoa, actual_views) \ EXPECT_EQ_RANGE(expected_literal, actual_views); \ EXPECT_EQ_RANGE(expected_cocoa, actual_views); #define EXPECT_EQ_3(expected_literal, expected_cocoa, actual_views) \ EXPECT_EQ(expected_literal, actual_views); \ EXPECT_EQ(expected_cocoa, actual_views); namespace { // Implemented NSResponder action messages for use in tests. NSArray* const kMoveActions = @[ @"moveForward:", @"moveRight:", @"moveBackward:", @"moveLeft:", @"moveUp:", @"moveDown:", @"moveWordForward:", @"moveWordBackward:", @"moveToBeginningOfLine:", @"moveToEndOfLine:", @"moveToBeginningOfParagraph:", @"moveToEndOfParagraph:", @"moveToEndOfDocument:", @"moveToBeginningOfDocument:", @"pageDown:", @"pageUp:", @"moveWordRight:", @"moveWordLeft:", @"moveToLeftEndOfLine:", @"moveToRightEndOfLine:" ]; NSArray* const kSelectActions = @[ @"moveBackwardAndModifySelection:", @"moveForwardAndModifySelection:", @"moveWordForwardAndModifySelection:", @"moveWordBackwardAndModifySelection:", @"moveUpAndModifySelection:", @"moveDownAndModifySelection:", @"moveToBeginningOfLineAndModifySelection:", @"moveToEndOfLineAndModifySelection:", @"moveToBeginningOfParagraphAndModifySelection:", @"moveToEndOfParagraphAndModifySelection:", @"moveToEndOfDocumentAndModifySelection:", @"moveToBeginningOfDocumentAndModifySelection:", @"pageDownAndModifySelection:", @"pageUpAndModifySelection:", @"moveParagraphForwardAndModifySelection:", @"moveParagraphBackwardAndModifySelection:", @"moveRightAndModifySelection:", @"moveLeftAndModifySelection:", @"moveWordRightAndModifySelection:", @"moveWordLeftAndModifySelection:", @"moveToLeftEndOfLineAndModifySelection:", @"moveToRightEndOfLineAndModifySelection:" ]; NSArray* const kDeleteActions = @[ @"deleteForward:", @"deleteBackward:", @"deleteWordForward:", @"deleteWordBackward:", @"deleteToBeginningOfLine:", @"deleteToEndOfLine:", @"deleteToBeginningOfParagraph:", @"deleteToEndOfParagraph:" ]; // This omits @"insertText:":. See BridgedNativeWidgetTest.NilTextInputClient. NSArray* const kMiscActions = @[ @"cancelOperation:", @"transpose:", @"yank:" ]; // Empty range shortcut for readibility. NSRange EmptyRange() { return NSMakeRange(NSNotFound, 0); } // Sets |composition_text| as the composition text with caret placed at // |caret_pos| and updates |caret_range|. void SetCompositionText(ui::TextInputClient* client, const std::u16string& composition_text, const int caret_pos, NSRange* caret_range) { ui::CompositionText composition; composition.selection = gfx::Range(caret_pos); composition.text = composition_text; client->SetCompositionText(composition); if (caret_range) *caret_range = NSMakeRange(caret_pos, 0); } // Returns a zero width rectangle corresponding to current caret position. gfx::Rect GetCaretBounds(const ui::TextInputClient* client) { gfx::Rect caret_bounds = client->GetCaretBounds(); caret_bounds.set_width(0); return caret_bounds; } // Returns a zero width rectangle corresponding to caret bounds when it's placed // at |caret_pos| and updates |caret_range|. gfx::Rect GetCaretBoundsForPosition(ui::TextInputClient* client, const std::u16string& composition_text, const int caret_pos, NSRange* caret_range) { SetCompositionText(client, composition_text, caret_pos, caret_range); return GetCaretBounds(client); } // Returns the expected boundary rectangle for characters of |composition_text| // within the |query_range|. gfx::Rect GetExpectedBoundsForRange(ui::TextInputClient* client, const std::u16string& composition_text, NSRange query_range) { gfx::Rect left_caret = GetCaretBoundsForPosition( client, composition_text, query_range.location, nullptr); gfx::Rect right_caret = GetCaretBoundsForPosition( client, composition_text, query_range.location + query_range.length, nullptr); // The expected bounds correspond to the area between the left and right caret // positions. return gfx::Rect(left_caret.x(), left_caret.y(), right_caret.x() - left_caret.x(), left_caret.height()); } // Uses the NSTextInputClient protocol to extract a substring from |view|. NSString* GetViewStringForRange(NSView<NSTextInputClient>* view, NSRange range) { return [[view attributedSubstringForProposedRange:range actualRange:nullptr] string]; } // The behavior of NSTextView for RTL strings is buggy for some move and select // commands, but only when the command is received when there is a selection // active. E.g. moveRight: moves a cursor right in an RTL string, but it moves // to the left-end of a selection. See TestEditingCommands() for specifics. // This is filed as rdar://27863290. bool IsRTLMoveBuggy(SEL sel) { return sel == @selector(moveWordRight:) || sel == @selector(moveWordLeft:) || sel == @selector(moveRight:) || sel == @selector(moveLeft:); } bool IsRTLSelectBuggy(SEL sel) { return sel == @selector(moveWordRightAndModifySelection:) || sel == @selector(moveWordLeftAndModifySelection:) || sel == @selector(moveRightAndModifySelection:) || sel == @selector(moveLeftAndModifySelection:); } // Used by InterpretKeyEventsDonorForNSView to simulate IME behavior. using InterpretKeyEventsCallback = base::RepeatingCallback<void(id)>; InterpretKeyEventsCallback* g_fake_interpret_key_events = nullptr; // Used by UpdateWindowsDonorForNSApp to hook -[NSApp updateWindows]. base::RepeatingClosure* g_update_windows_closure = nullptr; // Used to provide a return value for +[NSTextInputContext currentInputContext]. NSTextInputContext* g_fake_current_input_context = nullptr; } // namespace // Subclass of BridgedContentView with an override of interpretKeyEvents:. Note // the size of the class must match BridgedContentView since the method table // is swapped out at runtime. This is basically a mock, but mocks are banned // under ui/views. Method swizzling causes these tests to flake when // parallelized in the same process. @interface InterpretKeyEventMockedBridgedContentView : BridgedContentView @end @implementation InterpretKeyEventMockedBridgedContentView - (void)interpretKeyEvents:(NSArray<NSEvent*>*)eventArray { ASSERT_TRUE(g_fake_interpret_key_events); g_fake_interpret_key_events->Run(self); } @end @interface UpdateWindowsDonorForNSApp : NSApplication @end @implementation UpdateWindowsDonorForNSApp - (void)updateWindows { ASSERT_TRUE(g_update_windows_closure); g_update_windows_closure->Run(); } @end @interface CurrentInputContextDonorForNSTextInputContext : NSTextInputContext @end @implementation CurrentInputContextDonorForNSTextInputContext + (NSTextInputContext*)currentInputContext { return g_fake_current_input_context; } @end // Let's not mess with the machine's actual find pasteboard! @interface MockFindPasteboard : FindPasteboard @end @implementation MockFindPasteboard { base::scoped_nsobject<NSString> _text; } + (FindPasteboard*)sharedInstance { static MockFindPasteboard* instance = nil; if (!instance) { instance = [[MockFindPasteboard alloc] init]; } return instance; } - (instancetype)init { self = [super init]; if (self) { _text.reset([[NSString alloc] init]); } return self; } - (void)loadTextFromPasteboard:(NSNotification*)notification { // No-op } - (void)setFindText:(NSString*)newText { _text.reset([newText copy]); } - (NSString*)findText { return _text; } @end @interface NativeWidgetMacNSWindowForTesting : NativeWidgetMacNSWindow { BOOL hasShadowForTesting; } @end @implementation NativeWidgetMacNSWindowForTesting // Preserves the value of the hasShadow flag. During testing, -hasShadow will // always return NO because shadows are disabled on the bots. - (void)setHasShadow:(BOOL)flag { hasShadowForTesting = flag; [super setHasShadow:flag]; } // Returns the value of the hasShadow flag during tests. - (BOOL)hasShadowForTesting { return hasShadowForTesting; } @end namespace views::test { // Provides the |parent| argument to construct a NativeWidgetNSWindowBridge. class MockNativeWidgetMac : public NativeWidgetMac { public: explicit MockNativeWidgetMac(internal::NativeWidgetDelegate* delegate) : NativeWidgetMac(delegate) {} MockNativeWidgetMac(const MockNativeWidgetMac&) = delete; MockNativeWidgetMac& operator=(const MockNativeWidgetMac&) = delete; using NativeWidgetMac::GetInProcessNSWindowBridge; using NativeWidgetMac::GetNSWindowHost; // internal::NativeWidgetPrivate: void InitNativeWidget(Widget::InitParams params) override { ownership_ = params.ownership; base::scoped_nsobject<NativeWidgetMacNSWindow> window( [[NativeWidgetMacNSWindowForTesting alloc] initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO]); GetNSWindowHost()->CreateInProcessNSWindowBridge(window); if (auto* parent = NativeWidgetMacNSWindowHost::GetFromNativeView(params.parent)) { GetNSWindowHost()->SetParent(parent); } GetNSWindowHost()->InitWindow(params, ConvertBoundsToScreenIfNeeded(params.bounds)); // Usually the bridge gets initialized here. It is skipped to run extra // checks in tests, and so that a second window isn't created. delegate()->OnNativeWidgetCreated(); // To allow events to dispatch to a view, it needs a way to get focus. SetFocusManager(GetWidget()->GetFocusManager()); } void ReorderNativeViews() override { // Called via Widget::Init to set the content view. No-op in these tests. } }; // Helper test base to construct a NativeWidgetNSWindowBridge with a valid // parent. class BridgedNativeWidgetTestBase : public ui::CocoaTest { public: struct SkipInitialization {}; BridgedNativeWidgetTestBase() : widget_(new Widget), native_widget_mac_(new MockNativeWidgetMac(widget_.get())) {} explicit BridgedNativeWidgetTestBase(SkipInitialization tag) : native_widget_mac_(nullptr) {} BridgedNativeWidgetTestBase(const BridgedNativeWidgetTestBase&) = delete; BridgedNativeWidgetTestBase& operator=(const BridgedNativeWidgetTestBase&) = delete; remote_cocoa::NativeWidgetNSWindowBridge* bridge() { return native_widget_mac_->GetInProcessNSWindowBridge(); } NativeWidgetMacNSWindowHost* GetNSWindowHost() { return native_widget_mac_->GetNSWindowHost(); } // Generate an autoreleased KeyDown NSEvent* in |widget_| for pressing the // corresponding |key_code|. NSEvent* VkeyKeyDown(ui::KeyboardCode key_code) { return cocoa_test_event_utils::SynthesizeKeyEvent( widget_->GetNativeWindow().GetNativeNSWindow(), true /* keyDown */, key_code, 0); } // Generate an autoreleased KeyDown NSEvent* using the given keycode, and // representing the first unicode character of |chars|. NSEvent* UnicodeKeyDown(int key_code, NSString* chars) { return cocoa_test_event_utils::KeyEventWithKeyCode( key_code, [chars characterAtIndex:0], NSEventTypeKeyDown, 0); } // Overridden from testing::Test: void SetUp() override { ui::CocoaTest::SetUp(); Widget::InitParams init_params; init_params.native_widget = native_widget_mac_.get(); init_params.type = type_; init_params.ownership = ownership_; init_params.opacity = opacity_; init_params.bounds = bounds_; init_params.shadow_type = shadow_type_; if (native_widget_mac_) native_widget_mac_->GetWidget()->Init(std::move(init_params)); } void TearDown() override { // ui::CocoaTest::TearDown will wait until all NSWindows are destroyed, so // be sure to destroy the widget (which will destroy its NSWindow) // beforehand. widget_.reset(); ui::CocoaTest::TearDown(); } NSWindow* bridge_window() const { if (auto* bridge = native_widget_mac_->GetInProcessNSWindowBridge()) return bridge->ns_window(); return nil; } bool BridgeWindowHasShadow() { return [base::mac::ObjCCast<NativeWidgetMacNSWindowForTesting>(bridge_window()) hasShadowForTesting]; } protected: std::unique_ptr<Widget> widget_; raw_ptr<MockNativeWidgetMac> native_widget_mac_; // Weak. Owned by |widget_|. // Use a frameless window, otherwise Widget will try to center the window // before the tests covering the Init() flow are ready to do that. Widget::InitParams::Type type_ = Widget::InitParams::TYPE_WINDOW_FRAMELESS; // To control the lifetime without an actual window that must be closed, // tests in this file need to use WIDGET_OWNS_NATIVE_WIDGET. Widget::InitParams::Ownership ownership_ = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; // Opacity defaults to "infer" which is usually updated by ViewsDelegate. Widget::InitParams::WindowOpacity opacity_ = Widget::InitParams::WindowOpacity::kOpaque; gfx::Rect bounds_ = gfx::Rect(100, 100, 100, 100); Widget::InitParams::ShadowType shadow_type_ = Widget::InitParams::ShadowType::kDefault; private: TestViewsDelegate test_views_delegate_; display::ScopedNativeScreen screen_; }; class BridgedNativeWidgetTest : public BridgedNativeWidgetTestBase, public TextfieldController { public: using HandleKeyEventCallback = base::RepeatingCallback<bool(Textfield*, const ui::KeyEvent& key_event)>; BridgedNativeWidgetTest(); BridgedNativeWidgetTest(const BridgedNativeWidgetTest&) = delete; BridgedNativeWidgetTest& operator=(const BridgedNativeWidgetTest&) = delete; ~BridgedNativeWidgetTest() override; // Install a textfield with input type |text_input_type| in the view hierarchy // and make it the text input client. Also initializes |dummy_text_view_|. Textfield* InstallTextField( const std::u16string& text, ui::TextInputType text_input_type = ui::TEXT_INPUT_TYPE_TEXT); Textfield* InstallTextField(const std::string& text); // Returns the actual current text for |ns_view_|, or the selected substring. NSString* GetActualText(); NSString* GetActualSelectedText(); // Returns the expected current text from |dummy_text_view_|, or the selected // substring. NSString* GetExpectedText(); NSString* GetExpectedSelectedText(); // Returns the actual selection range for |ns_view_|. NSRange GetActualSelectionRange(); // Returns the expected selection range from |dummy_text_view_|. NSRange GetExpectedSelectionRange(); // Set the selection range for the installed textfield and |dummy_text_view_|. void SetSelectionRange(NSRange range); // Perform command |sel| on |ns_view_| and |dummy_text_view_|. void PerformCommand(SEL sel); // Make selection from |start| to |end| on installed views::Textfield and // |dummy_text_view_|. If |start| > |end|, extend selection to left from // |start|. void MakeSelection(int start, int end); // Helper method to set the private |keyDownEvent_| field on |ns_view_|. void SetKeyDownEvent(NSEvent* event); // Sets a callback to run on the next HandleKeyEvent(). void SetHandleKeyEventCallback(HandleKeyEventCallback callback); // testing::Test: void SetUp() override; void TearDown() override; // TextfieldController: bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) override; protected: // Test delete to beginning of line or paragraph based on |sel|. |sel| can be // either deleteToBeginningOfLine: or deleteToBeginningOfParagraph:. void TestDeleteBeginning(SEL sel); // Test delete to end of line or paragraph based on |sel|. |sel| can be // either deleteToEndOfLine: or deleteToEndOfParagraph:. void TestDeleteEnd(SEL sel); // Test editing commands in |selectors| against the expectations set by // |dummy_text_view_|. This is done by selecting every substring within a set // of test strings (both RTL and non-RTL by default) and performing every // selector on both the NSTextView and the BridgedContentView hosting a // focused views::TextField to ensure the resulting text and selection ranges // match. |selectors| is an NSArray of NSStrings. |cases| determines whether // RTL strings are to be tested. void TestEditingCommands(NSArray* selectors); std::unique_ptr<views::View> view_; // Weak. Owned by bridge(). BridgedContentView* ns_view_; // An NSTextView which helps set the expectations for our tests. base::scoped_nsobject<NSTextView> dummy_text_view_; HandleKeyEventCallback handle_key_event_callback_; base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::UI}; }; // Class that counts occurrences of a VKEY_RETURN accelerator, marking them // processed. class EnterAcceleratorView : public View { public: EnterAcceleratorView() { AddAccelerator({ui::VKEY_RETURN, 0}); } int count() const { return count_; } // View: bool AcceleratorPressed(const ui::Accelerator& accelerator) override { ++count_; return true; } private: int count_ = 0; }; BridgedNativeWidgetTest::BridgedNativeWidgetTest() = default; BridgedNativeWidgetTest::~BridgedNativeWidgetTest() = default; Textfield* BridgedNativeWidgetTest::InstallTextField( const std::u16string& text, ui::TextInputType text_input_type) { Textfield* textfield = new Textfield(); textfield->SetText(text); textfield->SetTextInputType(text_input_type); textfield->set_controller(this); view_->RemoveAllChildViews(); view_->AddChildView(textfield); textfield->SetBoundsRect(bounds_); // Request focus so the InputMethod can dispatch events to the RootView, and // have them delivered to the textfield. Note that focusing a textfield // schedules a task to flash the cursor, so this requires |message_loop_|. textfield->RequestFocus(); GetNSWindowHost()->text_input_host()->SetTextInputClient(textfield); // Initialize the dummy text view. Initializing this with NSZeroRect causes // weird NSTextView behavior on OSX 10.9. dummy_text_view_.reset( [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]); [dummy_text_view_ setString:SysUTF16ToNSString(text)]; return textfield; } Textfield* BridgedNativeWidgetTest::InstallTextField(const std::string& text) { return InstallTextField(base::ASCIIToUTF16(text)); } NSString* BridgedNativeWidgetTest::GetActualText() { return GetViewStringForRange(ns_view_, EmptyRange()); } NSString* BridgedNativeWidgetTest::GetActualSelectedText() { return GetViewStringForRange(ns_view_, [ns_view_ selectedRange]); } NSString* BridgedNativeWidgetTest::GetExpectedText() { return GetViewStringForRange(dummy_text_view_, EmptyRange()); } NSString* BridgedNativeWidgetTest::GetExpectedSelectedText() { return GetViewStringForRange(dummy_text_view_, [dummy_text_view_ selectedRange]); } NSRange BridgedNativeWidgetTest::GetActualSelectionRange() { return [ns_view_ selectedRange]; } NSRange BridgedNativeWidgetTest::GetExpectedSelectionRange() { return [dummy_text_view_ selectedRange]; } void BridgedNativeWidgetTest::SetSelectionRange(NSRange range) { ui::TextInputClient* client = [ns_view_ textInputClient]; client->SetEditableSelectionRange(gfx::Range(range)); [dummy_text_view_ setSelectedRange:range]; } void BridgedNativeWidgetTest::PerformCommand(SEL sel) { [ns_view_ doCommandBySelector:sel]; [dummy_text_view_ doCommandBySelector:sel]; } void BridgedNativeWidgetTest::MakeSelection(int start, int end) { ui::TextInputClient* client = [ns_view_ textInputClient]; const gfx::Range range(start, end); // Although a gfx::Range is directed, the underlying model will not choose an // affinity until the cursor is moved. client->SetEditableSelectionRange(range); // Set the range without an affinity. The first @selector sent to the text // field determines the affinity. Note that Range::ToNSRange() may discard // the direction since NSRange has no direction. [dummy_text_view_ setSelectedRange:range.ToNSRange()]; } void BridgedNativeWidgetTest::SetKeyDownEvent(NSEvent* event) { ns_view_.keyDownEventForTesting = event; } void BridgedNativeWidgetTest::SetHandleKeyEventCallback( HandleKeyEventCallback callback) { handle_key_event_callback_ = std::move(callback); } void BridgedNativeWidgetTest::SetUp() { BridgedNativeWidgetTestBase::SetUp(); view_ = std::make_unique<views::internal::RootView>(widget_.get()); base::scoped_nsobject<NSWindow> window([bridge_window() retain]); // The delegate should exist before setting the root view. EXPECT_TRUE([window delegate]); GetNSWindowHost()->SetRootView(view_.get()); bridge()->CreateContentView(GetNSWindowHost()->GetRootViewNSViewId(), view_->bounds()); ns_view_ = bridge()->ns_view(); // Pretend it has been shown via NativeWidgetMac::Show(). [window orderFront:nil]; [window makeFirstResponder:bridge()->ns_view()]; } void BridgedNativeWidgetTest::TearDown() { // Clear kill buffer so that no state persists between tests. TextfieldModel::ClearKillBuffer(); if (GetNSWindowHost()) { GetNSWindowHost()->SetRootView(nullptr); bridge()->DestroyContentView(); } view_.reset(); BridgedNativeWidgetTestBase::TearDown(); } bool BridgedNativeWidgetTest::HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) { if (handle_key_event_callback_) return handle_key_event_callback_.Run(sender, key_event); return false; } void BridgedNativeWidgetTest::TestDeleteBeginning(SEL sel) { InstallTextField("foo bar baz"); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret to the beginning of the line. SetSelectionRange(NSMakeRange(0, 0)); // Verify no deletion takes place. PerformCommand(sel); EXPECT_NSEQ_3(@"foo bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret as- "foo| bar baz". SetSelectionRange(NSMakeRange(3, 0)); PerformCommand(sel); // Verify state is "| bar baz". EXPECT_NSEQ_3(@" bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Make a selection as- " bar |baz|". SetSelectionRange(NSMakeRange(5, 3)); PerformCommand(sel); // Verify only the selection is deleted so that the state is " bar |". EXPECT_NSEQ_3(@" bar ", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(5, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify yanking inserts the deleted text. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(@" bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(8, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } void BridgedNativeWidgetTest::TestDeleteEnd(SEL sel) { InstallTextField("foo bar baz"); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Caret is at the end of the line. Verify no deletion takes place. PerformCommand(sel); EXPECT_NSEQ_3(@"foo bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret as- "foo bar| baz". SetSelectionRange(NSMakeRange(7, 0)); PerformCommand(sel); // Verify state is "foo bar|". EXPECT_NSEQ_3(@"foo bar", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(7, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Make a selection as- "|foo |bar". SetSelectionRange(NSMakeRange(0, 4)); PerformCommand(sel); // Verify only the selection is deleted so that the state is "|bar". EXPECT_NSEQ_3(@"bar", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify yanking inserts the deleted text. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(@"foo bar", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(4, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } void BridgedNativeWidgetTest::TestEditingCommands(NSArray* selectors) { struct { std::u16string test_string; bool is_rtl; } test_cases[] = { {u"ab c", false}, {u"\x0634\x0632 \x064A", true}, }; for (const auto& test_case : test_cases) { for (NSString* selector_string in selectors) { SEL sel = NSSelectorFromString(selector_string); const int len = test_case.test_string.length(); for (int i = 0; i <= len; i++) { for (int j = 0; j <= len; j++) { SCOPED_TRACE(base::StringPrintf( "Testing range [%d-%d] for case %s and selector %s\n", i, j, base::UTF16ToUTF8(test_case.test_string).c_str(), base::SysNSStringToUTF8(selector_string).c_str())); InstallTextField(test_case.test_string); MakeSelection(i, j); // Sanity checks for MakeSelection(). EXPECT_NSEQ(GetExpectedSelectedText(), GetActualSelectedText()); EXPECT_EQ_RANGE_3(NSMakeRange(std::min(i, j), std::abs(i - j)), GetExpectedSelectionRange(), GetActualSelectionRange()); // Bail out early for selection-modifying commands that are buggy in // Cocoa, since the selected text will not match. if (test_case.is_rtl && i != j && IsRTLSelectBuggy(sel)) continue; PerformCommand(sel); EXPECT_NSEQ(GetExpectedSelectedText(), GetActualSelectedText()); EXPECT_NSEQ(GetExpectedText(), GetActualText()); // Spot-check some Cocoa RTL bugs. These only manifest when there is a // selection (i != j), not for regular cursor moves. if (test_case.is_rtl && i != j && IsRTLMoveBuggy(sel)) { if (sel == @selector(moveRight:)) { // Surely moving right with an rtl string moves to the start of a // range (i.e. min). But Cocoa moves to the end. EXPECT_EQ_RANGE(NSMakeRange(std::max(i, j), 0), GetExpectedSelectionRange()); EXPECT_EQ_RANGE(NSMakeRange(std::min(i, j), 0), GetActualSelectionRange()); } else if (sel == @selector(moveLeft:)) { EXPECT_EQ_RANGE(NSMakeRange(std::min(i, j), 0), GetExpectedSelectionRange()); EXPECT_EQ_RANGE(NSMakeRange(std::max(i, j), 0), GetActualSelectionRange()); } continue; } EXPECT_EQ_RANGE(GetExpectedSelectionRange(), GetActualSelectionRange()); } } } } } // The TEST_VIEW macro expects the view it's testing to have a superview. In // these tests, the NSView bridge is a contentView, at the root. These mimic // what TEST_VIEW usually does. TEST_F(BridgedNativeWidgetTest, BridgedNativeWidgetTest_TestViewAddRemove) { base::scoped_nsobject<BridgedContentView> view([bridge()->ns_view() retain]); base::scoped_nsobject<NSWindow> window([bridge_window() retain]); EXPECT_NSEQ([window contentView], view); EXPECT_NSEQ(window, [view window]); // The superview of a contentView is an NSNextStepFrame. EXPECT_TRUE([view superview]); EXPECT_TRUE([view bridge]); // Ensure the tracking area to propagate mouseMoved: events to the RootView is // installed. EXPECT_EQ(1u, [[view trackingAreas] count]); // Closing the window should tear down the C++ bridge, remove references to // any C++ objects in the ObjectiveC object, and remove it from the hierarchy. [window close]; EXPECT_FALSE([view bridge]); EXPECT_FALSE([view superview]); EXPECT_FALSE([view window]); EXPECT_EQ(0u, [[view trackingAreas] count]); EXPECT_FALSE([window contentView]); EXPECT_FALSE([window delegate]); } TEST_F(BridgedNativeWidgetTest, BridgedNativeWidgetTest_TestViewDisplay) { [bridge()->ns_view() display]; } // Test that resizing the window resizes the root view appropriately. TEST_F(BridgedNativeWidgetTest, ViewSizeTracksWindow) { const int kTestNewWidth = 400; const int kTestNewHeight = 300; // |bridge_window()| is borderless, so these should align. NSSize window_size = [bridge_window() frame].size; EXPECT_EQ(view_->width(), static_cast<int>(window_size.width)); EXPECT_EQ(view_->height(), static_cast<int>(window_size.height)); // Make sure a resize actually occurs. EXPECT_NE(kTestNewWidth, view_->width()); EXPECT_NE(kTestNewHeight, view_->height()); [bridge_window() setFrame:NSMakeRect(0, 0, kTestNewWidth, kTestNewHeight) display:NO]; EXPECT_EQ(kTestNewWidth, view_->width()); EXPECT_EQ(kTestNewHeight, view_->height()); } TEST_F(BridgedNativeWidgetTest, GetInputMethodShouldNotReturnNull) { EXPECT_TRUE(native_widget_mac_->GetInputMethod()); } // A simpler test harness for testing initialization flows. class BridgedNativeWidgetInitTest : public BridgedNativeWidgetTestBase { public: BridgedNativeWidgetInitTest() : BridgedNativeWidgetTestBase(SkipInitialization()) {} BridgedNativeWidgetInitTest(const BridgedNativeWidgetInitTest&) = delete; BridgedNativeWidgetInitTest& operator=(const BridgedNativeWidgetInitTest&) = delete; // Prepares a new |window_| and |widget_| for a call to PerformInit(). void CreateNewWidgetToInit() { widget_ = std::make_unique<Widget>(); native_widget_mac_ = new MockNativeWidgetMac(widget_.get()); } void PerformInit() { Widget::InitParams init_params; init_params.native_widget = native_widget_mac_.get(); init_params.type = type_; init_params.ownership = ownership_; init_params.opacity = opacity_; init_params.bounds = bounds_; init_params.shadow_type = shadow_type_; widget_->Init(std::move(init_params)); } }; // Test that NativeWidgetNSWindowBridge remains sane if Init() is never called. TEST_F(BridgedNativeWidgetInitTest, InitNotCalled) { // Don't use a Widget* as the delegate. ~Widget() checks for Widget:: // |native_widget_destroyed_| being set to true. That can only happen with a // non-null WidgetDelegate, which is only set in Widget::Init(). Then, since // neither Widget nor NativeWidget take ownership, use a unique_ptr. std::unique_ptr<MockNativeWidgetMac> native_widget( new MockNativeWidgetMac(nullptr)); native_widget_mac_ = native_widget.get(); EXPECT_FALSE(bridge()); EXPECT_FALSE(GetNSWindowHost()->GetInProcessNSWindow()); } // Tests the shadow type given in InitParams. TEST_F(BridgedNativeWidgetInitTest, ShadowType) { // Verify Widget::InitParam defaults and arguments added from SetUp(). EXPECT_EQ(Widget::InitParams::TYPE_WINDOW_FRAMELESS, type_); EXPECT_EQ(Widget::InitParams::WindowOpacity::kOpaque, opacity_); EXPECT_EQ(Widget::InitParams::ShadowType::kDefault, shadow_type_); CreateNewWidgetToInit(); EXPECT_FALSE( BridgeWindowHasShadow()); // Default for NSWindowStyleMaskBorderless. PerformInit(); // Borderless is 0, so isn't really a mask. Check that nothing is set. EXPECT_EQ(NSWindowStyleMaskBorderless, [bridge_window() styleMask]); EXPECT_TRUE(BridgeWindowHasShadow()); // ShadowType::kDefault means a shadow. CreateNewWidgetToInit(); shadow_type_ = Widget::InitParams::ShadowType::kNone; PerformInit(); EXPECT_FALSE(BridgeWindowHasShadow()); // Preserves lack of shadow. // Default for Widget::InitParams::TYPE_WINDOW. CreateNewWidgetToInit(); PerformInit(); EXPECT_FALSE(BridgeWindowHasShadow()); // ShadowType::kNone removes shadow. shadow_type_ = Widget::InitParams::ShadowType::kDefault; CreateNewWidgetToInit(); PerformInit(); EXPECT_TRUE(BridgeWindowHasShadow()); // Preserves shadow. widget_.reset(); } // Ensure a nil NSTextInputContext is returned when the ui::TextInputClient is // not editable, a password field, or unset. TEST_F(BridgedNativeWidgetTest, InputContext) { const std::u16string test_string = u"test_str"; InstallTextField(test_string, ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_FALSE([ns_view_ inputContext]); InstallTextField(test_string, ui::TEXT_INPUT_TYPE_TEXT); EXPECT_TRUE([ns_view_ inputContext]); GetNSWindowHost()->text_input_host()->SetTextInputClient(nullptr); EXPECT_FALSE([ns_view_ inputContext]); InstallTextField(test_string, ui::TEXT_INPUT_TYPE_NONE); EXPECT_FALSE([ns_view_ inputContext]); } // Test getting complete string using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_GetCompleteString) { const std::string test_string = "foo bar baz"; InstallTextField(test_string); NSRange range = NSMakeRange(0, test_string.size()); NSRange actual_range; NSAttributedString* actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; NSRange expected_range; NSAttributedString* expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(@"foo bar baz", [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(range, expected_range, actual_range); } // Test getting middle substring using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_GetMiddleSubstring) { const std::string test_string = "foo bar baz"; InstallTextField(test_string); NSRange range = NSMakeRange(4, 3); NSRange actual_range; NSAttributedString* actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; NSRange expected_range; NSAttributedString* expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(@"bar", [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(range, expected_range, actual_range); } // Test getting ending substring using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_GetEndingSubstring) { const std::string test_string = "foo bar baz"; InstallTextField(test_string); NSRange range = NSMakeRange(8, 100); NSRange actual_range; NSAttributedString* actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; NSRange expected_range; NSAttributedString* expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(@"baz", [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(NSMakeRange(8, 3), expected_range, actual_range); } // Test getting empty substring using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_GetEmptySubstring) { const std::string test_string = "foo bar baz"; InstallTextField(test_string); // Try with EmptyRange(). This behaves specially and should return the // complete string and the corresponding text range. NSRange range = EmptyRange(); NSRange actual_range = EmptyRange(); NSRange expected_range = EmptyRange(); NSAttributedString* actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; NSAttributedString* expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(@"foo bar baz", [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(NSMakeRange(0, test_string.length()), expected_range, actual_range); // Try with a valid empty range. range = NSMakeRange(2, 0); actual_range = EmptyRange(); expected_range = EmptyRange(); actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(nil, [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(range, expected_range, actual_range); // Try with an out of bounds empty range. range = NSMakeRange(20, 0); actual_range = EmptyRange(); expected_range = EmptyRange(); actual_text = [ns_view_ attributedSubstringForProposedRange:range actualRange:&actual_range]; expected_text = [dummy_text_view_ attributedSubstringForProposedRange:range actualRange:&expected_range]; EXPECT_NSEQ_3(nil, [expected_text string], [actual_text string]); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), expected_range, actual_range); } // Test inserting text using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_InsertText) { const std::string test_string = "foo"; InstallTextField(test_string); [ns_view_ insertText:SysUTF8ToNSString(test_string) replacementRange:EmptyRange()]; [dummy_text_view_ insertText:SysUTF8ToNSString(test_string) replacementRange:EmptyRange()]; EXPECT_NSEQ_3(@"foofoo", GetExpectedText(), GetActualText()); } // Test replacing text using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_ReplaceText) { const std::string test_string = "foo bar"; InstallTextField(test_string); [ns_view_ insertText:@"baz" replacementRange:NSMakeRange(4, 3)]; [dummy_text_view_ insertText:@"baz" replacementRange:NSMakeRange(4, 3)]; EXPECT_NSEQ_3(@"foo baz", GetExpectedText(), GetActualText()); } // Test IME composition using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_Compose) { const std::string test_string = "foo "; InstallTextField(test_string); EXPECT_EQ_3(NO, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); // As per NSTextInputClient documentation, markedRange should return // {NSNotFound, 0} iff hasMarked returns false. However, NSTextView returns // {text_length, text_length} for this case. We maintain consistency with the // documentation, hence the EXPECT_FALSE check. EXPECT_FALSE( NSEqualRanges([dummy_text_view_ markedRange], [ns_view_ markedRange])); EXPECT_EQ_RANGE(EmptyRange(), [ns_view_ markedRange]); // Start composition. NSString* compositionText = @"bar"; NSUInteger compositionLength = [compositionText length]; [ns_view_ setMarkedText:compositionText selectedRange:NSMakeRange(0, 2) replacementRange:EmptyRange()]; [dummy_text_view_ setMarkedText:compositionText selectedRange:NSMakeRange(0, 2) replacementRange:EmptyRange()]; EXPECT_EQ_3(YES, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); EXPECT_EQ_RANGE_3(NSMakeRange(test_string.size(), compositionLength), [dummy_text_view_ markedRange], [ns_view_ markedRange]); EXPECT_EQ_RANGE_3(NSMakeRange(test_string.size(), 2), GetExpectedSelectionRange(), GetActualSelectionRange()); // Confirm composition. [ns_view_ unmarkText]; [dummy_text_view_ unmarkText]; EXPECT_EQ_3(NO, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); EXPECT_FALSE( NSEqualRanges([dummy_text_view_ markedRange], [ns_view_ markedRange])); EXPECT_EQ_RANGE(EmptyRange(), [ns_view_ markedRange]); EXPECT_NSEQ_3(@"foo bar", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange([GetActualText() length], 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test IME composition for accented characters. TEST_F(BridgedNativeWidgetTest, TextInput_AccentedCharacter) { InstallTextField("abc"); // Simulate action messages generated when the key 'a' is pressed repeatedly // and leads to the showing of an IME candidate window. To simulate an event, // set the private keyDownEvent field on the BridgedContentView. // First an insertText: message with key 'a' is generated. SetKeyDownEvent(cocoa_test_event_utils::SynthesizeKeyEvent( widget_->GetNativeWindow().GetNativeNSWindow(), true, ui::VKEY_A, 0)); [ns_view_ insertText:@"a" replacementRange:EmptyRange()]; [dummy_text_view_ insertText:@"a" replacementRange:EmptyRange()]; SetKeyDownEvent(nil); EXPECT_EQ_3(NO, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); EXPECT_NSEQ_3(@"abca", GetExpectedText(), GetActualText()); // Next the IME popup appears. On selecting the accented character using arrow // keys, setMarkedText action message is generated which replaces the earlier // inserted 'a'. SetKeyDownEvent(cocoa_test_event_utils::SynthesizeKeyEvent( widget_->GetNativeWindow().GetNativeNSWindow(), true, ui::VKEY_RIGHT, 0)); [ns_view_ setMarkedText:@"à" selectedRange:NSMakeRange(0, 1) replacementRange:NSMakeRange(3, 1)]; [dummy_text_view_ setMarkedText:@"à" selectedRange:NSMakeRange(0, 1) replacementRange:NSMakeRange(3, 1)]; SetKeyDownEvent(nil); EXPECT_EQ_3(YES, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); EXPECT_EQ_RANGE_3(NSMakeRange(3, 1), [dummy_text_view_ markedRange], [ns_view_ markedRange]); EXPECT_EQ_RANGE_3(NSMakeRange(3, 1), GetExpectedSelectionRange(), GetActualSelectionRange()); EXPECT_NSEQ_3(@"abcà", GetExpectedText(), GetActualText()); // On pressing enter, the marked text is confirmed. SetKeyDownEvent(cocoa_test_event_utils::SynthesizeKeyEvent( widget_->GetNativeWindow().GetNativeNSWindow(), true, ui::VKEY_RETURN, 0)); [ns_view_ insertText:@"à" replacementRange:EmptyRange()]; [dummy_text_view_ insertText:@"à" replacementRange:EmptyRange()]; SetKeyDownEvent(nil); EXPECT_EQ_3(NO, [dummy_text_view_ hasMarkedText], [ns_view_ hasMarkedText]); EXPECT_EQ_RANGE_3(NSMakeRange(4, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); EXPECT_NSEQ_3(@"abcà", GetExpectedText(), GetActualText()); } // Test moving the caret left and right using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_MoveLeftRight) { InstallTextField("foo"); EXPECT_EQ_RANGE_3(NSMakeRange(3, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move right not allowed, out of range. PerformCommand(@selector(moveRight:)); EXPECT_EQ_RANGE_3(NSMakeRange(3, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move left. PerformCommand(@selector(moveLeft:)); EXPECT_EQ_RANGE_3(NSMakeRange(2, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move right. PerformCommand(@selector(moveRight:)); EXPECT_EQ_RANGE_3(NSMakeRange(3, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test backward delete using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteBackward) { InstallTextField("a"); EXPECT_EQ_RANGE_3(NSMakeRange(1, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Delete one character. PerformCommand(@selector(deleteBackward:)); EXPECT_NSEQ_3(nil, GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify that deletion did not modify the kill buffer. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(nil, GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Try to delete again on an empty string. PerformCommand(@selector(deleteBackward:)); EXPECT_NSEQ_3(nil, GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test forward delete using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteForward) { InstallTextField("a"); EXPECT_EQ_RANGE_3(NSMakeRange(1, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // At the end of the string, can't delete forward. PerformCommand(@selector(deleteForward:)); EXPECT_NSEQ_3(@"a", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(1, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Should succeed after moving left first. PerformCommand(@selector(moveLeft:)); PerformCommand(@selector(deleteForward:)); EXPECT_NSEQ_3(nil, GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify that deletion did not modify the kill buffer. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(nil, GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test forward word deletion using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteWordForward) { InstallTextField("foo bar baz"); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Caret is at the end of the line. Verify no deletion takes place. PerformCommand(@selector(deleteWordForward:)); EXPECT_NSEQ_3(@"foo bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret as- "foo b|ar baz". SetSelectionRange(NSMakeRange(5, 0)); PerformCommand(@selector(deleteWordForward:)); // Verify state is "foo b| baz" EXPECT_NSEQ_3(@"foo b baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(5, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Make a selection as- "|fo|o b baz". SetSelectionRange(NSMakeRange(0, 2)); PerformCommand(@selector(deleteWordForward:)); // Verify only the selection is deleted and state is "|o b baz". EXPECT_NSEQ_3(@"o b baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify that deletion did not modify the kill buffer. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(@"o b baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test backward word deletion using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteWordBackward) { InstallTextField("foo bar baz"); EXPECT_EQ_RANGE_3(NSMakeRange(11, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret to the beginning of the line. SetSelectionRange(NSMakeRange(0, 0)); // Verify no deletion takes place. PerformCommand(@selector(deleteWordBackward:)); EXPECT_NSEQ_3(@"foo bar baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(0, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Move the caret as- "foo ba|r baz". SetSelectionRange(NSMakeRange(6, 0)); PerformCommand(@selector(deleteWordBackward:)); // Verify state is "foo |r baz". EXPECT_NSEQ_3(@"foo r baz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(4, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Make a selection as- "f|oo r b|az". SetSelectionRange(NSMakeRange(1, 6)); PerformCommand(@selector(deleteWordBackward:)); // Verify only the selection is deleted and state is "f|az" EXPECT_NSEQ_3(@"faz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(1, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); // Verify that deletion did not modify the kill buffer. PerformCommand(@selector(yank:)); EXPECT_NSEQ_3(@"faz", GetExpectedText(), GetActualText()); EXPECT_EQ_RANGE_3(NSMakeRange(1, 0), GetExpectedSelectionRange(), GetActualSelectionRange()); } // Test deleting to beginning/end of line/paragraph using text input protocol. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteToBeginningOfLine) { TestDeleteBeginning(@selector(deleteToBeginningOfLine:)); } TEST_F(BridgedNativeWidgetTest, TextInput_DeleteToEndOfLine) { TestDeleteEnd(@selector(deleteToEndOfLine:)); } TEST_F(BridgedNativeWidgetTest, TextInput_DeleteToBeginningOfParagraph) { TestDeleteBeginning(@selector(deleteToBeginningOfParagraph:)); } TEST_F(BridgedNativeWidgetTest, TextInput_DeleteToEndOfParagraph) { TestDeleteEnd(@selector(deleteToEndOfParagraph:)); } // Test move commands against expectations set by |dummy_text_view_|. TEST_F(BridgedNativeWidgetTest, TextInput_MoveEditingCommands) { TestEditingCommands(kMoveActions); } // Test move and select commands against expectations set by |dummy_text_view_|. TEST_F(BridgedNativeWidgetTest, TextInput_MoveAndSelectEditingCommands) { TestEditingCommands(kSelectActions); } // Test delete commands against expectations set by |dummy_text_view_|. TEST_F(BridgedNativeWidgetTest, TextInput_DeleteCommands) { TestEditingCommands(kDeleteActions); } // Test that we don't crash during an action message even if the TextInputClient // is nil. Regression test for crbug.com/615745. TEST_F(BridgedNativeWidgetTest, NilTextInputClient) { GetNSWindowHost()->text_input_host()->SetTextInputClient(nullptr); NSMutableArray* selectors = [NSMutableArray array]; [selectors addObjectsFromArray:kMoveActions]; [selectors addObjectsFromArray:kSelectActions]; [selectors addObjectsFromArray:kDeleteActions]; // -insertText: is omitted from this list to avoid a DCHECK in // doCommandBySelector:. AppKit never passes -insertText: to // doCommandBySelector: (it calls -insertText: directly instead). [selectors addObjectsFromArray:kMiscActions]; for (NSString* selector in selectors) [ns_view_ doCommandBySelector:NSSelectorFromString(selector)]; [ns_view_ insertText:@""]; } // Test transpose command against expectations set by |dummy_text_view_|. TEST_F(BridgedNativeWidgetTest, TextInput_Transpose) { TestEditingCommands(@[ @"transpose:" ]); } // Test firstRectForCharacterRange:actualRange for cases where query range is // empty or outside composition range. TEST_F(BridgedNativeWidgetTest, TextInput_FirstRectForCharacterRange_Caret) { InstallTextField(""); ui::TextInputClient* client = [ns_view_ textInputClient]; // No composition. Ensure bounds and range corresponding to the current caret // position are returned. // Initially selection range will be [0, 0]. NSRange caret_range = NSMakeRange(0, 0); NSRange query_range = NSMakeRange(1, 1); NSRange actual_range; NSRect rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_EQ(GetCaretBounds(client), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(caret_range, actual_range); // Set composition with caret before second character ('e'). const std::u16string test_string = u"test_str"; const size_t kTextLength = 8; SetCompositionText(client, test_string, 1, &caret_range); // Test bounds returned for empty ranges within composition range. As per // Apple's documentation for firstRectForCharacterRange:actualRange:, for an // empty query range, the returned rectangle should coincide with the // insertion point and have zero width. However in our implementation, if the // empty query range lies within the composition range, we return a zero width // rectangle corresponding to the query range location. // Test bounds returned for empty range before second character ('e') are same // as caret bounds when placed before second character. query_range = NSMakeRange(1, 0); rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_EQ(GetCaretBoundsForPosition(client, test_string, 1, &caret_range), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(query_range, actual_range); // Test bounds returned for empty range after the composition text are same as // caret bounds when placed after the composition text. query_range = NSMakeRange(kTextLength, 0); rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_NE(GetCaretBoundsForPosition(client, test_string, 1, &caret_range), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ( GetCaretBoundsForPosition(client, test_string, kTextLength, &caret_range), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(query_range, actual_range); // Query outside composition range. Ensure bounds and range corresponding to // the current caret position are returned. query_range = NSMakeRange(kTextLength + 1, 0); rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_EQ(GetCaretBounds(client), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(caret_range, actual_range); // Make sure not crashing by passing null pointer instead of actualRange. rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:nullptr]; } // Test firstRectForCharacterRange:actualRange for non-empty query ranges within // the composition range. TEST_F(BridgedNativeWidgetTest, TextInput_FirstRectForCharacterRange) { InstallTextField(""); ui::TextInputClient* client = [ns_view_ textInputClient]; const std::u16string test_string = u"test_str"; const size_t kTextLength = 8; SetCompositionText(client, test_string, 1, nullptr); // Query bounds for the whole composition string. NSRange query_range = NSMakeRange(0, kTextLength); NSRange actual_range; NSRect rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_EQ(GetExpectedBoundsForRange(client, test_string, query_range), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(query_range, actual_range); // Query bounds for the substring "est_". query_range = NSMakeRange(1, 4); rect = [ns_view_ firstRectForCharacterRange:query_range actualRange:&actual_range]; EXPECT_EQ(GetExpectedBoundsForRange(client, test_string, query_range), gfx::ScreenRectFromNSRect(rect)); EXPECT_EQ_RANGE(query_range, actual_range); } // Test simulated codepaths for IMEs that do not always "mark" text. E.g. // phonetic languages such as Korean and Vietnamese. TEST_F(BridgedNativeWidgetTest, TextInput_SimulatePhoneticIme) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); // Sequence of calls (and corresponding keyDown events) obtained via tracing // with 2-Set Korean IME and pressing q, o, then Enter on the keyboard. NSEvent* q_in_ime = UnicodeKeyDown(12, @"ㅂ"); InterpretKeyEventsCallback handle_q_in_ime = base::BindRepeating([](id view) { [view insertText:@"ㅂ" replacementRange:NSMakeRange(NSNotFound, 0)]; }); NSEvent* o_in_ime = UnicodeKeyDown(31, @"ㅐ"); InterpretKeyEventsCallback handle_o_in_ime = base::BindRepeating([](id view) { [view insertText:@"배" replacementRange:NSMakeRange(0, 1)]; }); InterpretKeyEventsCallback handle_return_in_ime = base::BindRepeating([](id view) { // When confirming the composition, AppKit repeats itself. [view insertText:@"배" replacementRange:NSMakeRange(0, 1)]; [view insertText:@"배" replacementRange:NSMakeRange(0, 1)]; [view doCommandBySelector:@selector(insertNewLine:)]; }); // Add a hook for the KeyEvent being received by the TextfieldController. E.g. // this is where the Omnibox would start to search when Return is pressed. bool saw_vkey_return = false; SetHandleKeyEventCallback(base::BindRepeating( [](bool* saw_return, Textfield* textfield, const ui::KeyEvent& event) { if (event.key_code() == ui::VKEY_RETURN) { EXPECT_FALSE(*saw_return); *saw_return = true; EXPECT_EQ(base::SysNSStringToUTF16(@"배"), textfield->GetText()); } return false; }, &saw_vkey_return)); EXPECT_EQ(u"", textfield->GetText()); g_fake_interpret_key_events = &handle_q_in_ime; [ns_view_ keyDown:q_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"ㅂ"), textfield->GetText()); EXPECT_FALSE(saw_vkey_return); g_fake_interpret_key_events = &handle_o_in_ime; [ns_view_ keyDown:o_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"배"), textfield->GetText()); EXPECT_FALSE(saw_vkey_return); // Note the "Enter" should not replace the replacement range, even though a // replacement range was set. g_fake_interpret_key_events = &handle_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; EXPECT_EQ(base::SysNSStringToUTF16(@"배"), textfield->GetText()); // VKEY_RETURN should be seen by via the unhandled key event handler (but not // via -insertText:. EXPECT_TRUE(saw_vkey_return); g_fake_interpret_key_events = nullptr; } // Test simulated codepaths for typing 'm', 'o', 'o', Enter in the Telex IME. // This IME does not mark text, but, unlike 2-set Korean, it re-inserts the // entire word on each keypress, even though only the last character in the word // can be modified. This prevents the keypress being treated as a "character" // event (which is unavoidably unfortunate for the Undo buffer), but also led to // a codepath that suppressed a VKEY_RETURN when it should not, since there is // no candidate IME window to dismiss for this IME. TEST_F(BridgedNativeWidgetTest, TextInput_SimulateTelexMoo) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); EnterAcceleratorView* enter_view = new EnterAcceleratorView(); textfield->parent()->AddChildView(enter_view); // Sequence of calls (and corresponding keyDown events) obtained via tracing // with Telex IME and pressing 'm', 'o', 'o', then Enter on the keyboard. // Note that without the leading 'm', only one character changes, which could // allow the keypress to be treated as a character event, which would not // produce the bug. NSEvent* m_in_ime = UnicodeKeyDown(46, @"m"); InterpretKeyEventsCallback handle_m_in_ime = base::BindRepeating([](id view) { [view insertText:@"m" replacementRange:NSMakeRange(NSNotFound, 0)]; }); // Note that (unlike Korean IME), Telex generates a latin "o" for both events: // it doesn't associate a unicode character on the second NSEvent. NSEvent* o_in_ime = UnicodeKeyDown(31, @"o"); InterpretKeyEventsCallback handle_first_o_in_ime = base::BindRepeating([](id view) { // Note the whole word is replaced, not just the last character. [view insertText:@"mo" replacementRange:NSMakeRange(0, 1)]; }); InterpretKeyEventsCallback handle_second_o_in_ime = base::BindRepeating([](id view) { [view insertText:@"mô" replacementRange:NSMakeRange(0, 2)]; }); InterpretKeyEventsCallback handle_return_in_ime = base::BindRepeating([](id view) { // Note the previous -insertText: repeats, even though it is unchanged. // But the IME also follows with an -insertNewLine:. [view insertText:@"mô" replacementRange:NSMakeRange(0, 2)]; [view doCommandBySelector:@selector(insertNewLine:)]; }); EXPECT_EQ(u"", textfield->GetText()); EXPECT_EQ(0, enter_view->count()); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); g_fake_interpret_key_events = &handle_m_in_ime; [ns_view_ keyDown:m_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"m"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_first_o_in_ime; [ns_view_ keyDown:o_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"mo"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_second_o_in_ime; [ns_view_ keyDown:o_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"mô"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; EXPECT_EQ(base::SysNSStringToUTF16(@"mô"), textfield->GetText()); // No change. EXPECT_EQ(1, enter_view->count()); // Now we see the accelerator. } // Simulate 'a' and candidate selection keys. This should just insert "啊", // suppressing accelerators. TEST_F(BridgedNativeWidgetTest, TextInput_NoAcceleratorPinyinSelectWord) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); EnterAcceleratorView* enter_view = new EnterAcceleratorView(); textfield->parent()->AddChildView(enter_view); // Sequence of calls (and corresponding keyDown events) obtained via tracing // with Pinyin IME and pressing 'a', Tab, PageDown, PageUp, Right, Down, Left, // and finally Up on the keyboard. // Note 0 is the actual keyCode for 'a', not a placeholder. NSEvent* a_in_ime = UnicodeKeyDown(0, @"a"); InterpretKeyEventsCallback handle_a_in_ime = base::BindRepeating([](id view) { // Pinyin does not change composition text while selecting candidate words. [view setMarkedText:@"a" selectedRange:NSMakeRange(1, 0) replacementRange:NSMakeRange(NSNotFound, 0)]; }); InterpretKeyEventsCallback handle_tab_in_ime = base::BindRepeating([](id view) { [view setMarkedText:@"ā" selectedRange:NSMakeRange(0, 1) replacementRange:NSMakeRange(NSNotFound, 0)]; }); // Composition text will not change in candidate selection. InterpretKeyEventsCallback handle_candidate_select_in_ime = base::BindRepeating([](id view) {}); InterpretKeyEventsCallback handle_space_in_ime = base::BindRepeating([](id view) { // Space will confirm the composition. [view insertText:@"啊" replacementRange:NSMakeRange(NSNotFound, 0)]; }); InterpretKeyEventsCallback handle_enter_in_ime = base::BindRepeating([](id view) { // Space after Space will generate -insertNewLine:. [view doCommandBySelector:@selector(insertNewLine:)]; }); EXPECT_EQ(u"", textfield->GetText()); EXPECT_EQ(0, enter_view->count()); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); g_fake_interpret_key_events = &handle_a_in_ime; [ns_view_ keyDown:a_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"a"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_tab_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; EXPECT_EQ(base::SysNSStringToUTF16(@"ā"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); // Not seen as an accelerator. // Pinyin changes candidate word on this sequence of keys without changing the // composition text. At the end of this sequence, the word "啊" should be // selected. const ui::KeyboardCode key_seqence[] = {ui::VKEY_NEXT, ui::VKEY_PRIOR, ui::VKEY_RIGHT, ui::VKEY_DOWN, ui::VKEY_LEFT, ui::VKEY_UP}; g_fake_interpret_key_events = &handle_candidate_select_in_ime; for (auto key : key_seqence) { [ns_view_ keyDown:VkeyKeyDown(key)]; EXPECT_EQ(base::SysNSStringToUTF16(@"ā"), textfield->GetText()); // No change. EXPECT_EQ(0, enter_view->count()); } // Space to confirm composition g_fake_interpret_key_events = &handle_space_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_SPACE)]; EXPECT_EQ(base::SysNSStringToUTF16(@"啊"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); // The next Enter should be processed as accelerator. g_fake_interpret_key_events = &handle_enter_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; EXPECT_EQ(base::SysNSStringToUTF16(@"啊"), textfield->GetText()); EXPECT_EQ(1, enter_view->count()); } // Simulate 'a', Enter in Hiragana. This should just insert "あ", suppressing // accelerators. TEST_F(BridgedNativeWidgetTest, TextInput_NoAcceleratorEnterComposition) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); EnterAcceleratorView* enter_view = new EnterAcceleratorView(); textfield->parent()->AddChildView(enter_view); // Sequence of calls (and corresponding keyDown events) obtained via tracing // with Hiragana IME and pressing 'a', then Enter on the keyboard. // Note 0 is the actual keyCode for 'a', not a placeholder. NSEvent* a_in_ime = UnicodeKeyDown(0, @"a"); InterpretKeyEventsCallback handle_a_in_ime = base::BindRepeating([](id view) { // TODO(crbug/612675): |text| should be an NSAttributedString. [view setMarkedText:@"あ" selectedRange:NSMakeRange(1, 0) replacementRange:NSMakeRange(NSNotFound, 0)]; }); InterpretKeyEventsCallback handle_first_return_in_ime = base::BindRepeating([](id view) { [view insertText:@"あ" replacementRange:NSMakeRange(NSNotFound, 0)]; // Note there is no call to -insertNewLine: here. }); InterpretKeyEventsCallback handle_second_return_in_ime = base::BindRepeating( [](id view) { [view doCommandBySelector:@selector(insertNewLine:)]; }); EXPECT_EQ(u"", textfield->GetText()); EXPECT_EQ(0, enter_view->count()); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); g_fake_interpret_key_events = &handle_a_in_ime; [ns_view_ keyDown:a_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"あ"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_first_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; EXPECT_EQ(base::SysNSStringToUTF16(@"あ"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); // Not seen as an accelerator. g_fake_interpret_key_events = &handle_second_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; // Sanity check: send Enter again. EXPECT_EQ(base::SysNSStringToUTF16(@"あ"), textfield->GetText()); // No change. EXPECT_EQ(1, enter_view->count()); // Now we see the accelerator. } // Simulate 'a', Tab, Enter, Enter in Hiragana. This should just insert "a", // suppressing accelerators. TEST_F(BridgedNativeWidgetTest, TextInput_NoAcceleratorTabEnterComposition) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); EnterAcceleratorView* enter_view = new EnterAcceleratorView(); textfield->parent()->AddChildView(enter_view); // Sequence of calls (and corresponding keyDown events) obtained via tracing // with Hiragana IME and pressing 'a', Tab, then Enter on the keyboard. NSEvent* a_in_ime = UnicodeKeyDown(0, @"a"); InterpretKeyEventsCallback handle_a_in_ime = base::BindRepeating([](id view) { // TODO(crbug/612675): |text| should have an underline. [view setMarkedText:@"あ" selectedRange:NSMakeRange(1, 0) replacementRange:NSMakeRange(NSNotFound, 0)]; }); InterpretKeyEventsCallback handle_tab_in_ime = base::BindRepeating([](id view) { // TODO(crbug/612675): |text| should be an NSAttributedString (now with // a different underline color). [view setMarkedText:@"a" selectedRange:NSMakeRange(0, 1) replacementRange:NSMakeRange(NSNotFound, 0)]; // Note there is no -insertTab: generated. }); InterpretKeyEventsCallback handle_first_return_in_ime = base::BindRepeating([](id view) { // Do *nothing*. Enter does not confirm nor change the composition, it // just dismisses the IME window, leaving the text marked. }); InterpretKeyEventsCallback handle_second_return_in_ime = base::BindRepeating([](id view) { // The second return will confirm the composition. [view insertText:@"a" replacementRange:NSMakeRange(NSNotFound, 0)]; }); InterpretKeyEventsCallback handle_third_return_in_ime = base::BindRepeating([](id view) { // Only the third return will generate -insertNewLine:. [view doCommandBySelector:@selector(insertNewLine:)]; }); EXPECT_EQ(u"", textfield->GetText()); EXPECT_EQ(0, enter_view->count()); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); g_fake_interpret_key_events = &handle_a_in_ime; [ns_view_ keyDown:a_in_ime]; EXPECT_EQ(base::SysNSStringToUTF16(@"あ"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_tab_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_TAB)]; // Tab will switch to a Romanji (Latin) character. EXPECT_EQ(base::SysNSStringToUTF16(@"a"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); g_fake_interpret_key_events = &handle_first_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; // Enter just dismisses the IME window. The composition is still active. EXPECT_EQ(base::SysNSStringToUTF16(@"a"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); // Not seen as an accelerator. g_fake_interpret_key_events = &handle_second_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; // Enter now confirms the composition (unmarks text). Note there is still no // IME window visible but, since there is marked text, IME is still active. EXPECT_EQ(base::SysNSStringToUTF16(@"a"), textfield->GetText()); EXPECT_EQ(0, enter_view->count()); // Not seen as an accelerator. g_fake_interpret_key_events = &handle_third_return_in_ime; [ns_view_ keyDown:VkeyKeyDown(ui::VKEY_RETURN)]; // Send Enter a third time. EXPECT_EQ(base::SysNSStringToUTF16(@"a"), textfield->GetText()); // No change. EXPECT_EQ(1, enter_view->count()); // Now we see the accelerator. } // Test a codepath that could hypothetically cause [NSApp updateWindows] to be // called recursively due to IME dismissal during teardown triggering a focus // change. Twice. TEST_F(BridgedNativeWidgetTest, TextInput_RecursiveUpdateWindows) { Textfield* textfield = InstallTextField(""); EXPECT_TRUE([ns_view_ textInputClient]); object_setClass(ns_view_, [InterpretKeyEventMockedBridgedContentView class]); base::mac::ScopedObjCClassSwizzler update_windows_swizzler( [NSApplication class], [UpdateWindowsDonorForNSApp class], @selector(updateWindows)); base::mac::ScopedObjCClassSwizzler current_input_context_swizzler( [NSTextInputContext class], [CurrentInputContextDonorForNSTextInputContext class], @selector(currentInputContext)); int vkey_return_count = 0; // Everything happens with this one event. NSEvent* return_with_fake_ime = cocoa_test_event_utils::SynthesizeKeyEvent( widget_->GetNativeWindow().GetNativeNSWindow(), true, ui::VKEY_RETURN, 0); InterpretKeyEventsCallback generate_return_and_fake_ime = base::BindRepeating( [](int* saw_return_count, id view) { EXPECT_EQ(0, *saw_return_count); // First generate the return to simulate an input context change. [view insertText:@"\r" replacementRange:NSMakeRange(NSNotFound, 0)]; EXPECT_EQ(1, *saw_return_count); }, &vkey_return_count); bool saw_update_windows = false; base::RepeatingClosure update_windows_closure = base::BindRepeating( [](bool* saw_update_windows, BridgedContentView* view, NativeWidgetMacNSWindowHost* host, Textfield* textfield) { // Ensure updateWindows is not invoked recursively. EXPECT_FALSE(*saw_update_windows); *saw_update_windows = true; // Inside updateWindows, assume the IME got dismissed and wants to // insert its last bit of text for the old input context. [view insertText:@"배" replacementRange:NSMakeRange(0, 1)]; // This is triggered by the setTextInputClient:nullptr in // SetHandleKeyEventCallback(), so -inputContext should also be nil. EXPECT_FALSE([view inputContext]); // Ensure we can't recursively call updateWindows. A TextInputClient // reacting to InsertChar could theoretically do this, but toolkit-views // DCHECKs if there is recursive event dispatch, so call // setTextInputClient directly. host->text_input_host()->SetTextInputClient(textfield); // Finally simulate what -[NSApp updateWindows] should _actually_ do, // which is to update the input context (from the first responder). g_fake_current_input_context = [view inputContext]; // Now, the |textfield| set above should have been set again. EXPECT_TRUE(g_fake_current_input_context); }, &saw_update_windows, ns_view_, GetNSWindowHost(), textfield); SetHandleKeyEventCallback(base::BindRepeating( [](int* saw_return_count, BridgedContentView* view, NativeWidgetMacNSWindowHost* host, Textfield* textfield, const ui::KeyEvent& event) { if (event.key_code() == ui::VKEY_RETURN) { *saw_return_count += 1; // Simulate Textfield::OnBlur() by clearing the input method. // Textfield needs to be in a Widget to do this normally. host->text_input_host()->SetTextInputClient(nullptr); } return false; }, &vkey_return_count, ns_view_, GetNSWindowHost())); // Starting text (just insert it). [ns_view_ insertText:@"ㅂ" replacementRange:NSMakeRange(NSNotFound, 0)]; EXPECT_EQ(base::SysNSStringToUTF16(@"ㅂ"), textfield->GetText()); g_fake_interpret_key_events = &generate_return_and_fake_ime; g_update_windows_closure = &update_windows_closure; g_fake_current_input_context = [ns_view_ inputContext]; EXPECT_TRUE(g_fake_current_input_context); [ns_view_ keyDown:return_with_fake_ime]; // We should see one VKEY_RETURNs and one updateWindows. In particular, note // that there is not a second VKEY_RETURN seen generated by keyDown: thinking // the event has been unhandled. This is because it was handled when the fake // IME sent \r. EXPECT_TRUE(saw_update_windows); EXPECT_EQ(1, vkey_return_count); // The text inserted during updateWindows should have been inserted, even // though we were trying to change the input context. EXPECT_EQ(base::SysNSStringToUTF16(@"배"), textfield->GetText()); EXPECT_TRUE(g_fake_current_input_context); g_fake_current_input_context = nullptr; g_fake_interpret_key_events = nullptr; g_update_windows_closure = nullptr; } // Write selection text to the pasteboard. TEST_F(BridgedNativeWidgetTest, TextInput_WriteToPasteboard) { const std::string test_string = "foo bar baz"; InstallTextField(test_string); NSArray* types = @[ NSPasteboardTypeString ]; // Try to write with no selection. This will succeed, but the string will be // empty. { NSPasteboard* pboard = [NSPasteboard pasteboardWithUniqueName]; BOOL wrote_to_pboard = [ns_view_ writeSelectionToPasteboard:pboard types:types]; EXPECT_TRUE(wrote_to_pboard); NSArray* objects = [pboard readObjectsForClasses:@[ [NSString class] ] options:nullptr]; EXPECT_EQ(1u, [objects count]); EXPECT_NSEQ(@"", [objects lastObject]); } // Write a selection successfully. { SetSelectionRange(NSMakeRange(4, 7)); NSPasteboard* pboard = [NSPasteboard pasteboardWithUniqueName]; BOOL wrote_to_pboard = [ns_view_ writeSelectionToPasteboard:pboard types:types]; EXPECT_TRUE(wrote_to_pboard); NSArray* objects = [pboard readObjectsForClasses:@[ [NSString class] ] options:nullptr]; EXPECT_EQ(1u, [objects count]); EXPECT_NSEQ(@"bar baz", [objects lastObject]); } } TEST_F(BridgedNativeWidgetTest, WriteToFindPasteboard) { base::mac::ScopedObjCClassSwizzler swizzler([FindPasteboard class], [MockFindPasteboard class], @selector(sharedInstance)); EXPECT_NSEQ(@"", [[FindPasteboard sharedInstance] findText]); const std::string test_string = "foo bar baz"; InstallTextField(test_string); SetSelectionRange(NSMakeRange(4, 7)); [ns_view_ copyToFindPboard:nil]; EXPECT_NSEQ(@"bar baz", [[FindPasteboard sharedInstance] findText]); // Don't overwrite with empty selection SetSelectionRange(NSMakeRange(0, 0)); [ns_view_ copyToFindPboard:nil]; EXPECT_NSEQ(@"bar baz", [[FindPasteboard sharedInstance] findText]); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/bridged_native_widget_unittest.mm
Objective-C++
unknown
80,460
// 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 "components/remote_cocoa/app_shim/mouse_capture.h" #import <Cocoa/Cocoa.h> #import "base/mac/scoped_nsobject.h" #import "components/remote_cocoa/app_shim/mouse_capture_delegate.h" #import "ui/base/test/cocoa_helper.h" #import "ui/events/test/cocoa_test_event_utils.h" // Simple test view that counts calls to -[NSView mouseDown:]. @interface CocoaMouseCaptureTestView : NSView { @private int _mouseDownCount; } @property(readonly, nonatomic) int mouseDownCount; @end @implementation CocoaMouseCaptureTestView @synthesize mouseDownCount = _mouseDownCount; - (void)mouseDown:(NSEvent*)theEvent { ++_mouseDownCount; } @end namespace remote_cocoa { namespace { // Simple capture delegate that just counts events forwarded. class TestCaptureDelegate : public CocoaMouseCaptureDelegate { public: explicit TestCaptureDelegate(NSWindow* window) : window_(window) {} TestCaptureDelegate(const TestCaptureDelegate&) = delete; TestCaptureDelegate& operator=(const TestCaptureDelegate&) = delete; void Acquire() { mouse_capture_ = std::make_unique<CocoaMouseCapture>(this); } bool IsActive() { return mouse_capture_ && mouse_capture_->IsActive(); } void SimulateDestroy() { mouse_capture_.reset(); } void set_should_claim_event(bool should_claim_event) { should_claim_event_ = should_claim_event; } int event_count() { return event_count_; } int capture_lost_count() { return capture_lost_count_; } // CocoaMouseCaptureDelegate: bool PostCapturedEvent(NSEvent* event) override { ++event_count_; return should_claim_event_; } void OnMouseCaptureLost() override { ++capture_lost_count_; } NSWindow* GetWindow() const override { return window_; } private: std::unique_ptr<CocoaMouseCapture> mouse_capture_; bool should_claim_event_ = true; int event_count_ = 0; int capture_lost_count_ = 0; NSWindow* window_; }; } // namespace using CocoaMouseCaptureTest = ui::CocoaTest; // Test that a new capture properly "steals" capture from an existing one. TEST_F(CocoaMouseCaptureTest, OnCaptureLost) { TestCaptureDelegate capture(nil); capture.Acquire(); EXPECT_TRUE(capture.IsActive()); { TestCaptureDelegate capture2(nil); EXPECT_EQ(0, capture.capture_lost_count()); // A second capture steals from the first. capture2.Acquire(); EXPECT_TRUE(capture2.IsActive()); EXPECT_FALSE(capture.IsActive()); EXPECT_EQ(1, capture.capture_lost_count()); EXPECT_EQ(0, capture2.capture_lost_count()); // Simulate capture2 going out of scope. Inspect it. capture2.SimulateDestroy(); EXPECT_FALSE(capture2.IsActive()); EXPECT_EQ(1, capture2.capture_lost_count()); } // Re-acquiring is fine (not stealing). EXPECT_FALSE(capture.IsActive()); capture.Acquire(); EXPECT_TRUE(capture.IsActive()); // Having no CocoaMouseCapture instance is fine. capture.SimulateDestroy(); EXPECT_FALSE(capture.IsActive()); // Receives OnMouseCaptureLost again, since reacquired. EXPECT_EQ(2, capture.capture_lost_count()); } // Test event capture. TEST_F(CocoaMouseCaptureTest, CaptureEvents) { base::scoped_nsobject<CocoaMouseCaptureTestView> view( [[CocoaMouseCaptureTestView alloc] initWithFrame:NSZeroRect]); [test_window() setContentView:view]; std::pair<NSEvent*, NSEvent*> click = cocoa_test_event_utils::MouseClickInView(view, 1); // First check that the view receives events normally. EXPECT_EQ(0, [view mouseDownCount]); [NSApp sendEvent:click.first]; EXPECT_EQ(1, [view mouseDownCount]); { TestCaptureDelegate capture(test_window()); capture.Acquire(); // Now check that the capture captures events. EXPECT_EQ(0, capture.event_count()); [NSApp sendEvent:click.first]; EXPECT_EQ(1, [view mouseDownCount]); EXPECT_EQ(1, capture.event_count()); } // After the capture goes away, events should be received again. [NSApp sendEvent:click.first]; EXPECT_EQ(2, [view mouseDownCount]); } // Test local events properly swallowed / propagated. TEST_F(CocoaMouseCaptureTest, SwallowOrPropagateEvents) { base::scoped_nsobject<CocoaMouseCaptureTestView> view( [[CocoaMouseCaptureTestView alloc] initWithFrame:NSZeroRect]); [test_window() setContentView:view]; std::pair<NSEvent*, NSEvent*> click = cocoa_test_event_utils::MouseClickInView(view, 1); // First check that the view receives events normally. EXPECT_EQ(0, [view mouseDownCount]); [NSApp sendEvent:click.first]; EXPECT_EQ(1, [view mouseDownCount]); { TestCaptureDelegate capture(test_window()); capture.Acquire(); // By default, the delegate should claim events. EXPECT_EQ(0, capture.event_count()); [NSApp sendEvent:click.first]; EXPECT_EQ(1, [view mouseDownCount]); EXPECT_EQ(1, capture.event_count()); // Set the delegate not to claim events. capture.set_should_claim_event(false); [NSApp sendEvent:click.first]; EXPECT_EQ(2, [view mouseDownCount]); EXPECT_EQ(2, capture.event_count()); // Setting it back should restart the claiming of events. capture.set_should_claim_event(true); [NSApp sendEvent:click.first]; EXPECT_EQ(2, [view mouseDownCount]); EXPECT_EQ(3, capture.event_count()); } } } // namespace remote_cocoa
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/cocoa_mouse_capture_unittest.mm
Objective-C++
unknown
5,408
// 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_COCOA_DRAG_DROP_CLIENT_MAC_H_ #define UI_VIEWS_COCOA_DRAG_DROP_CLIENT_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/drag_drop_client.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/views/views_export.h" #include "ui/views/widget/drop_helper.h" namespace gfx { class Point; } // namespace gfx namespace remote_cocoa { class NativeWidgetNSWindowBridge; } // namespace remote_cocoa namespace views { namespace test { class DragDropClientMacTest; } // namespace test class View; // Implements drag and drop on MacViews. This class acts as a bridge between // the Views and native system's drag and drop. This class mimics // DesktopDragDropClientAuraX11. class VIEWS_EXPORT DragDropClientMac : public remote_cocoa::DragDropClient { public: DragDropClientMac(remote_cocoa::NativeWidgetNSWindowBridge* bridge, View* root_view); DragDropClientMac(const DragDropClientMac&) = delete; DragDropClientMac& operator=(const DragDropClientMac&) = delete; ~DragDropClientMac() override; // Initiates a drag and drop session. Returns the drag operation that was // applied at the end of the drag drop session. void StartDragAndDrop(View* view, std::unique_ptr<ui::OSExchangeData> data, int operation, ui::mojom::DragEventSource source); DropHelper* drop_helper() { return &drop_helper_; } // remote_cocoa::DragDropClient: NSDragOperation DragUpdate(id<NSDraggingInfo>) override; NSDragOperation Drop(id<NSDraggingInfo> sender) override; void EndDrag() override; void DragExit() override; private: friend class test::DragDropClientMacTest; // Converts the given NSPoint to the coordinate system in Views. gfx::Point LocationInView(NSPoint point) const; // Provides the data for the drag and drop session. std::unique_ptr<ui::OSExchangeData> exchange_data_; // Used to handle drag and drop with Views. DropHelper drop_helper_; // The drag and drop operation. int source_operation_ = 0; int last_operation_ = 0; // The bridge between the content view and the drag drop client. raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge, DanglingUntriaged> bridge_; // Weak. Owns |this|. // The closure for the drag and drop's run loop. base::OnceClosure quit_closure_; // Whether |this| is the source of current dragging session. bool is_drag_source_ = false; }; } // namespace views #endif // UI_VIEWS_COCOA_DRAG_DROP_CLIENT_MAC_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/drag_drop_client_mac.h
Objective-C
unknown
2,850
// 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. #import "ui/views/cocoa/drag_drop_client_mac.h" #include "base/mac/mac_util.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #import "components/remote_cocoa/app_shim/bridged_content_view.h" #import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h" #import "ui/base/dragdrop/os_exchange_data_provider_mac.h" #include "ui/gfx/image/image_skia_util_mac.h" #include "ui/views/drag_utils.h" #include "ui/views/widget/native_widget_mac.h" namespace views { DragDropClientMac::DragDropClientMac( remote_cocoa::NativeWidgetNSWindowBridge* bridge, View* root_view) : drop_helper_(root_view), bridge_(bridge) { DCHECK(bridge); } DragDropClientMac::~DragDropClientMac() = default; void DragDropClientMac::StartDragAndDrop( View* view, std::unique_ptr<ui::OSExchangeData> data, int operation, ui::mojom::DragEventSource source) { exchange_data_ = std::move(data); source_operation_ = operation; is_drag_source_ = true; const ui::OSExchangeDataProviderMac& provider_mac = static_cast<const ui::OSExchangeDataProviderMac&>( exchange_data_->provider()); // Release capture before beginning the dragging session. Capture may have // been acquired on the mouseDown, but capture is not required during the // dragging session and the mouseUp that would release it will be suppressed. bridge_->ReleaseCapture(); // Synthesize an event for dragging, since we can't be sure that // [NSApp currentEvent] will return a valid dragging event. NSWindow* window = bridge_->ns_window(); NSPoint position = [window mouseLocationOutsideOfEventStream]; NSTimeInterval event_time = [[NSApp currentEvent] timestamp]; NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDragged location:position modifierFlags:0 timestamp:event_time windowNumber:[window windowNumber] context:nil eventNumber:0 clickCount:1 pressure:1.0]; NSImage* image = gfx::NSImageFromImageSkiaWithColorSpace( provider_mac.GetDragImage(), base::mac::GetSRGBColorSpace()); DCHECK(!NSEqualSizes(image.size, NSZeroSize)); NSArray<NSDraggingItem*>* drag_items = provider_mac.GetDraggingItems(); if (!drag_items) { // The source of this data is ultimately the OS, and while this shouldn't be // nil, it is documented as possibly being so if things are broken. If so, // fail early rather than try to start a drag of a nil item list and making // things worse. return; } // At this point the mismatch between the Views drag API, which assumes a // single drag item, and the macOS drag API, which allows for multiple items, // is encountered. For now, set the dragging frame and image on the first // item, and set nil images for the remaining items. In the future, when Views // becomes more capable in the area of the clipboard, revisit this. // Create the frame to cause the mouse to be centered over the image, with the // image slightly above the mouse pointer for visibility. NSRect dragging_frame = NSMakeRect(event.locationInWindow.x - image.size.width / 2, event.locationInWindow.y - image.size.height / 4, image.size.width, image.size.height); for (NSUInteger i = 0; i < drag_items.count; ++i) { if (i == 0) { [drag_items[i] setDraggingFrame:dragging_frame contents:image]; } else { [drag_items[i] setDraggingFrame:NSMakeRect(0, 0, 1, 1) contents:nil]; } } [bridge_->ns_view() beginDraggingSessionWithItems:drag_items event:event source:bridge_->ns_view()]; // Since Drag and drop is asynchronous on the Mac, spin a nested run loop for // consistency with other platforms. base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); } NSDragOperation DragDropClientMac::DragUpdate(id<NSDraggingInfo> sender) { if (!exchange_data_) { exchange_data_ = std::make_unique<OSExchangeData>( ui::OSExchangeDataProviderMac::CreateProviderWrappingPasteboard( [sender draggingPasteboard])); source_operation_ = ui::DragDropTypes::NSDragOperationToDragOperation( [sender draggingSourceOperationMask]); } last_operation_ = drop_helper_.OnDragOver( *exchange_data_, LocationInView([sender draggingLocation]), source_operation_); return ui::DragDropTypes::DragOperationToNSDragOperation(last_operation_); } NSDragOperation DragDropClientMac::Drop(id<NSDraggingInfo> sender) { // OnDrop may delete |this|, so clear |exchange_data_| first. std::unique_ptr<ui::OSExchangeData> exchange_data = std::move(exchange_data_); ui::mojom::DragOperation drag_operation = drop_helper_.OnDrop( *exchange_data, LocationInView([sender draggingLocation]), last_operation_); return ui::DragDropTypes::DragOperationToNSDragOperation( static_cast<int>(drag_operation)); } void DragDropClientMac::EndDrag() { exchange_data_.reset(); is_drag_source_ = false; // Allow a test to invoke EndDrag() without spinning the nested run loop. if (!quit_closure_.is_null()) std::move(quit_closure_).Run(); } void DragDropClientMac::DragExit() { drop_helper_.OnDragExit(); if (!is_drag_source_) exchange_data_.reset(); } gfx::Point DragDropClientMac::LocationInView(NSPoint point) const { NSRect content_rect = [bridge_->ns_window() contentRectForFrameRect:[bridge_->ns_window() frame]]; return gfx::Point(point.x, NSHeight(content_rect) - point.y); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/drag_drop_client_mac.mm
Objective-C++
unknown
6,160
// 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 "base/memory/raw_ptr.h" #import "base/task/single_thread_task_runner.h" #include "base/task/single_thread_task_runner.h" #import "ui/views/cocoa/drag_drop_client_mac.h" #import <Cocoa/Cocoa.h> #include "base/functional/bind.h" #import "base/mac/scoped_objc_class_swizzler.h" #include "base/strings/utf_string_conversions.h" #import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #import "ui/base/clipboard/clipboard_util_mac.h" #import "ui/base/dragdrop/drag_drop_types.h" #import "ui/base/dragdrop/mojom/drag_drop_types.mojom.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/gfx/image/image_unittest_util.h" #import "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/test/widget_test.h" #include "ui/views/view.h" #include "ui/views/widget/native_widget_mac.h" #include "ui/views/widget/widget.h" @interface NSView (DragSessionTestingDonor) @end @implementation NSView (DragSessionTestingDonor) - (NSDraggingSession*)cr_beginDraggingSessionWithItems:(NSArray*)items event:(NSEvent*)event source:(id<NSDraggingSource>) source { return nil; } @end // Mocks the NSDraggingInfo sent to the DragDropClientMac's DragUpdate() and // Drop() methods. Out of the required methods of the protocol, only // draggingLocation and draggingPasteboard are used. @interface MockDraggingInfo : NSObject<NSDraggingInfo> { NSPasteboard* _pasteboard; } @property BOOL animatesToDestination; @property NSInteger numberOfValidItemsForDrop; @property NSDraggingFormation draggingFormation; @property(readonly) NSSpringLoadingHighlight springLoadingHighlight; @end @implementation MockDraggingInfo @synthesize animatesToDestination; @synthesize numberOfValidItemsForDrop; @synthesize draggingFormation; @synthesize springLoadingHighlight; - (instancetype)initWithPasteboard:(NSPasteboard*)pasteboard { if ((self = [super init])) { _pasteboard = pasteboard; } return self; } - (NSPoint)draggingLocation { return NSMakePoint(50, 50); } - (NSPasteboard*)draggingPasteboard { return _pasteboard; } - (NSInteger)draggingSequenceNumber { return 0; } - (id)draggingSource { return nil; } - (NSDragOperation)draggingSourceOperationMask { return NSDragOperationEvery; } - (NSWindow*)draggingDestinationWindow { return nil; } - (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)dropDestination { return nil; } - (NSImage*)draggedImage { return nil; } - (NSPoint)draggedImageLocation { return NSZeroPoint; } - (void)slideDraggedImageTo:(NSPoint)aPoint { } - (void) enumerateDraggingItemsWithOptions:(NSDraggingItemEnumerationOptions)enumOpts forView:(NSView*)view classes:(NSArray*)classArray searchOptions:(NSDictionary*)searchOptions usingBlock:(void (^)(NSDraggingItem* draggingItem, NSInteger idx, BOOL* stop))block { } - (void)resetSpringLoading { } @end namespace views::test { using ::base::ASCIIToUTF16; using ::ui::mojom::DragOperation; // View object that will receive and process dropped data from the test. class DragDropView : public View { public: DragDropView() = default; DragDropView(const DragDropView&) = delete; DragDropView& operator=(const DragDropView&) = delete; void set_formats(int formats) { formats_ = formats; } // View: bool GetDropFormats( int* formats, std::set<ui::ClipboardFormatType>* format_types) override { *formats |= formats_; return true; } bool CanDrop(const OSExchangeData& data) override { return true; } int OnDragUpdated(const ui::DropTargetEvent& event) override { return ui::DragDropTypes::DRAG_COPY; } views::View::DropCallback GetDropCallback( const ui::DropTargetEvent& event) override { return base::BindOnce( [](const ui::DropTargetEvent& event, ui::mojom::DragOperation& output_drag_op, std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) { output_drag_op = DragOperation::kMove; }); } private: // Drop formats accepted by this View object. int formats_ = 0; }; class DragDropClientMacTest : public WidgetTest { public: DragDropClientMacTest() : widget_(new Widget) {} DragDropClientMacTest(const DragDropClientMacTest&) = delete; DragDropClientMacTest& operator=(const DragDropClientMacTest&) = delete; DragDropClientMac* drag_drop_client() { return ns_window_host_->drag_drop_client(); } NSDragOperation DragUpdate(NSPasteboard* pasteboard) { DragDropClientMac* client = drag_drop_client(); dragging_info_.reset( [[MockDraggingInfo alloc] initWithPasteboard:pasteboard]); return client->DragUpdate(dragging_info_.get()); } NSDragOperation Drop() { DragDropClientMac* client = drag_drop_client(); DCHECK(dragging_info_.get()); NSDragOperation operation = client->Drop(dragging_info_.get()); dragging_info_.reset(); return operation; } void SetData(OSExchangeData& data) { drag_drop_client()->exchange_data_ = std::make_unique<ui::OSExchangeData>(data.provider().Clone()); } // testing::Test: void SetUp() override { WidgetTest::SetUp(); widget_ = CreateTopLevelPlatformWidget(); gfx::Rect bounds(0, 0, 100, 100); widget_->SetBounds(bounds); ns_window_host_ = NativeWidgetMacNSWindowHost::GetFromNativeWindow( widget_->GetNativeWindow()); bridge_ = ns_window_host_->GetInProcessNSWindowBridge(); widget_->Show(); target_ = new DragDropView(); widget_->non_client_view()->frame_view()->AddChildView(target_.get()); target_->SetBoundsRect(bounds); drag_drop_client()->source_operation_ = ui::DragDropTypes::DRAG_COPY; } void TearDown() override { if (widget_) widget_->CloseNow(); WidgetTest::TearDown(); } protected: raw_ptr<Widget> widget_ = nullptr; raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge> bridge_ = nullptr; raw_ptr<NativeWidgetMacNSWindowHost> ns_window_host_ = nullptr; raw_ptr<DragDropView> target_ = nullptr; base::scoped_nsobject<MockDraggingInfo> dragging_info_; }; // Tests if the drag and drop target receives the dropped data. TEST_F(DragDropClientMacTest, BasicDragDrop) { // Create the drop data OSExchangeData data; const std::u16string& text = u"text"; data.SetString(text); SetData(data); target_->set_formats(ui::OSExchangeData::STRING | ui::OSExchangeData::URL); // Check if the target receives the data from a drop and returns the expected // operation. EXPECT_EQ(DragUpdate(nil), NSDragOperationCopy); EXPECT_EQ(Drop(), NSDragOperationMove); } // Ensure that capture is released before the end of a drag and drop operation. TEST_F(DragDropClientMacTest, ReleaseCapture) { // DragDropView doesn't actually capture the mouse, so explicitly acquire it // to test that StartDragAndDrop() actually releases it. // Although this is not an interactive UI test, acquiring capture should be OK // since the runloop will exit before the system has any opportunity to // capture anything. bridge_->AcquireCapture(); EXPECT_TRUE(ns_window_host_->IsMouseCaptureActive()); // Create the drop data std::unique_ptr<OSExchangeData> data(std::make_unique<OSExchangeData>()); const std::u16string& text = u"text"; data->SetString(text); data->provider().SetDragImage(gfx::test::CreateImageSkia(100, 100), gfx::Vector2d()); SetData(*data.get()); // There's no way to cleanly stop NSDraggingSession inside unit tests, so just // don't start it at all. base::mac::ScopedObjCClassSwizzler swizzle( [NSView class], @selector(beginDraggingSessionWithItems:event:source:), @selector(cr_beginDraggingSessionWithItems:event:source:)); // Immediately quit drag'n'drop, or we'll hang. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&DragDropClientMac::EndDrag, base::Unretained(drag_drop_client()))); // It will call ReleaseCapture(). drag_drop_client()->StartDragAndDrop(target_, std::move(data), 0, ui::mojom::DragEventSource::kMouse); // The capture should be released. EXPECT_FALSE(ns_window_host_->IsMouseCaptureActive()); } // Tests if the drag and drop target rejects the dropped data with the // incorrect format. TEST_F(DragDropClientMacTest, InvalidFormatDragDrop) { OSExchangeData data; const std::u16string& text = u"text"; data.SetString(text); SetData(data); target_->set_formats(ui::OSExchangeData::URL); // Check if the target receives the data from a drop and returns the expected // operation. EXPECT_EQ(DragUpdate(nil), NSDragOperationNone); EXPECT_EQ(Drop(), NSDragOperationNone); } // Tests if the drag and drop target can accept data without an OSExchangeData // object. TEST_F(DragDropClientMacTest, PasteboardToOSExchangeTest) { target_->set_formats(ui::OSExchangeData::STRING); scoped_refptr<ui::UniquePasteboard> pasteboard = new ui::UniquePasteboard; // The test should reject the data if the pasteboard is empty. EXPECT_EQ(DragUpdate(pasteboard->get()), NSDragOperationNone); EXPECT_EQ(Drop(), NSDragOperationNone); drag_drop_client()->EndDrag(); // Add valid data to the pasteboard and check to see if the target accepts // it. [pasteboard->get() setString:@"text" forType:NSPasteboardTypeString]; EXPECT_EQ(DragUpdate(pasteboard->get()), NSDragOperationCopy); EXPECT_EQ(Drop(), NSDragOperationMove); } // View object that will close Widget on drop. class DragDropCloseView : public DragDropView { public: DragDropCloseView() = default; DragDropCloseView(const DragDropCloseView&) = delete; DragDropCloseView& operator=(const DragDropCloseView&) = delete; views::View::DropCallback GetDropCallback( const ui::DropTargetEvent& event) override { // base::Unretained is safe here because in the tests the view isn't deleted // before the drop callback is run. return base::BindOnce(&DragDropCloseView::PerformDrop, base::Unretained(this)); } private: void PerformDrop(const ui::DropTargetEvent& event, ui::mojom::DragOperation& output_drag_op, std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) { GetWidget()->CloseNow(); output_drag_op = DragOperation::kMove; } }; // Tests that closing Widget on drop does not crash. TEST_F(DragDropClientMacTest, CloseWidgetOnDrop) { OSExchangeData data; const std::u16string& text = u"text"; data.SetString(text); SetData(data); target_ = new DragDropCloseView(); widget_->non_client_view()->frame_view()->AddChildView(target_.get()); target_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); target_->set_formats(ui::OSExchangeData::STRING | ui::OSExchangeData::URL); EXPECT_EQ(DragUpdate(nil), NSDragOperationCopy); EXPECT_EQ(Drop(), NSDragOperationMove); // Drop callback will have deleted the widget. widget_ = nullptr; } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/drag_drop_client_mac_unittest.mm
Objective-C++
unknown
11,475
// 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 "components/remote_cocoa/app_shim/native_widget_ns_window_fullscreen_controller.h" #include "base/test/task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace remote_cocoa::test { using testing::_; using testing::Invoke; using testing::Return; class MockClient : public NativeWidgetNSWindowFullscreenController::Client { public: MOCK_METHOD1(FullscreenControllerTransitionStart, void(bool)); MOCK_METHOD1(FullscreenControllerTransitionComplete, void(bool)); MOCK_METHOD3(FullscreenControllerSetFrame, void(const gfx::Rect&, bool animate, base::OnceCallback<void()> animation_complete)); MOCK_METHOD0(FullscreenControllerToggleFullscreen, void()); MOCK_METHOD0(FullscreenControllerCloseWindow, void()); MOCK_CONST_METHOD0(FullscreenControllerGetDisplayId, int64_t()); MOCK_CONST_METHOD1(FullscreenControllerGetFrameForDisplay, gfx::Rect(int64_t display_id)); MOCK_CONST_METHOD0(FullscreenControllerGetFrame, gfx::Rect()); }; class MacFullscreenControllerTest : public testing::Test { public: void SetUp() override { EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()).Times(0); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(_, _, _)).Times(0); EXPECT_CALL(mock_client_, FullscreenControllerCloseWindow()).Times(0); } protected: const gfx::Rect kWindowRect{1, 2, 3, 4}; const int64_t kDisplay0Id = 0; const int64_t kDisplay1Id = 1; const gfx::Rect kDisplay0Frame{9, 10, 11, 12}; const gfx::Rect kDisplay1Frame{13, 14, 15, 16}; MockClient mock_client_; NativeWidgetNSWindowFullscreenController controller_{&mock_client_}; base::test::SingleThreadTaskEnvironment task_environment_; }; // Fake implementation of FullscreenControllerSetFrame // which executes the given callback immediately. void FullscreenControllerSetFrameFake(const gfx::Rect&, bool, base::OnceCallback<void()> callback) { std::move(callback).Run(); } // Simple enter-and-exit fullscreen via the green traffic light button. TEST_F(MacFullscreenControllerTest, SimpleUserInitiated) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // The controller should do nothing, and wait until it receives // OnWindowDidEnterFullscreen. task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Calling EnterFullscreen inside the transition will do nothing. controller_.EnterFullscreen(display::kInvalidDisplayId); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Calling EnterFullscreen while fullscreen should do nothing. controller_.EnterFullscreen(display::kInvalidDisplayId); EXPECT_FALSE(controller_.IsInFullscreenTransition()); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Calling EnterFullscreen specifying the display that we are currently on // will also be a no-op. EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillOnce(Return(kDisplay0Id)); controller_.EnterFullscreen(kDisplay0Id); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen via the green traffic light. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.OnWindowWillExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Calling ExitFullscreen inside the transition will do nothing. controller_.ExitFullscreen(); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Complete the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); controller_.OnWindowDidExitFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); task_environment_.RunUntilIdle(); } // Simple enter-and-exit fullscreen programmatically. TEST_F(MacFullscreenControllerTest, SimpleProgrammatic) { // Enter fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.EnterFullscreen(display::kInvalidDisplayId); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // The call to ToggleFullscreen is sent via a posted task, so it shouldn't // happen until after the run loop is pumped. The function // OnWindowWillEnterFullscreen is called from within ToggleFullscreen. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Complete the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); // Exit fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.ExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Make ToggleFullscreen happen, and invoke OnWindowWillExitFullscreen. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Complete the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); controller_.OnWindowDidExitFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); task_environment_.RunUntilIdle(); } // A transition that fails to enter fullscreen. TEST_F(MacFullscreenControllerTest, FailEnterFullscreenSimple) { // Enter fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.EnterFullscreen(display::kInvalidDisplayId); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); // Fail the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); controller_.OnWindowDidExitFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); } // A transition that fails to exit fullscreen. TEST_F(MacFullscreenControllerTest, FailExitFullscreen) { // Enter fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.EnterFullscreen(display::kInvalidDisplayId); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Start to exit fullscreen, through OnWindowWillExitFullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.ExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Fail the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); } // A simple cross-screen transition. TEST_F(MacFullscreenControllerTest, SimpleCrossScreen) { // Enter fullscreen to display 0, from display 0. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.EnterFullscreen(kDisplay1Id); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // This will trigger a call to MoveToTargetDisplayThenToggleFullscreen, even // though we are not actually moving displays. It will also then post a task // To ToggleFullscreen (because RunUntilIdle will pick up that posted task). EXPECT_CALL(mock_client_, FullscreenControllerGetFrameForDisplay(kDisplay1Id)) .Times(1) .WillOnce(Return(kDisplay1Frame)); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kDisplay1Frame, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to fullscreen on the new display. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Re-entering fullscreen on our current display should be a no-op. EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillOnce(Return(kDisplay1Id)); controller_.EnterFullscreen(kDisplay1Id); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen. This will post a task to restore bounds. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.ExitFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Let the run loop run, it will restore the bounds. EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kWindowRect, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); } // A cross-screen transition after having entered fullscreen. TEST_F(MacFullscreenControllerTest, CrossScreenFromFullscreen) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Enter fullscreen on a different display. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillRepeatedly(Return(kDisplay0Id)); controller_.EnterFullscreen(kDisplay1Id); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Execute the task posted to ToggleFullscreen. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to windowed. This will post a task to move to the // target display's frame. EXPECT_CALL(mock_client_, FullscreenControllerGetFrameForDisplay(kDisplay1Id)) .Times(1) .WillOnce(Return(kDisplay1Frame)); controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Execute the posted task to set the new frame. This will also re-toggle // fullscreen in the RunUntilIdle. EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kDisplay1Frame, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen. This will restore bounds. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.ExitFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); controller_.OnWindowDidExitFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kWindowRect, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); } // Fail a cross-screen transition when exiting fullscreen. TEST_F(MacFullscreenControllerTest, CrossScreenFromFullscreenFailExit) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Attempt to enter fullscreen on a different display. Get as far as toggling // fullscreen to get back to windowed mode. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillRepeatedly(Return(kDisplay0Id)); controller_.EnterFullscreen(kDisplay1Id); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Fail the transition back to windowed. This should just leave us as being // fullscreen. It will issue the TransitionComplete notification indicating // that the transition is over, and that we're in fullscreen mode (no mention // of which display). EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // No further tasks should run. task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); } // Fail a cross-screen transition when entering fullscreen. TEST_F(MacFullscreenControllerTest, CrossScreenFromFullscreenFailEnter) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Enter fullscreen on a different display. Get as far as toggling fullscreen // to get back to windowed mode, moving the window, and then toggling // fullscreen on the new display. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillRepeatedly(Return(kDisplay0Id)); controller_.EnterFullscreen(kDisplay1Id); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); EXPECT_CALL(mock_client_, FullscreenControllerGetFrameForDisplay(kDisplay1Id)) .Times(1) .WillOnce(Return(kDisplay1Frame)); controller_.OnWindowDidExitFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kDisplay1Frame, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Fail the transition to fullscreen mode. This will cause us to post tasks // to stay in windowed mode. controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // This will cause us to restore the window's original frame, and then declare // the transition complete, with the final state after transition as being // windowed. EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kWindowRect, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); } // Be instructed to exit fullscreen while entering fullscreen. TEST_F(MacFullscreenControllerTest, ExitWhileEntering) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); // Call ExitFullscreen inside the transition. controller_.ExitFullscreen(); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Complete the transition to fullscreen. This will report that it is still // in transition to windowed. controller_.OnWindowDidEnterFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // The above call will have posted a ToggleFullscreen task. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); // Complete the transition to windowed mode. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); controller_.OnWindowDidExitFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Nothing more should happen. task_environment_.RunUntilIdle(); } // Be instructed to enter fullscreen while exiting fullscreen. TEST_F(MacFullscreenControllerTest, EnterWhileExiting) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.OnWindowWillExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Call EnterFullscreen inside the transition. controller_.EnterFullscreen(display::kInvalidDisplayId); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to windowed mode. This will report that it is // still in transition to fullscreen. controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // The above call will have posted a ToggleFullscreen task. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to fullscreen mode. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Nothing more should happen. task_environment_.RunUntilIdle(); } // Be instructed to enter fullscreen on a different screen, while exiting // fullscreen. TEST_F(MacFullscreenControllerTest, EnterCrossScreenWhileExiting) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.OnWindowWillExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Call EnterFullscreen inside the transition. controller_.EnterFullscreen(kDisplay1Id); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to windowed mode. This will report that it is // still in transition to fullscreen. controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // The above call will have posted a MoveToTargetDisplayThenToggleFullscreen // task, which will then post a ToggleFullscreen task. EXPECT_CALL(mock_client_, FullscreenControllerGetFrameForDisplay(kDisplay1Id)) .Times(1) .WillOnce(Return(kDisplay1Frame)); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kDisplay1Frame, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to fullscreen mode. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Nothing more should happen. task_environment_.RunUntilIdle(); } // Be instructed to enter fullscreen on a different screen, while entering // fullscreen. TEST_F(MacFullscreenControllerTest, EnterCrossScreenWhileEntering) { // Enter fullscreen the way that clicking the green traffic light does it. EXPECT_CALL(mock_client_, FullscreenControllerGetFrame()) .Times(1) .WillOnce(Return(kWindowRect)); EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(true)).Times(1); controller_.OnWindowWillEnterFullscreen(); task_environment_.RunUntilIdle(); // Call EnterFullscreen inside the transition. controller_.EnterFullscreen(kDisplay1Id); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the original fullscreen transition. This will check to see if // the display we are on is the display we wanted to be on. Seeing that it // isn't, it will post a task to exit fullscreen before moving to the correct // display. EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillOnce(Return(kDisplay0Id)); controller_.OnWindowDidEnterFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // The above will have posted a task to ToggleFullscreen. EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillExitFullscreen)); task_environment_.RunUntilIdle(); // Complete the transition to windowed mode. This will once again check to see // if the display we are on is the display we wanted to be on. Seeing that it // isn't, it will move to the correct display and toggle fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerGetDisplayId()) .WillOnce(Return(kDisplay0Id)); controller_.OnWindowDidExitFullscreen(); EXPECT_CALL(mock_client_, FullscreenControllerGetFrameForDisplay(kDisplay1Id)) .Times(1) .WillOnce(Return(kDisplay1Frame)); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kDisplay1Frame, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerToggleFullscreen()) .WillOnce(Invoke(&controller_, &NativeWidgetNSWindowFullscreenController:: OnWindowWillEnterFullscreen)); task_environment_.RunUntilIdle(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Complete the transition to fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(true)) .Times(1); controller_.OnWindowDidEnterFullscreen(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_TRUE(controller_.GetTargetFullscreenState()); // Exit fullscreen. EXPECT_CALL(mock_client_, FullscreenControllerTransitionStart(false)) .Times(1); controller_.OnWindowWillExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); // Complete the transition to windowed mode. The frame frame should be reset. controller_.OnWindowDidExitFullscreen(); EXPECT_TRUE(controller_.IsInFullscreenTransition()); EXPECT_CALL(mock_client_, FullscreenControllerSetFrame(kWindowRect, true, _)) .WillOnce(FullscreenControllerSetFrameFake); EXPECT_CALL(mock_client_, FullscreenControllerTransitionComplete(false)) .Times(1); task_environment_.RunUntilIdle(); EXPECT_FALSE(controller_.IsInFullscreenTransition()); EXPECT_FALSE(controller_.GetTargetFullscreenState()); } } // namespace remote_cocoa::test
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/fullscreen_controller_unittest.cc
C++
unknown
32,245
// 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 "components/remote_cocoa/app_shim/immersive_mode_controller.h" #include "components/remote_cocoa/app_shim/immersive_mode_tabbed_controller.h" #import <Cocoa/Cocoa.h> #include <memory> #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #import "base/mac/scoped_nsobject.h" #include "components/remote_cocoa/app_shim/bridged_content_view.h" #include "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h" #import "ui/base/cocoa/window_size_constants.h" #import "ui/base/test/cocoa_helper.h" namespace { const double kBrowserHeight = 200; const double kBrowserWidth = 400; const double kOverlayViewHeight = 100; const double kOverlayViewWidth = kBrowserWidth; const double kTabOverlayViewHeight = 50; const double kTabOverlayViewWidth = kBrowserWidth; const double kTitlebarHeight = 28; } namespace remote_cocoa { class CocoaImmersiveModeControllerTest : public ui::CocoaTest { public: CocoaImmersiveModeControllerTest() = default; CocoaImmersiveModeControllerTest(const CocoaImmersiveModeControllerTest&) = delete; CocoaImmersiveModeControllerTest& operator=( const CocoaImmersiveModeControllerTest&) = delete; void SetUp() override { ui::CocoaTest::SetUp(); // Create a blank browser window. browser_.reset([[NSWindow alloc] initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]); [browser_ setFrame:NSMakeRect(0, 0, kBrowserWidth, kBrowserHeight) display:YES]; [browser_ orderBack:nil]; browser_.get().releasedWhenClosed = NO; // Create a blank overlay window. overlay_.reset([[NativeWidgetMacNSWindow alloc] initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO]); overlay_.get().releasedWhenClosed = NO; [overlay_ setFrame:NSMakeRect(0, 0, kOverlayViewWidth, kOverlayViewHeight) display:YES]; overlay_.get().contentView = [[[BridgedContentView alloc] initWithBridge:nullptr bounds:gfx::Rect()] autorelease]; [overlay_.get().contentView setFrame:NSMakeRect(0, 0, kOverlayViewWidth, kOverlayViewHeight)]; [browser_ addChildWindow:overlay_ ordered:NSWindowAbove]; EXPECT_EQ(overlay_.get().isVisible, YES); // Create a blank tab overlay window as a child of overlay window. tab_overlay_.reset([[NativeWidgetMacNSWindow alloc] initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO]); tab_overlay_.get().releasedWhenClosed = NO; [tab_overlay_ setFrame:NSMakeRect(0, 0, kTabOverlayViewWidth, kTabOverlayViewHeight) display:YES]; tab_overlay_.get().contentView = [[[BridgedContentView alloc] initWithBridge:nullptr bounds:gfx::Rect()] autorelease]; [tab_overlay_.get().contentView setFrame:NSMakeRect(0, 0, kTabOverlayViewWidth, kTabOverlayViewHeight)]; [overlay_ addChildWindow:tab_overlay_ ordered:NSWindowAbove]; EXPECT_EQ(tab_overlay_.get().isVisible, YES); } void TearDown() override { EXPECT_EQ(browser_.get().titlebarAccessoryViewControllers.count, 0u); [tab_overlay_ close]; tab_overlay_.reset(); [overlay_ close]; overlay_.reset(); [browser_ close]; browser_.reset(); ui::CocoaTest::TearDown(); } NSWindow* browser() { return browser_; } NSWindow* overlay() { return overlay_; } NSWindow* tab_overlay() { return tab_overlay_; } private: base::scoped_nsobject<NSWindow> browser_; base::scoped_nsobject<NSWindow> overlay_; base::scoped_nsobject<NSWindow> tab_overlay_; }; // Test ImmersiveModeController construction and destruction. TEST_F(CocoaImmersiveModeControllerTest, ImmersiveModeController) { bool view_will_appear_ran = false; // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeController>( browser(), overlay(), base::BindOnce( [](bool* view_will_appear_ran) { *view_will_appear_ran = true; }, &view_will_appear_ran)); immersive_mode_controller->Enable(); EXPECT_TRUE(view_will_appear_ran); EXPECT_EQ(browser().titlebarAccessoryViewControllers.count, 2u); } // Test that reveal locks work as expected. TEST_F(CocoaImmersiveModeControllerTest, RevealLock) { // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeController>( browser(), overlay(), base::DoNothing()); immersive_mode_controller->Enable(); // Autohide top chrome. immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAutohide); EXPECT_EQ( browser() .titlebarAccessoryViewControllers.firstObject.fullScreenMinHeight, 0); // Grab 3 reveal locks and make sure that top chrome is displayed. EXPECT_EQ(immersive_mode_controller->reveal_lock_count(), 0); immersive_mode_controller->RevealLock(); immersive_mode_controller->RevealLock(); immersive_mode_controller->RevealLock(); EXPECT_EQ(immersive_mode_controller->reveal_lock_count(), 3); EXPECT_EQ( browser() .titlebarAccessoryViewControllers.firstObject.fullScreenMinHeight, browser() .titlebarAccessoryViewControllers.firstObject.view.frame.size.height); // Let go of 2 reveal locks and make sure that top chrome is still displayed. immersive_mode_controller->RevealUnlock(); immersive_mode_controller->RevealUnlock(); EXPECT_EQ( browser() .titlebarAccessoryViewControllers.firstObject.fullScreenMinHeight, browser() .titlebarAccessoryViewControllers.firstObject.view.frame.size.height); // Let go of the final reveal lock and make sure top chrome is hidden. immersive_mode_controller->RevealUnlock(); EXPECT_EQ( browser() .titlebarAccessoryViewControllers.firstObject.fullScreenMinHeight, 0); } // Test ImmersiveModeController titlebar frame KVO. TEST_F(CocoaImmersiveModeControllerTest, TitlebarObserver) { // Create a fake NSToolbarFullScreenWindow and associated views. base::scoped_nsobject<NSView> titlebar_container_view([[NSView alloc] initWithFrame:NSMakeRect(0, kOverlayViewHeight, kOverlayViewWidth, kOverlayViewHeight)]); base::scoped_nsobject<NSWindow> fullscreen_window([[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, kOverlayViewWidth, kBrowserHeight) styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO]); fullscreen_window.get().releasedWhenClosed = NO; [fullscreen_window.get().contentView addSubview:titlebar_container_view]; [fullscreen_window orderBack:nil]; auto immersive_mode_controller = std::make_unique<ImmersiveModeController>( browser(), overlay(), base::DoNothing()); base::WeakPtrFactory<ImmersiveModeController> weak_ptr_factory( immersive_mode_controller.get()); // Grab the content view from the controller and add it to the test // `titlebar_container_view`. BridgedContentView* overlay_view = immersive_mode_controller->overlay_content_view(); [titlebar_container_view addSubview:overlay_view]; overlay_view.frame = NSMakeRect(0, 0, kOverlayViewWidth, kOverlayViewHeight); // Create a titlebar observer. This is the class under test. base::scoped_nsobject<ImmersiveModeTitlebarObserver> titlebar_observer( [[ImmersiveModeTitlebarObserver alloc] initWithController:weak_ptr_factory.GetWeakPtr() titlebarContainerView:titlebar_container_view]); // Observer the fake titlebar container view. [titlebar_container_view addObserver:titlebar_observer forKeyPath:@"frame" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nullptr]; // Make sure that the overlay view moves along the y axis as the titlebar // container view moves. This simulates the titlebar reveal when top chrome is // always visible. Down. for (int i = 0; i < kTitlebarHeight + 1; ++i) { [titlebar_container_view setFrame:NSMakeRect(0, kOverlayViewHeight - i, kOverlayViewWidth, kOverlayViewHeight)]; EXPECT_EQ(overlay().frame.origin.y, 100 - i); } // And back up. for (int i = 1; i <= kTitlebarHeight; ++i) { [titlebar_container_view setFrame:NSMakeRect(0, (kOverlayViewHeight - kTitlebarHeight) + i, kOverlayViewWidth, kOverlayViewHeight)]; EXPECT_EQ(overlay().frame.origin.y, (kOverlayViewHeight - kTitlebarHeight) + i); } // Clip the overlay view and make sure the overlay window moves off screen. // This simulates top chrome auto hiding. if (@available(macOS 11.0, *)) { [titlebar_container_view setFrame:NSMakeRect(0, kOverlayViewHeight + 1, kOverlayViewWidth, kOverlayViewHeight)]; EXPECT_EQ(overlay().frame.origin.y, -kOverlayViewHeight); // Remove the clip and make sure the overlay window moves back. [titlebar_container_view setFrame:NSMakeRect(0, kOverlayViewHeight, kOverlayViewWidth, kOverlayViewHeight)]; EXPECT_EQ(overlay().frame.origin.y, kOverlayViewHeight); } [titlebar_container_view removeObserver:titlebar_observer forKeyPath:@"frame"]; [fullscreen_window close]; fullscreen_window.reset(); } // Test ImmersiveModeController toolbar visibility. TEST_F(CocoaImmersiveModeControllerTest, ToolbarVisibility) { // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeTabbedController>( browser(), overlay(), tab_overlay(), base::DoNothing()); immersive_mode_controller->Enable(); // The controller will be hidden until the fullscreen transition is complete. immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAlways); EXPECT_TRUE(browser().titlebarAccessoryViewControllers.firstObject.hidden); immersive_mode_controller->FullscreenTransitionCompleted(); EXPECT_FALSE(browser().titlebarAccessoryViewControllers.firstObject.hidden); immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kNone); EXPECT_TRUE(browser().titlebarAccessoryViewControllers.firstObject.hidden); immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAutohide); EXPECT_FALSE(browser().titlebarAccessoryViewControllers.firstObject.hidden); } // Test ImmersiveModeTabbedController construction and destruction. TEST_F(CocoaImmersiveModeControllerTest, Tabbed) { bool view_will_appear_ran = false; // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeTabbedController>( browser(), overlay(), tab_overlay(), base::BindOnce( [](bool* view_will_appear_ran) { *view_will_appear_ran = true; }, &view_will_appear_ran)); immersive_mode_controller->Enable(); EXPECT_TRUE(view_will_appear_ran); // TODO(https://crbug.com/1426944): Enable() does not add the controller. It // will be added / removed from the view controller tree during // UpdateToolbarVisibility(). Remove this comment and update the test once the // bug has been resolved. EXPECT_EQ(browser().titlebarAccessoryViewControllers.count, 2u); immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAlways); EXPECT_EQ(browser().titlebarAccessoryViewControllers.count, 3u); immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kNone); EXPECT_EQ(browser().titlebarAccessoryViewControllers.count, 2u); } // Test ImmersiveModeTabbedController reveal lock tests. TEST_F(CocoaImmersiveModeControllerTest, TabbedRevealLock) { // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeTabbedController>( browser(), overlay(), tab_overlay(), base::DoNothing()); immersive_mode_controller->Enable(); immersive_mode_controller->FullscreenTransitionCompleted(); // Autohide top chrome. immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAutohide); // A visible NSToolbar will reveal the titlebar, which hosts the tab view // controller. Make sure reveal lock and unlock work as expected. EXPECT_FALSE(browser().toolbar.visible); immersive_mode_controller->RevealLock(); EXPECT_TRUE(browser().toolbar.visible); immersive_mode_controller->RevealUnlock(); EXPECT_FALSE(browser().toolbar.visible); // Make sure the visibility state doesn't change while a reveal lock is // active. immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAlways); EXPECT_TRUE(browser().toolbar.visible); immersive_mode_controller->RevealLock(); immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAutohide); EXPECT_TRUE(browser().toolbar.visible); // Make sure the visibility state updates after the last reveal lock has // been released. immersive_mode_controller->RevealUnlock(); EXPECT_FALSE(browser().toolbar.visible); } // Test ImmersiveModeTabbedController construction and destruction. TEST_F(CocoaImmersiveModeControllerTest, TabbedChildWindow) { // Controller under test. auto immersive_mode_controller = std::make_unique<ImmersiveModeTabbedController>( browser(), overlay(), tab_overlay(), base::DoNothing()); immersive_mode_controller->Enable(); immersive_mode_controller->FullscreenTransitionCompleted(); // Autohide top chrome. immersive_mode_controller->UpdateToolbarVisibility( mojom::ToolbarVisibilityStyle::kAutohide); // Create a popup. CocoaTestHelperWindow* popup = [[CocoaTestHelperWindow alloc] init]; EXPECT_EQ(immersive_mode_controller->reveal_lock_count(), 0); // Add the popup as a child of tab_overlay. [tab_overlay() addChildWindow:popup ordered:NSWindowAbove]; EXPECT_EQ(immersive_mode_controller->reveal_lock_count(), 1); // Make sure that closing the popup results in the reveal lock count // decrementing. [popup close]; EXPECT_EQ(immersive_mode_controller->reveal_lock_count(), 0); } } // namespace remote_cocoa
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/immersive_mode_controller_unittest.mm
Objective-C++
unknown
15,110
// 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_COCOA_NATIVE_WIDGET_MAC_EVENT_MONITOR_H_ #define UI_VIEWS_COCOA_NATIVE_WIDGET_MAC_EVENT_MONITOR_H_ #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "ui/views/views_export.h" namespace ui { class Event; } // namespace ui namespace views { class NativeWidgetMacNSWindowHost; // A class for event monitoring. This will create a NSEvent local monitor in // for this widget (in this process or in a remote process). The monitor will // call back through the Client interface. class VIEWS_EXPORT NativeWidgetMacEventMonitor { public: class Client { public: // Called for every observed NSEvent. If this client handles the event, // it should set `event_handled` to true. The initial value of // `event_handled` will be true if another client handled this event. virtual void NativeWidgetMacEventMonitorOnEvent(ui::Event* event, bool* event_handled) = 0; }; ~NativeWidgetMacEventMonitor(); private: friend class NativeWidgetMacNSWindowHost; explicit NativeWidgetMacEventMonitor(Client* client); const raw_ptr<Client> client_; // Scoped closure runner that will unregister `this` from its // NativeWidgetMacNSWindowHost when `this` is destroyed. base::ScopedClosureRunner remove_closure_runner_; }; } // namespace views #endif // UI_VIEWS_COCOA_NATIVE_WIDGET_MAC_EVENT_MONITOR_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_widget_mac_event_monitor.h
C++
unknown
1,610
// 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/cocoa/native_widget_mac_event_monitor.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" namespace views { NativeWidgetMacEventMonitor::NativeWidgetMacEventMonitor(Client* client) : client_(client) {} NativeWidgetMacEventMonitor::~NativeWidgetMacEventMonitor() = default; } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_widget_mac_event_monitor.mm
Objective-C++
unknown
479
// 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_COCOA_NATIVE_WIDGET_MAC_NS_WINDOW_HOST_H_ #define UI_VIEWS_COCOA_NATIVE_WIDGET_MAC_NS_WINDOW_HOST_H_ #include <list> #include <map> #include <memory> #include <string> #include <vector> #include "base/mac/scoped_nsobject.h" #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_host_helper.h" #include "components/remote_cocoa/app_shim/ns_view_ids.h" #include "components/remote_cocoa/browser/application_host.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "components/remote_cocoa/common/native_widget_ns_window.mojom.h" #include "components/remote_cocoa/common/native_widget_ns_window_host.mojom.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "ui/accelerated_widget_mac/accelerated_widget_mac.h" #include "ui/base/cocoa/accessibility_focus_overrider.h" #include "ui/compositor/layer_owner.h" #include "ui/display/mac/display_link_mac.h" #include "ui/views/cocoa/drag_drop_client_mac.h" #include "ui/views/cocoa/native_widget_mac_event_monitor.h" #include "ui/views/views_export.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_observer.h" @class NativeWidgetMacNSWindow; @class NSAccessibilityRemoteUIElement; @class NSView; namespace remote_cocoa { class NativeWidgetNSWindowBridge; class ScopedNativeWindowMapping; } // namespace remote_cocoa namespace ui { class RecyclableCompositorMac; } // namespace ui namespace views { class NativeWidgetMac; class NativeWidgetMacEventMonitor; class TextInputHost; // The portion of NativeWidgetMac that lives in the browser process. This // communicates to the NativeWidgetNSWindowBridge, which interacts with the // Cocoa APIs, and which may live in an app shim process. class VIEWS_EXPORT NativeWidgetMacNSWindowHost : public remote_cocoa::NativeWidgetNSWindowHostHelper, public remote_cocoa::ApplicationHost::Observer, public remote_cocoa::mojom::NativeWidgetNSWindowHost, public DialogObserver, public ui::AccessibilityFocusOverrider::Client, public ui::LayerDelegate, public ui::LayerOwner, public ui::AcceleratedWidgetMacNSView { public: // Retrieves the bridge host associated with the given NativeWindow. Returns // null if the supplied handle has no associated Widget. static NativeWidgetMacNSWindowHost* GetFromNativeWindow( gfx::NativeWindow window); static NativeWidgetMacNSWindowHost* GetFromNativeView(gfx::NativeView view); // Key used to bind the content NSView to the overlay widget in immersive // mode. static const char kImmersiveContentNSView[]; // Unique integer id handles are used to bridge between the // NativeWidgetMacNSWindowHost in one process and the NativeWidgetNSWindowHost // potentially in another. static NativeWidgetMacNSWindowHost* GetFromId( uint64_t bridged_native_widget_id); uint64_t bridged_native_widget_id() const { return widget_id_; } // Creates one side of the bridge. |owner| must not be NULL. explicit NativeWidgetMacNSWindowHost(NativeWidgetMac* owner); NativeWidgetMacNSWindowHost(const NativeWidgetMacNSWindowHost&) = delete; NativeWidgetMacNSWindowHost& operator=(const NativeWidgetMacNSWindowHost&) = delete; ~NativeWidgetMacNSWindowHost() override; // The NativeWidgetMac that owns |this|. views::NativeWidgetMac* native_widget_mac() const { return native_widget_mac_; } NativeWidgetMacNSWindowHost* parent() const { return parent_; } std::vector<NativeWidgetMacNSWindowHost*> children() const { return children_; } // The bridge factory that was used to create the true NSWindow for this // widget. This is nullptr for in-process windows. remote_cocoa::ApplicationHost* application_host() const { return application_host_; } TextInputHost* text_input_host() const { return text_input_host_.get(); } // A NSWindow that is guaranteed to exist in this process. If the bridge // object for this host is in this process, then this points to the bridge's // NSWindow. Otherwise, it mirrors the id and bounds of the child window. NativeWidgetMacNSWindow* GetInProcessNSWindow() const; // Return the accessibility object for the content NSView. gfx::NativeViewAccessible GetNativeViewAccessibleForNSView() const; // Return the accessibility object for the NSWindow. gfx::NativeViewAccessible GetNativeViewAccessibleForNSWindow() const; // The mojo interface through which to communicate with the underlying // NSWindow and NSView. This points to either |remote_ns_window_remote_| or // |in_process_ns_window_bridge_|. remote_cocoa::mojom::NativeWidgetNSWindow* GetNSWindowMojo() const; // Direct access to the NativeWidgetNSWindowBridge that this is hosting. // TODO(ccameron): Remove all accesses to this member, and replace them // with methods that may be sent across processes. remote_cocoa::NativeWidgetNSWindowBridge* GetInProcessNSWindowBridge() const { return in_process_ns_window_bridge_.get(); } TooltipManager* tooltip_manager() { return tooltip_manager_.get(); } DragDropClientMac* drag_drop_client() const { return drag_drop_client_.get(); } // Create and set the bridge object to be in this process. void CreateInProcessNSWindowBridge( base::scoped_nsobject<NativeWidgetMacNSWindow> window); // Create and set the bridge object to be potentially in another process. void CreateRemoteNSWindow( remote_cocoa::ApplicationHost* application_host, remote_cocoa::mojom::CreateWindowParamsPtr window_create_params); void InitWindow(const Widget::InitParams& params, const gfx::Rect& initial_bounds_in_screen); // Close the window immediately. This function may result in |this| being // deleted. void CloseWindowNow(); // Changes the bounds of the window and the hosted layer if present. The // argument is always a location in screen coordinates (in contrast to the // views::Widget::SetBounds method, when the argument is only sometimes in // screen coordinates). void SetBoundsInScreen(const gfx::Rect& bounds); // Tell the window to transition to being fullscreen or not-fullscreen. // If `fullscreen` is true, then `target_display_id` specifies the display to // which window should move (or an invalid display, to use the default). void SetFullscreen(bool fullscreen, int64_t target_display_id = display::kInvalidDisplayId); // The ultimate fullscreen state that is being targeted (irrespective of any // active transitions). bool target_fullscreen_state() const { return target_fullscreen_state_; } // Set the root view (set during initialization and un-set during teardown). void SetRootView(views::View* root_view); // Return the id through which the NSView for |root_view_| may be looked up. uint64_t GetRootViewNSViewId() const { return root_view_id_; } // Initialize the ui::Compositor and ui::Layer. void CreateCompositor(const Widget::InitParams& params); // Set the window's title, returning true if the title has changed. bool SetWindowTitle(const std::u16string& title); // Called when the owning Widget's Init method has completed. void OnWidgetInitDone(); // Redispatch a keyboard event using the widget's window's CommandDispatcher. // Return true if the event is handled. bool RedispatchKeyEvent(NSEvent* event); // Geometry of the window, in DIPs. const gfx::Rect& GetWindowBoundsInScreen() const { return window_bounds_in_screen_; } // Geometry of the content area of the window, in DIPs. Note that this is not // necessarily the same as the views::View's size. gfx::Rect GetContentBoundsInScreen() const; // The display that the window is currently on (or best guess thereof). const display::Display& GetCurrentDisplay() const { return display_; } // The restored bounds will be derived from the current NSWindow frame unless // fullscreen or transitioning between fullscreen states. gfx::Rect GetRestoredBounds() const; // An opaque blob of AppKit data which includes, among other things, a // window's workspace and fullscreen state, and can be retrieved from or // applied to a window. const std::vector<uint8_t>& GetWindowStateRestorationData() const; // Set |parent_| and update the old and new parents' |children_|. It is valid // to set |new_parent| to nullptr. Propagate this to the BridgedNativeWidget. void SetParent(NativeWidgetMacNSWindowHost* new_parent); // Properties set and queried by views. Not actually native. void SetNativeWindowProperty(const char* name, void* value); void* GetNativeWindowProperty(const char* name) const; // Updates |attached_native_view_host_views_| on // NativeViewHost::Attach()/Detach(). void OnNativeViewHostAttach(const views::View* view, NSView* native_view); void OnNativeViewHostDetach(const views::View* view); // Sorts child NSViews according to NativeViewHosts order in views hierarchy. void ReorderChildViews(); bool IsVisible() const { return is_visible_; } bool IsMiniaturized() const { return is_miniaturized_; } bool IsWindowKey() const { return is_window_key_; } bool IsMouseCaptureActive() const { return is_mouse_capture_active_; } bool IsZoomed() const { return is_zoomed_; } // Add a NSEvent local event monitor, which will send events to `client` // before they are dispatched to their ordinary target. Clients may specify // that they have handled an event, which will prevent further dispatch. All // clients will receive all events, in the order that the clients were added, // regardless of whether or not a previous client handled the event. std::unique_ptr<NativeWidgetMacEventMonitor> AddEventMonitor( NativeWidgetMacEventMonitor::Client* client); void RemoveEventMonitor(NativeWidgetMacEventMonitor*); // Used by NativeWidgetPrivate::GetGlobalCapture. static NSView* GetGlobalCaptureView(); // Notify PWA whether can GoBack/GoForward. void CanGoBack(bool can_go_back); void CanGoForward(bool can_go_forward); private: friend class TextInputHost; void UpdateCompositorProperties(); void DestroyCompositor(); // Sort |attached_native_view_host_views_| by the order in which their // NSViews should appear as subviews. This does a recursive pre-order // traversal of the views::View tree starting at |view|. void GetAttachedNativeViewHostViewsRecursive( View* view, std::vector<NSView*>* attached_native_view_host_views_ordered) const; // If we are accessing the BridgedNativeWidget through mojo, then // |in_process_ns_window_| is not the true window that is resized. This // function updates the frame of |in_process_ns_window_| to keep it in sync // for any native calls that may use it (e.g, for context menu positioning). void UpdateLocalWindowFrame(const gfx::Rect& frame); // NativeWidgetNSWindowHostHelper: id GetNativeViewAccessible() override; void DispatchKeyEvent(ui::KeyEvent* event) override; bool DispatchKeyEventToMenuController(ui::KeyEvent* event) override; void GetWordAt(const gfx::Point& location_in_content, bool* found_word, gfx::DecoratedText* decorated_word, gfx::Point* baseline_point) override; remote_cocoa::DragDropClient* GetDragDropClient() override; ui::TextInputClient* GetTextInputClient() override; bool MustPostTaskToRunModalSheetAnimation() const override; // remote_cocoa::ApplicationHost::Observer: void OnApplicationHostDestroying( remote_cocoa::ApplicationHost* host) override; // remote_cocoa::mojom::NativeWidgetNSWindowHost: void OnVisibilityChanged(bool visible) override; void OnWindowNativeThemeChanged() override; void OnViewSizeChanged(const gfx::Size& new_size) override; bool GetSheetOffsetY(int32_t* offset_y) override; void SetKeyboardAccessible(bool enabled) override; void OnIsFirstResponderChanged(bool is_first_responder) override; void OnMouseCaptureActiveChanged(bool capture_is_active) override; void OnScrollEvent(std::unique_ptr<ui::Event> event) override; void OnMouseEvent(std::unique_ptr<ui::Event> event) override; void OnGestureEvent(std::unique_ptr<ui::Event> event) override; bool DispatchKeyEventRemote(std::unique_ptr<ui::Event> event, bool* event_handled) override; bool DispatchKeyEventToMenuControllerRemote(std::unique_ptr<ui::Event> event, bool* event_swallowed, bool* event_handled) override; bool DispatchMonitorEvent(std::unique_ptr<ui::Event> event, bool* event_handled) override; bool GetHasMenuController(bool* has_menu_controller) override; bool GetIsDraggableBackgroundAt(const gfx::Point& location_in_content, bool* is_draggable_background) override; bool GetTooltipTextAt(const gfx::Point& location_in_content, std::u16string* new_tooltip_text) override; bool GetWidgetIsModal(bool* widget_is_modal) override; bool GetIsFocusedViewTextual(bool* is_textual) override; void OnWindowGeometryChanged( const gfx::Rect& window_bounds_in_screen_dips, const gfx::Rect& content_bounds_in_screen_dips) override; void OnWindowFullscreenTransitionStart(bool target_fullscreen_state) override; void OnWindowFullscreenTransitionComplete( bool target_fullscreen_state) override; void OnWindowMiniaturizedChanged(bool miniaturized) override; void OnWindowZoomedChanged(bool zoomed) override; void OnWindowDisplayChanged(const display::Display& display) override; void OnWindowWillClose() override; void OnWindowHasClosed() override; void OnWindowKeyStatusChanged(bool is_key, bool is_content_first_responder, bool full_keyboard_access_enabled) override; void OnWindowStateRestorationDataChanged( const std::vector<uint8_t>& data) override; void OnWindowParentChanged(uint64_t new_parent_id) override; void DoDialogButtonAction(ui::DialogButton button) override; bool GetDialogButtonInfo(ui::DialogButton type, bool* button_exists, std::u16string* button_label, bool* is_button_enabled, bool* is_button_default) override; bool GetDoDialogButtonsExist(bool* buttons_exist) override; bool GetShouldShowWindowTitle(bool* should_show_window_title) override; bool GetCanWindowBecomeKey(bool* can_window_become_key) override; bool GetAlwaysRenderWindowAsKey(bool* always_render_as_key) override; bool OnWindowCloseRequested(bool* can_window_close) override; bool GetWindowFrameTitlebarHeight(bool* override_titlebar_height, float* titlebar_height) override; void OnFocusWindowToolbar() override; void SetRemoteAccessibilityTokens( const std::vector<uint8_t>& window_token, const std::vector<uint8_t>& view_token) override; bool GetRootViewAccessibilityToken(int64_t* pid, std::vector<uint8_t>* token) override; bool ValidateUserInterfaceItem( int32_t command, remote_cocoa::mojom::ValidateUserInterfaceItemResultPtr* out_result) override; bool WillExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, bool* will_execute) override; bool ExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, bool* was_executed) override; bool HandleAccelerator(const ui::Accelerator& accelerator, bool require_priority_handler, bool* was_handled) override; // remote_cocoa::mojom::NativeWidgetNSWindowHost, synchronous callbacks: void GetSheetOffsetY(GetSheetOffsetYCallback callback) override; void DispatchKeyEventRemote(std::unique_ptr<ui::Event> event, DispatchKeyEventRemoteCallback callback) override; void DispatchKeyEventToMenuControllerRemote( std::unique_ptr<ui::Event> event, DispatchKeyEventToMenuControllerRemoteCallback callback) override; void DispatchMonitorEvent(std::unique_ptr<ui::Event> event, DispatchMonitorEventCallback callback) override; void GetHasMenuController(GetHasMenuControllerCallback callback) override; void GetIsDraggableBackgroundAt( const gfx::Point& location_in_content, GetIsDraggableBackgroundAtCallback callback) override; void GetTooltipTextAt(const gfx::Point& location_in_content, GetTooltipTextAtCallback callback) override; void GetWidgetIsModal(GetWidgetIsModalCallback callback) override; void GetIsFocusedViewTextual( GetIsFocusedViewTextualCallback callback) override; void GetDialogButtonInfo(ui::DialogButton button, GetDialogButtonInfoCallback callback) override; void GetDoDialogButtonsExist( GetDoDialogButtonsExistCallback callback) override; void GetShouldShowWindowTitle( GetShouldShowWindowTitleCallback callback) override; void GetCanWindowBecomeKey(GetCanWindowBecomeKeyCallback callback) override; void GetAlwaysRenderWindowAsKey( GetAlwaysRenderWindowAsKeyCallback callback) override; void OnWindowCloseRequested(OnWindowCloseRequestedCallback callback) override; void GetWindowFrameTitlebarHeight( GetWindowFrameTitlebarHeightCallback callback) override; void GetRootViewAccessibilityToken( GetRootViewAccessibilityTokenCallback callback) override; void ValidateUserInterfaceItem( int32_t command, ValidateUserInterfaceItemCallback callback) override; void WillExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) override; void ExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) override; void HandleAccelerator(const ui::Accelerator& accelerator, bool require_priority_handler, HandleAcceleratorCallback callback) override; // DialogObserver: void OnDialogChanged() override; // ui::AccessibilityFocusOverrider::Client: id GetAccessibilityFocusedUIElement() override; // ui::LayerDelegate: void OnPaintLayer(const ui::PaintContext& context) override; void OnDeviceScaleFactorChanged(float old_device_scale_factor, float new_device_scale_factor) override; void UpdateVisualState() override; // ui::AcceleratedWidgetMacNSView: void AcceleratedWidgetCALayerParamsUpdated() override; // If `display_link_` is valid and `display_link_updater_` does not exist, // create it. It will call back to OnVSyncParametersUpdated with new VSync // parameters. void RequestVSyncParametersUpdate(); void OnVSyncParametersUpdated(ui::VSyncParamsMac params); // The id that this bridge may be looked up from. const uint64_t widget_id_; const raw_ptr<views::NativeWidgetMac> native_widget_mac_; // Weak. Owns |this_|. // Structure used to look up this structure's interfaces from its // gfx::NativeWindow. std::unique_ptr<remote_cocoa::ScopedNativeWindowMapping> native_window_mapping_; // Parent and child widgets. raw_ptr<NativeWidgetMacNSWindowHost> parent_ = nullptr; std::vector<NativeWidgetMacNSWindowHost*> children_; // The factory that was used to create |remote_ns_window_remote_|. This must // be the same as |parent_->application_host_|. raw_ptr<remote_cocoa::ApplicationHost> application_host_ = nullptr; Widget::InitParams::Type widget_type_ = Widget::InitParams::TYPE_WINDOW; // The id that may be used to look up the NSView for |root_view_|. const uint64_t root_view_id_; // Weak. Owned by |native_widget_mac_|. raw_ptr<views::View> root_view_ = nullptr; std::unique_ptr<DragDropClientMac> drag_drop_client_; // The mojo remote for a BridgedNativeWidget, which may exist in another // process. mojo::AssociatedRemote<remote_cocoa::mojom::NativeWidgetNSWindow> remote_ns_window_remote_; // Remote accessibility objects corresponding to the NSWindow and its root // NSView. base::scoped_nsobject<NSAccessibilityRemoteUIElement> remote_window_accessible_; base::scoped_nsobject<NSAccessibilityRemoteUIElement> remote_view_accessible_; // Used to force the NSApplication's focused accessibility element to be the // views::Views accessibility tree when the NSView for this is focused. ui::AccessibilityFocusOverrider accessibility_focus_overrider_; // TODO(ccameron): Rather than instantiate a NativeWidgetNSWindowBridge here, // we will instantiate a mojo NativeWidgetNSWindowBridge interface to a Cocoa // instance that may be in another process. std::unique_ptr<remote_cocoa::NativeWidgetNSWindowBridge> in_process_ns_window_bridge_; // Window that is guaranteed to exist in this process (see // GetInProcessNSWindow). base::scoped_nsobject<NativeWidgetMacNSWindow> in_process_ns_window_; // Id mapping for |in_process_ns_window_|'s content NSView. std::unique_ptr<remote_cocoa::ScopedNSViewIdMapping> in_process_view_id_mapping_; std::unique_ptr<TooltipManager> tooltip_manager_; std::unique_ptr<TextInputHost> text_input_host_; std::u16string window_title_; // The display that the window is currently on. display::Display display_; // Display link for getting vsync info for `display_`, and VSyncCallbackMac to // use for callbacks. scoped_refptr<ui::DisplayLinkMac> display_link_; std::unique_ptr<ui::VSyncCallbackMac> display_link_updater_; // Updating VSync parameters can be expensive, so set this to the next time // when we should update VSync parameters. base::TimeTicks display_link_next_update_time_; // The geometry of the window and its contents view, in screen coordinates. gfx::Rect window_bounds_in_screen_; gfx::Rect content_bounds_in_screen_; std::vector<uint8_t> state_restoration_data_; bool is_visible_ = false; bool target_fullscreen_state_ = false; bool in_fullscreen_transition_ = false; bool is_miniaturized_ = false; bool is_window_key_ = false; bool is_mouse_capture_active_ = false; bool is_headless_mode_window_ = false; bool is_zoomed_ = false; gfx::Rect window_bounds_before_fullscreen_; // Weak pointers to event monitors for this widget. The event monitors // themselves will remove themselves from this list. std::list<NativeWidgetMacEventMonitor*> event_monitors_; std::unique_ptr<ui::RecyclableCompositorMac> compositor_; std::unique_ptr<remote_cocoa::ScopedCGWindowID> scoped_cg_window_id_; // Properties used by Set/GetNativeWindowProperty. std::map<std::string, void*> native_window_properties_; // Contains NativeViewHost->gfx::NativeView associations for NativeViewHosts // attached to |this|. std::map<const views::View*, NSView*> attached_native_view_host_views_; mojo::AssociatedReceiver<remote_cocoa::mojom::NativeWidgetNSWindowHost> remote_ns_window_host_receiver_{this}; base::WeakPtrFactory<NativeWidgetMacNSWindowHost> weak_factory_for_vsync_update_{this}; base::WeakPtrFactory<NativeWidgetMacNSWindowHost> weak_factory_{this}; }; } // namespace views #endif // UI_VIEWS_COCOA_NATIVE_WIDGET_MAC_NS_WINDOW_HOST_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_widget_mac_ns_window_host.h
Objective-C
unknown
24,082
// 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/cocoa/native_widget_mac_ns_window_host.h" #include <tuple> #include <utility> #include "base/base64.h" #include "base/containers/contains.h" #include "base/mac/foundation_util.h" #include "base/no_destructor.h" #include "base/numerics/safe_conversions.h" #include "base/ranges/algorithm.h" #include "base/strings/sys_string_conversions.h" #include "base/time/time.h" #include "components/remote_cocoa/app_shim/immersive_mode_controller.h" #include "components/remote_cocoa/app_shim/immersive_mode_delegate_mac.h" #include "components/remote_cocoa/app_shim/mouse_capture.h" #include "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/ns_view_ids.h" #include "components/remote_cocoa/browser/window.h" #include "mojo/public/cpp/bindings/self_owned_associated_receiver.h" #include "ui/accelerated_widget_mac/window_resize_helper_mac.h" #include "ui/base/cocoa/animation_utils.h" #include "ui/base/cocoa/nswindow_test_util.h" #include "ui/base/cocoa/remote_accessibility_api.h" #include "ui/base/cocoa/remote_layer_api.h" #include "ui/base/hit_test.h" #include "ui/base/ime/input_method.h" #include "ui/compositor/layer.h" #include "ui/compositor/recyclable_compositor_mac.h" #include "ui/display/screen.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/native_theme/native_theme_mac.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/cocoa/text_input_host.h" #include "ui/views/cocoa/tooltip_manager_mac.h" #include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_config.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/native_widget_mac.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/window/dialog_delegate.h" #include "ui/views/word_lookup_client.h" using remote_cocoa::mojom::NativeWidgetNSWindowInitParams; using remote_cocoa::mojom::WindowVisibilityState; namespace views { namespace { // Dummy implementation of the BridgedNativeWidgetHost interface. This structure // exists to work around a bug wherein synchronous mojo calls to an associated // interface can hang if the interface request is unbound. This structure is // bound to the real host's interface, and then deletes itself only once the // underlying connection closes. // https://crbug.com/915572 class BridgedNativeWidgetHostDummy : public remote_cocoa::mojom::NativeWidgetNSWindowHost { public: BridgedNativeWidgetHostDummy() = default; ~BridgedNativeWidgetHostDummy() override = default; private: void OnVisibilityChanged(bool visible) override {} void OnWindowNativeThemeChanged() override {} void OnViewSizeChanged(const gfx::Size& new_size) override {} void SetKeyboardAccessible(bool enabled) override {} void OnIsFirstResponderChanged(bool is_first_responder) override {} void OnMouseCaptureActiveChanged(bool capture_is_active) override {} void OnScrollEvent(std::unique_ptr<ui::Event> event) override {} void OnMouseEvent(std::unique_ptr<ui::Event> event) override {} void OnGestureEvent(std::unique_ptr<ui::Event> event) override {} void OnWindowGeometryChanged( const gfx::Rect& window_bounds_in_screen_dips, const gfx::Rect& content_bounds_in_screen_dips) override {} void OnWindowFullscreenTransitionStart( bool target_fullscreen_state) override {} void OnWindowFullscreenTransitionComplete(bool is_fullscreen) override {} void OnWindowMiniaturizedChanged(bool miniaturized) override {} void OnWindowZoomedChanged(bool zoomed) override {} void OnWindowDisplayChanged(const display::Display& display) override {} void OnWindowWillClose() override {} void OnWindowHasClosed() override {} void OnWindowKeyStatusChanged(bool is_key, bool is_content_first_responder, bool full_keyboard_access_enabled) override {} void OnWindowStateRestorationDataChanged( const std::vector<uint8_t>& data) override {} void OnWindowParentChanged(uint64_t new_parent_id) override {} void DoDialogButtonAction(ui::DialogButton button) override {} void OnFocusWindowToolbar() override {} void SetRemoteAccessibilityTokens( const std::vector<uint8_t>& window_token, const std::vector<uint8_t>& view_token) override {} void GetSheetOffsetY(GetSheetOffsetYCallback callback) override { float offset_y = 0; std::move(callback).Run(offset_y); } void DispatchKeyEventRemote( std::unique_ptr<ui::Event> event, DispatchKeyEventRemoteCallback callback) override { bool event_handled = false; std::move(callback).Run(event_handled); } void DispatchKeyEventToMenuControllerRemote( std::unique_ptr<ui::Event> event, DispatchKeyEventToMenuControllerRemoteCallback callback) override { ui::KeyEvent* key_event = event->AsKeyEvent(); bool event_swallowed = false; std::move(callback).Run(event_swallowed, key_event->handled()); } void DispatchMonitorEvent(std::unique_ptr<ui::Event> event, DispatchMonitorEventCallback callback) override { bool event_handled = false; std::move(callback).Run(event_handled); } void GetHasMenuController(GetHasMenuControllerCallback callback) override { bool has_menu_controller = false; std::move(callback).Run(has_menu_controller); } void GetIsDraggableBackgroundAt( const gfx::Point& location_in_content, GetIsDraggableBackgroundAtCallback callback) override { bool is_draggable_background = false; std::move(callback).Run(is_draggable_background); } void GetTooltipTextAt(const gfx::Point& location_in_content, GetTooltipTextAtCallback callback) override { std::u16string new_tooltip_text; std::move(callback).Run(new_tooltip_text); } void GetIsFocusedViewTextual( GetIsFocusedViewTextualCallback callback) override { bool is_textual = false; std::move(callback).Run(is_textual); } void GetWidgetIsModal(GetWidgetIsModalCallback callback) override { bool widget_is_modal = false; std::move(callback).Run(widget_is_modal); } void GetDialogButtonInfo(ui::DialogButton button, GetDialogButtonInfoCallback callback) override { bool exists = false; std::u16string label; bool is_enabled = false; bool is_default = false; std::move(callback).Run(exists, label, is_enabled, is_default); } void GetDoDialogButtonsExist( GetDoDialogButtonsExistCallback callback) override { bool buttons_exist = false; std::move(callback).Run(buttons_exist); } void GetShouldShowWindowTitle( GetShouldShowWindowTitleCallback callback) override { bool should_show_window_title = false; std::move(callback).Run(should_show_window_title); } void GetCanWindowBecomeKey(GetCanWindowBecomeKeyCallback callback) override { bool can_window_become_key = false; std::move(callback).Run(can_window_become_key); } void GetAlwaysRenderWindowAsKey( GetAlwaysRenderWindowAsKeyCallback callback) override { bool always_render_as_key = false; std::move(callback).Run(always_render_as_key); } void OnWindowCloseRequested( OnWindowCloseRequestedCallback callback) override { bool can_window_close = false; std::move(callback).Run(can_window_close); } void GetWindowFrameTitlebarHeight( GetWindowFrameTitlebarHeightCallback callback) override { bool override_titlebar_height = false; float titlebar_height = 0; std::move(callback).Run(override_titlebar_height, titlebar_height); } void GetRootViewAccessibilityToken( GetRootViewAccessibilityTokenCallback callback) override { std::vector<uint8_t> token; int64_t pid = 0; std::move(callback).Run(pid, token); } void ValidateUserInterfaceItem( int32_t command, ValidateUserInterfaceItemCallback callback) override { remote_cocoa::mojom::ValidateUserInterfaceItemResultPtr result; std::move(callback).Run(std::move(result)); } void WillExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) override { bool will_execute = false; std::move(callback).Run(will_execute); } void ExecuteCommand(int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) override { bool was_executed = false; std::move(callback).Run(was_executed); } void HandleAccelerator(const ui::Accelerator& accelerator, bool require_priority_handler, HandleAcceleratorCallback callback) override { bool was_handled = false; std::move(callback).Run(was_handled); } }; std::map<uint64_t, NativeWidgetMacNSWindowHost*>& GetIdToWidgetHostImplMap() { static base::NoDestructor<std::map<uint64_t, NativeWidgetMacNSWindowHost*>> id_map; return *id_map; } uint64_t g_last_bridged_native_widget_id = 0; NSWindow* OriginalHostingWindowFromFullScreenWindow( NSWindow* full_screen_window) { if ([full_screen_window.delegate conformsToProtocol:@protocol(ImmersiveModeDelegate)]) { return base::mac::ObjCCastStrict<NSObject<ImmersiveModeDelegate>>( full_screen_window.delegate) .originalHostingWindow; } return nullptr; } } // namespace // static NativeWidgetMacNSWindowHost* NativeWidgetMacNSWindowHost::GetFromNativeWindow( gfx::NativeWindow native_window) { NSWindow* window = native_window.GetNativeNSWindow(); if (NativeWidgetMacNSWindow* widget_window = base::mac::ObjCCast<NativeWidgetMacNSWindow>(window)) { return GetFromId([widget_window bridgedNativeWidgetId]); } // If the window is a system created NSToolbarFullScreenWindow we need to do // some additional work to find the original window. // TODO(mek): Figure out how to make this work with remote remote_cocoa // windows. if (remote_cocoa::IsNSToolbarFullScreenWindow(window)) { NSWindow* original = OriginalHostingWindowFromFullScreenWindow(window); if (NativeWidgetMacNSWindow* widget_window = base::mac::ObjCCast<NativeWidgetMacNSWindow>(original)) { return GetFromId([widget_window bridgedNativeWidgetId]); } } return nullptr; // Not created by NativeWidgetMac. } // static NativeWidgetMacNSWindowHost* NativeWidgetMacNSWindowHost::GetFromNativeView( gfx::NativeView native_view) { return GetFromNativeWindow([native_view.GetNativeNSView() window]); } // static const char NativeWidgetMacNSWindowHost::kImmersiveContentNSView[] = "kImmersiveContentNSView"; // static NativeWidgetMacNSWindowHost* NativeWidgetMacNSWindowHost::GetFromId( uint64_t bridged_native_widget_id) { auto found = GetIdToWidgetHostImplMap().find(bridged_native_widget_id); if (found == GetIdToWidgetHostImplMap().end()) return nullptr; return found->second; } NativeWidgetMacNSWindowHost::NativeWidgetMacNSWindowHost(NativeWidgetMac* owner) : widget_id_(++g_last_bridged_native_widget_id), native_widget_mac_(owner), root_view_id_(remote_cocoa::GetNewNSViewId()), accessibility_focus_overrider_(this), text_input_host_(new TextInputHost(this)) { DCHECK(GetIdToWidgetHostImplMap().find(widget_id_) == GetIdToWidgetHostImplMap().end()); GetIdToWidgetHostImplMap().emplace(widget_id_, this); DCHECK(owner); } NativeWidgetMacNSWindowHost::~NativeWidgetMacNSWindowHost() { DCHECK(children_.empty()); native_window_mapping_.reset(); if (application_host_) { remote_ns_window_remote_.reset(); application_host_->RemoveObserver(this); application_host_ = nullptr; } // Workaround for https://crbug.com/915572 if (remote_ns_window_host_receiver_.is_bound()) { auto receiver = remote_ns_window_host_receiver_.Unbind(); if (receiver.is_valid()) { mojo::MakeSelfOwnedAssociatedReceiver( std::make_unique<BridgedNativeWidgetHostDummy>(), std::move(receiver)); } } // Ensure that |this| cannot be reached by its id while it is being destroyed. auto found = GetIdToWidgetHostImplMap().find(widget_id_); DCHECK(found != GetIdToWidgetHostImplMap().end()); DCHECK_EQ(found->second, this); GetIdToWidgetHostImplMap().erase(found); // Destroy the bridge first to prevent any calls back into this during // destruction. // TODO(ccameron): When all communication from |bridge_| to this goes through // the BridgedNativeWidgetHost, this can be replaced with closing that pipe. in_process_ns_window_bridge_.reset(); DestroyCompositor(); } NativeWidgetMacNSWindow* NativeWidgetMacNSWindowHost::GetInProcessNSWindow() const { return in_process_ns_window_.get(); } gfx::NativeViewAccessible NativeWidgetMacNSWindowHost::GetNativeViewAccessibleForNSView() const { if (in_process_ns_window_bridge_) return in_process_ns_window_bridge_->ns_view(); return remote_view_accessible_.get(); } gfx::NativeViewAccessible NativeWidgetMacNSWindowHost::GetNativeViewAccessibleForNSWindow() const { if (in_process_ns_window_bridge_) return in_process_ns_window_bridge_->ns_window(); return remote_window_accessible_.get(); } remote_cocoa::mojom::NativeWidgetNSWindow* NativeWidgetMacNSWindowHost::GetNSWindowMojo() const { if (remote_ns_window_remote_) return remote_ns_window_remote_.get(); if (in_process_ns_window_bridge_) return in_process_ns_window_bridge_.get(); return nullptr; } void NativeWidgetMacNSWindowHost::CreateInProcessNSWindowBridge( base::scoped_nsobject<NativeWidgetMacNSWindow> window) { in_process_ns_window_ = window; in_process_ns_window_bridge_ = std::make_unique<remote_cocoa::NativeWidgetNSWindowBridge>( widget_id_, this, this, text_input_host_.get()); in_process_ns_window_bridge_->SetWindow(window); } void NativeWidgetMacNSWindowHost::CreateRemoteNSWindow( remote_cocoa::ApplicationHost* application_host, remote_cocoa::mojom::CreateWindowParamsPtr window_create_params) { accessibility_focus_overrider_.SetAppIsRemote(true); application_host_ = application_host; application_host_->AddObserver(this); // Create a local invisible window that will be used as the gfx::NativeWindow // handle to track this window in this process. { auto in_process_ns_window_create_params = remote_cocoa::mojom::CreateWindowParams::New(); in_process_ns_window_create_params->style_mask = NSWindowStyleMaskBorderless; in_process_ns_window_ = remote_cocoa::NativeWidgetNSWindowBridge::CreateNSWindow( in_process_ns_window_create_params.get()); [in_process_ns_window_ setBridgedNativeWidgetId:widget_id_]; [in_process_ns_window_ setAlphaValue:0.0]; in_process_view_id_mapping_ = std::make_unique<remote_cocoa::ScopedNSViewIdMapping>( root_view_id_, [in_process_ns_window_ contentView]); [in_process_ns_window_ enforceNeverMadeVisible]; } // Initialize |remote_ns_window_remote_| to point to a bridge created by // |factory|. mojo::PendingAssociatedRemote<remote_cocoa::mojom::TextInputHost> text_input_host_remote; text_input_host_->BindReceiver( text_input_host_remote.InitWithNewEndpointAndPassReceiver()); application_host_->GetApplication()->CreateNativeWidgetNSWindow( widget_id_, remote_ns_window_remote_.BindNewEndpointAndPassReceiver(), remote_ns_window_host_receiver_.BindNewEndpointAndPassRemote( ui::WindowResizeHelperMac::Get()->task_runner()), std::move(text_input_host_remote)); // Create the window in its process, and attach it to its parent window. GetNSWindowMojo()->CreateWindow(std::move(window_create_params)); } void NativeWidgetMacNSWindowHost::InitWindow( const Widget::InitParams& params, const gfx::Rect& initial_bounds_in_screen) { native_window_mapping_ = std::make_unique<remote_cocoa::ScopedNativeWindowMapping>( gfx::NativeWindow(in_process_ns_window_.get()), application_host_, in_process_ns_window_bridge_.get(), GetNSWindowMojo()); Widget* widget = native_widget_mac_->GetWidget(); widget_type_ = params.type; bool is_tooltip = params.type == Widget::InitParams::TYPE_TOOLTIP; if (!is_tooltip) tooltip_manager_ = std::make_unique<TooltipManagerMac>(GetNSWindowMojo()); if (params.workspace.length()) { std::string restoration_data; if (base::Base64Decode(params.workspace, &restoration_data)) { state_restoration_data_ = std::vector<uint8_t>(restoration_data.begin(), restoration_data.end()); } else { DLOG(ERROR) << "Failed to decode a window's state restoration data."; } } // Initialize the window. { auto window_params = NativeWidgetNSWindowInitParams::New(); window_params->modal_type = widget->widget_delegate()->GetModalType(); window_params->is_translucent = params.opacity == Widget::InitParams::WindowOpacity::kTranslucent; window_params->is_headless_mode_window = params.headless_mode; window_params->is_tooltip = is_tooltip; is_headless_mode_window_ = params.headless_mode; // OSX likes to put shadows on most things. However, frameless windows (with // styleMask = NSWindowStyleMaskBorderless) default to no shadow. So change // that. ShadowType::kDrop is used for Menus, which get the same shadow // style on Mac. switch (params.shadow_type) { case Widget::InitParams::ShadowType::kNone: window_params->has_window_server_shadow = false; break; case Widget::InitParams::ShadowType::kDefault: // Controls should get views shadows instead of native shadows. window_params->has_window_server_shadow = params.type != Widget::InitParams::TYPE_CONTROL; break; case Widget::InitParams::ShadowType::kDrop: window_params->has_window_server_shadow = true; break; } // No default case, to pick up new types. // Include "regular" windows without the standard frame in the window cycle. // These use NSWindowStyleMaskBorderless so do not get it by default. window_params->force_into_collection_cycle = widget_type_ == Widget::InitParams::TYPE_WINDOW && params.remove_standard_frame; window_params->state_restoration_data = state_restoration_data_; GetNSWindowMojo()->InitWindow(std::move(window_params)); } // Set a meaningful initial bounds. Note that except for frameless widgets // with no WidgetDelegate, the bounds will be set again by Widget after // initializing the non-client view. In the former case, if bounds were not // set at all, the creator of the Widget is expected to call SetBounds() // before calling Widget::Show() to avoid a kWindowSizeDeterminedLater-sized // (i.e. 1x1) window appearing. UpdateLocalWindowFrame(initial_bounds_in_screen); GetNSWindowMojo()->SetInitialBounds(initial_bounds_in_screen, widget->GetMinimumSize()); // Widgets for UI controls (usually layered above web contents) start visible. if (widget_type_ == Widget::InitParams::TYPE_CONTROL) GetNSWindowMojo()->SetVisibilityState(WindowVisibilityState::kShowInactive); } void NativeWidgetMacNSWindowHost::CloseWindowNow() { bool is_out_of_process = !in_process_ns_window_bridge_; // Note that CloseWindowNow may delete |this| for in-process windows. if (GetNSWindowMojo()) GetNSWindowMojo()->CloseWindowNow(); // If it is out-of-process, then simulate the calls that would have been // during window closure. if (is_out_of_process) { OnWindowWillClose(); while (!children_.empty()) children_.front()->CloseWindowNow(); OnWindowHasClosed(); } } void NativeWidgetMacNSWindowHost::SetBoundsInScreen(const gfx::Rect& bounds) { DCHECK(!bounds.IsEmpty() || !native_widget_mac_->GetWidget()->GetMinimumSize().IsEmpty()) << "Zero-sized windows are not supported on Mac"; UpdateLocalWindowFrame(bounds); GetNSWindowMojo()->SetBounds( bounds, native_widget_mac_->GetWidget()->GetMinimumSize()); if (remote_ns_window_remote_) { gfx::Rect window_in_screen = gfx::ScreenRectFromNSRect([in_process_ns_window_ frame]); gfx::Rect content_in_screen = gfx::ScreenRectFromNSRect([in_process_ns_window_ contentRectForFrameRect:[in_process_ns_window_ frame]]); OnWindowGeometryChanged(window_in_screen, content_in_screen); } } void NativeWidgetMacNSWindowHost::SetFullscreen(bool fullscreen, int64_t target_display_id) { // Note that when the NSWindow begins a fullscreen transition, the value of // |target_fullscreen_state_| updates via OnWindowFullscreenTransitionStart. // The update here is necessary for the case where we are currently in // transition (and therefore OnWindowFullscreenTransitionStart will not be // called until the current transition completes). target_fullscreen_state_ = fullscreen; if (target_fullscreen_state_) GetNSWindowMojo()->EnterFullscreen(target_display_id); else GetNSWindowMojo()->ExitFullscreen(); } void NativeWidgetMacNSWindowHost::SetRootView(views::View* root_view) { root_view_ = root_view; if (root_view_) { // TODO(ccameron): Drag-drop functionality does not yet run over mojo. if (in_process_ns_window_bridge_) { drag_drop_client_ = std::make_unique<DragDropClientMac>( in_process_ns_window_bridge_.get(), root_view_); } } else { drag_drop_client_.reset(); } } void NativeWidgetMacNSWindowHost::CreateCompositor( const Widget::InitParams& params) { DCHECK(!compositor_); DCHECK(!layer()); DCHECK(ViewsDelegate::GetInstance()); // "Infer" must be handled by ViewsDelegate::OnBeforeWidgetInit(). DCHECK_NE(Widget::InitParams::WindowOpacity::kInferred, params.opacity); bool translucent = params.opacity == Widget::InitParams::WindowOpacity::kTranslucent; // Create the layer. SetLayer(std::make_unique<ui::Layer>(params.layer_type)); layer()->set_delegate(this); layer()->SetFillsBoundsOpaquely(!translucent); // Create the compositor and attach the layer to it. ui::ContextFactory* context_factory = ViewsDelegate::GetInstance()->GetContextFactory(); DCHECK(context_factory); compositor_ = std::make_unique<ui::RecyclableCompositorMac>(context_factory); compositor_->widget()->SetNSView(this); compositor_->compositor()->SetBackgroundColor( translucent ? SK_ColorTRANSPARENT : SK_ColorWHITE); compositor_->compositor()->SetRootLayer(layer()); // The compositor is locked (prevented from producing frames) until the widget // is made visible unless the window was created in headless mode in which // case it will never become visible but we want its compositor to produce // frames for screenshooting and screencasting. UpdateCompositorProperties(); layer()->SetVisible(is_visible_); if (is_visible_ || is_headless_mode_window_) compositor_->Unsuspend(); // Register the CGWindowID (used to identify this window for video capture) // when it is received. Note that this is done at this moment (as opposed to // as a callback to CreateWindow) so that we can associate the CGWindowID with // the (now existing) compositor. auto lambda = [](NativeWidgetMacNSWindowHost* host, uint32_t cg_window_id) { if (!host->compositor_) return; host->scoped_cg_window_id_ = std::make_unique<remote_cocoa::ScopedCGWindowID>( cg_window_id, host->compositor_->compositor()->frame_sink_id()); }; GetNSWindowMojo()->InitCompositorView( base::BindOnce(lambda, base::Unretained(this))); } void NativeWidgetMacNSWindowHost::UpdateCompositorProperties() { if (!compositor_) return; layer()->SetBounds(gfx::Rect(content_bounds_in_screen_.size())); // Mac device scale factor is always an integer so the result here is an // integer pixel size. gfx::Size content_bounds_in_pixels = gfx::ToRoundedSize(gfx::ConvertSizeToPixels( content_bounds_in_screen_.size(), display_.device_scale_factor())); compositor_->UpdateSurface(content_bounds_in_pixels, display_.device_scale_factor(), display_.color_spaces()); } void NativeWidgetMacNSWindowHost::DestroyCompositor() { if (layer()) { // LayerOwner supports a change in ownership, e.g., to animate a closing // window, but that won't work as expected for the root layer in // NativeWidgetNSWindowBridge. DCHECK_EQ(this, layer()->owner()); layer()->CompleteAllAnimations(); } DestroyLayer(); if (!compositor_) return; compositor_->widget()->ResetNSView(); compositor_->compositor()->SetRootLayer(nullptr); compositor_.reset(); } bool NativeWidgetMacNSWindowHost::SetWindowTitle(const std::u16string& title) { if (window_title_ == title) return false; window_title_ = title; GetNSWindowMojo()->SetWindowTitle(window_title_); return true; } void NativeWidgetMacNSWindowHost::OnWidgetInitDone() { Widget* widget = native_widget_mac_->GetWidget(); if (DialogDelegate* dialog = widget->widget_delegate()->AsDialogDelegate()) dialog->AddObserver(this); } bool NativeWidgetMacNSWindowHost::RedispatchKeyEvent(NSEvent* event) { // If the target window is in-process, then redispatch the event directly, // and give an accurate return value. if (in_process_ns_window_bridge_) return in_process_ns_window_bridge_->RedispatchKeyEvent(event); // If the target window is out of process then always report the event as // handled (because it should never be handled in this process). GetNSWindowMojo()->RedispatchKeyEvent(ui::EventToData(event)); return true; } gfx::Rect NativeWidgetMacNSWindowHost::GetContentBoundsInScreen() const { return content_bounds_in_screen_; } gfx::Rect NativeWidgetMacNSWindowHost::GetRestoredBounds() const { if (target_fullscreen_state_ || in_fullscreen_transition_) return window_bounds_before_fullscreen_; return window_bounds_in_screen_; } const std::vector<uint8_t>& NativeWidgetMacNSWindowHost::GetWindowStateRestorationData() const { return state_restoration_data_; } void NativeWidgetMacNSWindowHost::SetNativeWindowProperty(const char* name, void* value) { if (value) native_window_properties_[name] = value; else native_window_properties_.erase(name); } void* NativeWidgetMacNSWindowHost::GetNativeWindowProperty( const char* name) const { auto found = native_window_properties_.find(name); if (found == native_window_properties_.end()) return nullptr; return found->second; } void NativeWidgetMacNSWindowHost::SetParent( NativeWidgetMacNSWindowHost* new_parent) { if (new_parent == parent_) return; if (parent_) { auto found = base::ranges::find(parent_->children_, this); DCHECK(found != parent_->children_.end()); parent_->children_.erase(found); parent_ = nullptr; } // We can only re-parent to another Widget if that Widget is hosted in the // same process that we were already hosted by. If this is not the case, just // close the Widget. // https://crbug.com/957927 remote_cocoa::ApplicationHost* new_application_host = new_parent ? new_parent->application_host() : application_host_.get(); if (new_application_host != application_host_) { DLOG(ERROR) << "Cannot migrate views::NativeWidget to another process, " "closing it instead."; GetNSWindowMojo()->CloseWindow(); return; } parent_ = new_parent; if (parent_) { parent_->children_.push_back(this); GetNSWindowMojo()->SetParent(parent_->bridged_native_widget_id()); } else { GetNSWindowMojo()->SetParent(0); } } void NativeWidgetMacNSWindowHost::OnNativeViewHostAttach(const View* view, NSView* native_view) { DCHECK_EQ(0u, attached_native_view_host_views_.count(view)); attached_native_view_host_views_[view] = native_view; native_widget_mac_->GetWidget()->ReorderNativeViews(); } void NativeWidgetMacNSWindowHost::OnNativeViewHostDetach(const View* view) { auto it = attached_native_view_host_views_.find(view); DCHECK(it != attached_native_view_host_views_.end()); attached_native_view_host_views_.erase(it); } void NativeWidgetMacNSWindowHost::ReorderChildViews() { Widget* widget = native_widget_mac_->GetWidget(); if (!widget->GetRootView()) return; // Get the ordering for the NSViews in |attached_native_view_host_views_|. std::vector<NSView*> attached_subviews; GetAttachedNativeViewHostViewsRecursive(widget->GetRootView(), &attached_subviews); // Convert to NSView ids that can go over mojo. If need be, create temporary // NSView ids. std::vector<uint64_t> attached_subview_ids; std::list<remote_cocoa::ScopedNSViewIdMapping> temp_ids; for (NSView* subview : attached_subviews) { uint64_t ns_view_id = remote_cocoa::GetIdFromNSView(subview); if (!ns_view_id) { // Subviews that do not already have an id will not work if the target is // in a different process. DCHECK(in_process_ns_window_bridge_); ns_view_id = remote_cocoa::GetNewNSViewId(); temp_ids.emplace_back(ns_view_id, subview); } attached_subview_ids.push_back(ns_view_id); } GetNSWindowMojo()->SortSubviews(attached_subview_ids); } void NativeWidgetMacNSWindowHost::GetAttachedNativeViewHostViewsRecursive( View* view, std::vector<NSView*>* order) const { auto found = attached_native_view_host_views_.find(view); if (found != attached_native_view_host_views_.end()) order->push_back(found->second); for (View* child : view->children()) GetAttachedNativeViewHostViewsRecursive(child, order); } void NativeWidgetMacNSWindowHost::UpdateLocalWindowFrame( const gfx::Rect& frame) { if (!remote_ns_window_remote_) return; [in_process_ns_window_ setFrame:gfx::ScreenRectToNSRect(frame) display:NO animate:NO]; } std::unique_ptr<NativeWidgetMacEventMonitor> NativeWidgetMacNSWindowHost::AddEventMonitor( NativeWidgetMacEventMonitor::Client* client) { // Enable the local event monitor if this is the first registered monitor. if (event_monitors_.empty()) GetNSWindowMojo()->SetLocalEventMonitorEnabled(true); // Add the new monitor to `event_monitors_`. auto* monitor = new NativeWidgetMacEventMonitor(client); event_monitors_.push_back(monitor); // Set up `monitor`'s remove closure to remove it from `event_monitors_`. auto remove_lambda = [](base::WeakPtr<NativeWidgetMacNSWindowHost> weak_this, NativeWidgetMacEventMonitor* monitor) { if (!weak_this) return; auto found = base::ranges::find(weak_this->event_monitors_, monitor); CHECK(found != weak_this->event_monitors_.end()); weak_this->event_monitors_.erase(found); // If this was the last monitor to be removed, disable the local // event monitor. if (weak_this->event_monitors_.empty()) weak_this->GetNSWindowMojo()->SetLocalEventMonitorEnabled(false); }; monitor->remove_closure_runner_.ReplaceClosure( base::BindOnce(remove_lambda, weak_factory_.GetWeakPtr(), monitor)); return base::WrapUnique<NativeWidgetMacEventMonitor>(monitor); } // static NSView* NativeWidgetMacNSWindowHost::GetGlobalCaptureView() { // TODO(ccameron): This will not work across process boundaries. return [remote_cocoa::CocoaMouseCapture::GetGlobalCaptureWindow() contentView]; } void NativeWidgetMacNSWindowHost::CanGoBack(bool can_go_back) { GetNSWindowMojo()->SetCanGoBack(can_go_back); } void NativeWidgetMacNSWindowHost::CanGoForward(bool can_go_forward) { GetNSWindowMojo()->SetCanGoForward(can_go_forward); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, remote_cocoa::BridgedNativeWidgetHostHelper: id NativeWidgetMacNSWindowHost::GetNativeViewAccessible() { return root_view_ ? root_view_->GetNativeViewAccessible() : nil; } void NativeWidgetMacNSWindowHost::DispatchKeyEvent(ui::KeyEvent* event) { std::ignore = root_view_->GetWidget()->GetInputMethod()->DispatchKeyEvent(event); } bool NativeWidgetMacNSWindowHost::DispatchKeyEventToMenuController( ui::KeyEvent* event) { MenuController* menu_controller = MenuController::GetActiveInstance(); if (menu_controller && root_view_ && menu_controller->owner() == root_view_->GetWidget()) { return menu_controller->OnWillDispatchKeyEvent(event) == ui::POST_DISPATCH_NONE; } return false; } remote_cocoa::DragDropClient* NativeWidgetMacNSWindowHost::GetDragDropClient() { return drag_drop_client_.get(); } ui::TextInputClient* NativeWidgetMacNSWindowHost::GetTextInputClient() { return text_input_host_->GetTextInputClient(); } bool NativeWidgetMacNSWindowHost::MustPostTaskToRunModalSheetAnimation() const { return false; } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, remote_cocoa::ApplicationHost::Observer: void NativeWidgetMacNSWindowHost::OnApplicationHostDestroying( remote_cocoa::ApplicationHost* host) { DCHECK_EQ(host, application_host_); application_host_->RemoveObserver(this); application_host_ = nullptr; // Because the process hosting this window has ended, close the window by // sending the window close messages that the bridge would have sent. OnWindowWillClose(); // Explicitly propagate this message to all children (they are also observers, // but may not be destroyed before |this| is destroyed, which would violate // tear-down assumptions). This would have been done by the bridge, had it // shut down cleanly. while (!children_.empty()) children_.front()->OnApplicationHostDestroying(host); OnWindowHasClosed(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, // remote_cocoa::mojom::NativeWidgetNSWindowHost: void NativeWidgetMacNSWindowHost::OnVisibilityChanged(bool window_visible) { is_visible_ = window_visible; if (compositor_) { layer()->SetVisible(window_visible); if (window_visible) { compositor_->Unsuspend(); layer()->SchedulePaint(layer()->bounds()); } else { compositor_->Suspend(); } } native_widget_mac_->GetWidget()->OnNativeWidgetVisibilityChanged( window_visible); } void NativeWidgetMacNSWindowHost::OnWindowNativeThemeChanged() { ui::NativeTheme::GetInstanceForNativeUi()->NotifyOnNativeThemeUpdated(); } void NativeWidgetMacNSWindowHost::OnScrollEvent( std::unique_ptr<ui::Event> event) { root_view_->GetWidget()->OnScrollEvent(event->AsScrollEvent()); } void NativeWidgetMacNSWindowHost::OnMouseEvent( std::unique_ptr<ui::Event> event) { ui::MouseEvent* mouse_event = event->AsMouseEvent(); if (scoped_cg_window_id_) { scoped_cg_window_id_->OnMouseMoved(mouse_event->location_f(), window_bounds_in_screen_.size()); } root_view_->GetWidget()->OnMouseEvent(mouse_event); // Note that |this| may be destroyed by the above call to OnMouseEvent. // https://crbug.com/1193454 } void NativeWidgetMacNSWindowHost::OnGestureEvent( std::unique_ptr<ui::Event> event) { root_view_->GetWidget()->OnGestureEvent(event->AsGestureEvent()); } bool NativeWidgetMacNSWindowHost::DispatchKeyEventRemote( std::unique_ptr<ui::Event> event, bool* event_handled) { DispatchKeyEvent(event->AsKeyEvent()); *event_handled = event->handled(); return true; } bool NativeWidgetMacNSWindowHost::DispatchKeyEventToMenuControllerRemote( std::unique_ptr<ui::Event> event, bool* event_swallowed, bool* event_handled) { *event_swallowed = DispatchKeyEventToMenuController(event->AsKeyEvent()); *event_handled = event->handled(); return true; } bool NativeWidgetMacNSWindowHost::DispatchMonitorEvent( std::unique_ptr<ui::Event> event, bool* event_handled) { // The calls to NativeWidgetMacEventMonitorOnEvent can add or remove monitors, // so take a snapshot of `event_monitors_` before making any calls. auto event_monitors_snapshot = event_monitors_; // The calls to NativeWidgetMacEventMonitorOnEvent can delete `this`. Use // `weak_this` to detect that. auto weak_this = weak_factory_.GetWeakPtr(); *event_handled = false; for (auto* event_monitor : event_monitors_snapshot) { // Ensure `event_monitor` was not removed from `event_monitors_` by a // previous call to NativeWidgetMacEventMonitorOnEvent. if (!base::Contains(event_monitors_, event_monitor)) continue; event_monitor->client_->NativeWidgetMacEventMonitorOnEvent(event.get(), event_handled); if (!weak_this) return true; } return true; } bool NativeWidgetMacNSWindowHost::GetHasMenuController( bool* has_menu_controller) { MenuController* menu_controller = MenuController::GetActiveInstance(); *has_menu_controller = menu_controller && root_view_ && menu_controller->owner() == root_view_->GetWidget() && // The editable combobox menu does not swallow keys. !menu_controller->IsEditableCombobox(); return true; } void NativeWidgetMacNSWindowHost::OnViewSizeChanged(const gfx::Size& new_size) { root_view_->SetSize(new_size); } bool NativeWidgetMacNSWindowHost::GetSheetOffsetY(int32_t* offset_y) { *offset_y = native_widget_mac_->SheetOffsetY(); return true; } void NativeWidgetMacNSWindowHost::SetKeyboardAccessible(bool enabled) { views::FocusManager* focus_manager = root_view_->GetWidget()->GetFocusManager(); if (focus_manager) focus_manager->SetKeyboardAccessible(enabled); } void NativeWidgetMacNSWindowHost::OnIsFirstResponderChanged( bool is_first_responder) { accessibility_focus_overrider_.SetViewIsFirstResponder(is_first_responder); FocusManager* focus_manager = root_view_->GetWidget()->GetFocusManager(); if (focus_manager->IsSettingFocusedView()) { // This first responder change is not initiated by the os, // but by the focus change within the browser (e.g. tab switch), // so skip setting the focus. return; } if (is_first_responder) { focus_manager->RestoreFocusedView(); } else { // Do not call ClearNativeFocus because that will re-make the // BridgedNativeWidget first responder (and this is called to indicate that // it is no longer first responder). focus_manager->StoreFocusedView(false /* clear_native_focus */); } } void NativeWidgetMacNSWindowHost::OnMouseCaptureActiveChanged(bool is_active) { DCHECK_NE(is_mouse_capture_active_, is_active); is_mouse_capture_active_ = is_active; if (!is_mouse_capture_active_) native_widget_mac_->GetWidget()->OnMouseCaptureLost(); } bool NativeWidgetMacNSWindowHost::GetIsDraggableBackgroundAt( const gfx::Point& location_in_content, bool* is_draggable_background) { int component = root_view_->GetWidget()->GetNonClientComponent(location_in_content); *is_draggable_background = component == HTCAPTION; return true; } bool NativeWidgetMacNSWindowHost::GetTooltipTextAt( const gfx::Point& location_in_content, std::u16string* new_tooltip_text) { views::View* view = root_view_->GetTooltipHandlerForPoint(location_in_content); if (view) { gfx::Point view_point = location_in_content; views::View::ConvertPointToScreen(root_view_, &view_point); views::View::ConvertPointFromScreen(view, &view_point); *new_tooltip_text = view->GetTooltipText(view_point); } return true; } void NativeWidgetMacNSWindowHost::GetWordAt( const gfx::Point& location_in_content, bool* found_word, gfx::DecoratedText* decorated_word, gfx::Point* baseline_point) { *found_word = false; views::View* target = root_view_->GetEventHandlerForPoint(location_in_content); if (!target) return; views::WordLookupClient* word_lookup_client = target->GetWordLookupClient(); if (!word_lookup_client) return; gfx::Point location_in_target = location_in_content; views::View::ConvertPointToTarget(root_view_, target, &location_in_target); if (!word_lookup_client->GetWordLookupDataAtPoint( location_in_target, decorated_word, baseline_point)) { return; } // Convert |baselinePoint| to the coordinate system of |root_view_|. views::View::ConvertPointToTarget(target, root_view_, baseline_point); *found_word = true; } bool NativeWidgetMacNSWindowHost::GetWidgetIsModal(bool* widget_is_modal) { *widget_is_modal = native_widget_mac_->GetWidget()->IsModal(); return true; } bool NativeWidgetMacNSWindowHost::GetIsFocusedViewTextual(bool* is_textual) { views::FocusManager* focus_manager = root_view_ ? root_view_->GetWidget()->GetFocusManager() : nullptr; *is_textual = focus_manager && focus_manager->GetFocusedView() && focus_manager->GetFocusedView()->GetClassName() == views::Label::kViewClassName; return true; } void NativeWidgetMacNSWindowHost::OnWindowGeometryChanged( const gfx::Rect& new_window_bounds_in_screen, const gfx::Rect& new_content_bounds_in_screen) { UpdateLocalWindowFrame(new_window_bounds_in_screen); bool window_has_moved = new_window_bounds_in_screen.origin() != window_bounds_in_screen_.origin(); bool content_has_resized = new_content_bounds_in_screen.size() != content_bounds_in_screen_.size(); window_bounds_in_screen_ = new_window_bounds_in_screen; content_bounds_in_screen_ = new_content_bounds_in_screen; // When a window grows vertically, the AppKit origin changes, but as far as // tookit-views is concerned, the window hasn't moved. Suppress these. if (window_has_moved) native_widget_mac_->GetWidget()->OnNativeWidgetMove(); // Note we can't use new_window_bounds_in_screen.size(), since it includes the // titlebar for the purposes of detecting a window move. if (content_has_resized) { native_widget_mac_->GetWidget()->OnNativeWidgetSizeChanged( content_bounds_in_screen_.size()); // Update the compositor surface and layer size. UpdateCompositorProperties(); } } void NativeWidgetMacNSWindowHost::OnWindowFullscreenTransitionStart( bool target_fullscreen_state) { target_fullscreen_state_ = target_fullscreen_state; in_fullscreen_transition_ = true; // If going into fullscreen, store an answer for GetRestoredBounds(). if (target_fullscreen_state) window_bounds_before_fullscreen_ = window_bounds_in_screen_; // Notify that fullscreen state is changing. native_widget_mac_->OnWindowFullscreenTransitionStart(); } void NativeWidgetMacNSWindowHost::OnWindowFullscreenTransitionComplete( bool actual_fullscreen_state) { in_fullscreen_transition_ = false; // Notify that fullscreen state has changed. native_widget_mac_->OnWindowFullscreenTransitionComplete(); // Ensure constraints are re-applied when completing a transition. native_widget_mac_->OnSizeConstraintsChanged(); ui::NSWindowFullscreenNotificationWaiter::NotifyFullscreenTransitionComplete( native_widget_mac_->GetNativeWindow(), actual_fullscreen_state); } void NativeWidgetMacNSWindowHost::OnWindowMiniaturizedChanged( bool miniaturized) { is_miniaturized_ = miniaturized; if (native_widget_mac_) native_widget_mac_->GetWidget()->OnNativeWidgetWindowShowStateChanged(); } void NativeWidgetMacNSWindowHost::OnWindowZoomedChanged(bool zoomed) { is_zoomed_ = zoomed; } void NativeWidgetMacNSWindowHost::OnWindowDisplayChanged( const display::Display& new_display) { bool display_id_changed = display_.id() != new_display.id(); display_ = new_display; if (compositor_) { // Mac device scale factor is always an integer so the result here is an // integer pixel size. gfx::Size content_bounds_in_pixels = gfx::ToRoundedSize(gfx::ConvertSizeToPixels( content_bounds_in_screen_.size(), display_.device_scale_factor())); compositor_->UpdateSurface(content_bounds_in_pixels, display_.device_scale_factor(), display_.color_spaces()); } if (display_id_changed) { display_link_ = ui::DisplayLinkMac::GetForDisplay( base::checked_cast<CGDirectDisplayID>(display_.id())); if (!display_link_) { // Note that on some headless systems, the display link will fail to be // created, so this should not be a fatal error. LOG(ERROR) << "Failed to create display link."; } if (compositor_) { RequestVSyncParametersUpdate(); compositor_->compositor()->SetVSyncDisplayID(display_.id()); } } } void NativeWidgetMacNSWindowHost::OnWindowWillClose() { Widget* widget = native_widget_mac_->GetWidget(); if (DialogDelegate* dialog = widget->widget_delegate()->AsDialogDelegate()) dialog->RemoveObserver(this); native_widget_mac_->WindowDestroying(); // Remove |this| from the parent's list of children. SetParent(nullptr); } void NativeWidgetMacNSWindowHost::OnWindowHasClosed() { // OnWindowHasClosed will be called only after all child windows have had // OnWindowWillClose called on them. DCHECK(children_.empty()); native_widget_mac_->WindowDestroyed(); } void NativeWidgetMacNSWindowHost::OnWindowKeyStatusChanged( bool is_key, bool is_content_first_responder, bool full_keyboard_access_enabled) { // Explicitly set the keyboard accessibility state on regaining key // window status. if (is_key && is_content_first_responder) SetKeyboardAccessible(full_keyboard_access_enabled); accessibility_focus_overrider_.SetWindowIsKey(is_key); is_window_key_ = is_key; native_widget_mac_->OnWindowKeyStatusChanged(is_key, is_content_first_responder); } void NativeWidgetMacNSWindowHost::OnWindowStateRestorationDataChanged( const std::vector<uint8_t>& data) { state_restoration_data_ = data; native_widget_mac_->GetWidget()->OnNativeWidgetWorkspaceChanged(); } void NativeWidgetMacNSWindowHost::OnWindowParentChanged( uint64_t new_parent_id) { NativeWidgetMacNSWindowHost* new_parent = GetFromId(new_parent_id); if (new_parent == parent_) { return; } if (parent_) { auto found = base::ranges::find(parent_->children_, this); CHECK(found != parent_->children_.end()); parent_->children_.erase(found); parent_ = nullptr; } parent_ = new_parent; if (parent_) { parent_->children_.push_back(this); } if (Widget* widget = native_widget_mac_->GetWidget()) { widget->OnNativeWidgetParentChanged( parent_ ? parent_->native_widget_mac()->GetNativeView() : nullptr); } } void NativeWidgetMacNSWindowHost::DoDialogButtonAction( ui::DialogButton button) { views::DialogDelegate* dialog = root_view_->GetWidget()->widget_delegate()->AsDialogDelegate(); DCHECK(dialog); if (button == ui::DIALOG_BUTTON_OK) { dialog->AcceptDialog(); } else { DCHECK_EQ(button, ui::DIALOG_BUTTON_CANCEL); dialog->CancelDialog(); } } bool NativeWidgetMacNSWindowHost::GetDialogButtonInfo( ui::DialogButton button, bool* button_exists, std::u16string* button_label, bool* is_button_enabled, bool* is_button_default) { *button_exists = false; views::DialogDelegate* dialog = root_view_->GetWidget()->widget_delegate()->AsDialogDelegate(); if (!dialog || !(dialog->GetDialogButtons() & button)) return true; *button_exists = true; *button_label = dialog->GetDialogButtonLabel(button); *is_button_enabled = dialog->IsDialogButtonEnabled(button); *is_button_default = button == dialog->GetDefaultDialogButton(); return true; } bool NativeWidgetMacNSWindowHost::GetDoDialogButtonsExist(bool* buttons_exist) { views::DialogDelegate* dialog = root_view_->GetWidget()->widget_delegate()->AsDialogDelegate(); *buttons_exist = dialog && dialog->GetDialogButtons(); return true; } bool NativeWidgetMacNSWindowHost::GetShouldShowWindowTitle( bool* should_show_window_title) { *should_show_window_title = root_view_ ? root_view_->GetWidget()->widget_delegate()->ShouldShowWindowTitle() : true; return true; } bool NativeWidgetMacNSWindowHost::GetCanWindowBecomeKey( bool* can_window_become_key) { *can_window_become_key = root_view_ ? root_view_->GetWidget()->CanActivate() : false; return true; } bool NativeWidgetMacNSWindowHost::GetAlwaysRenderWindowAsKey( bool* always_render_as_key) { *always_render_as_key = root_view_ ? root_view_->GetWidget()->ShouldPaintAsActive() : false; return true; } bool NativeWidgetMacNSWindowHost::OnWindowCloseRequested( bool* can_window_close) { *can_window_close = true; views::NonClientView* non_client_view = root_view_ ? root_view_->GetWidget()->non_client_view() : nullptr; if (non_client_view) *can_window_close = non_client_view->OnWindowCloseRequested() == CloseRequestResult::kCanClose; return true; } bool NativeWidgetMacNSWindowHost::GetWindowFrameTitlebarHeight( bool* override_titlebar_height, float* titlebar_height) { native_widget_mac_->GetWindowFrameTitlebarHeight(override_titlebar_height, titlebar_height); return true; } void NativeWidgetMacNSWindowHost::OnFocusWindowToolbar() { native_widget_mac_->OnFocusWindowToolbar(); } void NativeWidgetMacNSWindowHost::SetRemoteAccessibilityTokens( const std::vector<uint8_t>& window_token, const std::vector<uint8_t>& view_token) { remote_window_accessible_ = ui::RemoteAccessibility::GetRemoteElementFromToken(window_token); remote_view_accessible_ = ui::RemoteAccessibility::GetRemoteElementFromToken(view_token); [remote_view_accessible_ setWindowUIElement:remote_window_accessible_.get()]; [remote_view_accessible_ setTopLevelUIElement:remote_window_accessible_.get()]; } bool NativeWidgetMacNSWindowHost::GetRootViewAccessibilityToken( int64_t* pid, std::vector<uint8_t>* token) { *pid = getpid(); id element_id = GetNativeViewAccessible(); *token = ui::RemoteAccessibility::GetTokenForLocalElement(element_id); return true; } bool NativeWidgetMacNSWindowHost::ValidateUserInterfaceItem( int32_t command, remote_cocoa::mojom::ValidateUserInterfaceItemResultPtr* out_result) { *out_result = remote_cocoa::mojom::ValidateUserInterfaceItemResult::New(); native_widget_mac_->ValidateUserInterfaceItem(command, out_result->get()); return true; } bool NativeWidgetMacNSWindowHost::WillExecuteCommand( int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, bool* will_execute) { *will_execute = native_widget_mac_->WillExecuteCommand( command, window_open_disposition, is_before_first_responder); return true; } bool NativeWidgetMacNSWindowHost::ExecuteCommand( int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, bool* was_executed) { *was_executed = native_widget_mac_->ExecuteCommand( command, window_open_disposition, is_before_first_responder); return true; } bool NativeWidgetMacNSWindowHost::HandleAccelerator( const ui::Accelerator& accelerator, bool require_priority_handler, bool* was_handled) { *was_handled = false; if (Widget* widget = native_widget_mac_->GetWidget()) { if (require_priority_handler && !widget->GetFocusManager()->HasPriorityHandler(accelerator)) { return true; } *was_handled = widget->GetFocusManager()->ProcessAccelerator(accelerator); } return true; } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, // remote_cocoa::mojom::NativeWidgetNSWindowHost synchronous callbacks: void NativeWidgetMacNSWindowHost::GetSheetOffsetY( GetSheetOffsetYCallback callback) { int32_t offset_y = 0; GetSheetOffsetY(&offset_y); std::move(callback).Run(offset_y); } void NativeWidgetMacNSWindowHost::DispatchKeyEventRemote( std::unique_ptr<ui::Event> event, DispatchKeyEventRemoteCallback callback) { bool event_handled = false; DispatchKeyEventRemote(std::move(event), &event_handled); std::move(callback).Run(event_handled); } void NativeWidgetMacNSWindowHost::DispatchKeyEventToMenuControllerRemote( std::unique_ptr<ui::Event> event, DispatchKeyEventToMenuControllerRemoteCallback callback) { ui::KeyEvent* key_event = event->AsKeyEvent(); bool event_swallowed = DispatchKeyEventToMenuController(key_event); std::move(callback).Run(event_swallowed, key_event->handled()); } void NativeWidgetMacNSWindowHost::DispatchMonitorEvent( std::unique_ptr<ui::Event> event, DispatchMonitorEventCallback callback) { bool event_handled = false; DispatchMonitorEvent(std::move(event), &event_handled); std::move(callback).Run(event_handled); } void NativeWidgetMacNSWindowHost::GetHasMenuController( GetHasMenuControllerCallback callback) { bool has_menu_controller = false; GetHasMenuController(&has_menu_controller); std::move(callback).Run(has_menu_controller); } void NativeWidgetMacNSWindowHost::GetIsDraggableBackgroundAt( const gfx::Point& location_in_content, GetIsDraggableBackgroundAtCallback callback) { bool is_draggable_background = false; GetIsDraggableBackgroundAt(location_in_content, &is_draggable_background); std::move(callback).Run(is_draggable_background); } void NativeWidgetMacNSWindowHost::GetTooltipTextAt( const gfx::Point& location_in_content, GetTooltipTextAtCallback callback) { std::u16string new_tooltip_text; GetTooltipTextAt(location_in_content, &new_tooltip_text); std::move(callback).Run(new_tooltip_text); } void NativeWidgetMacNSWindowHost::GetIsFocusedViewTextual( GetIsFocusedViewTextualCallback callback) { bool is_textual = false; GetIsFocusedViewTextual(&is_textual); std::move(callback).Run(is_textual); } void NativeWidgetMacNSWindowHost::GetWidgetIsModal( GetWidgetIsModalCallback callback) { bool widget_is_modal = false; GetWidgetIsModal(&widget_is_modal); std::move(callback).Run(widget_is_modal); } void NativeWidgetMacNSWindowHost::GetDialogButtonInfo( ui::DialogButton button, GetDialogButtonInfoCallback callback) { bool exists = false; std::u16string label; bool is_enabled = false; bool is_default = false; GetDialogButtonInfo(button, &exists, &label, &is_enabled, &is_default); std::move(callback).Run(exists, label, is_enabled, is_default); } void NativeWidgetMacNSWindowHost::GetDoDialogButtonsExist( GetDoDialogButtonsExistCallback callback) { bool buttons_exist = false; GetDoDialogButtonsExist(&buttons_exist); std::move(callback).Run(buttons_exist); } void NativeWidgetMacNSWindowHost::GetShouldShowWindowTitle( GetShouldShowWindowTitleCallback callback) { bool should_show_window_title = false; GetShouldShowWindowTitle(&should_show_window_title); std::move(callback).Run(should_show_window_title); } void NativeWidgetMacNSWindowHost::GetCanWindowBecomeKey( GetCanWindowBecomeKeyCallback callback) { bool can_window_become_key = false; GetCanWindowBecomeKey(&can_window_become_key); std::move(callback).Run(can_window_become_key); } void NativeWidgetMacNSWindowHost::GetAlwaysRenderWindowAsKey( GetAlwaysRenderWindowAsKeyCallback callback) { bool always_render_as_key = false; GetAlwaysRenderWindowAsKey(&always_render_as_key); std::move(callback).Run(always_render_as_key); } void NativeWidgetMacNSWindowHost::OnWindowCloseRequested( OnWindowCloseRequestedCallback callback) { bool can_window_close = false; OnWindowCloseRequested(&can_window_close); std::move(callback).Run(can_window_close); } void NativeWidgetMacNSWindowHost::GetWindowFrameTitlebarHeight( GetWindowFrameTitlebarHeightCallback callback) { bool override_titlebar_height = false; float titlebar_height = 0; GetWindowFrameTitlebarHeight(&override_titlebar_height, &titlebar_height); std::move(callback).Run(override_titlebar_height, titlebar_height); } void NativeWidgetMacNSWindowHost::GetRootViewAccessibilityToken( GetRootViewAccessibilityTokenCallback callback) { std::vector<uint8_t> token; int64_t pid; GetRootViewAccessibilityToken(&pid, &token); std::move(callback).Run(pid, token); } void NativeWidgetMacNSWindowHost::ValidateUserInterfaceItem( int32_t command, ValidateUserInterfaceItemCallback callback) { remote_cocoa::mojom::ValidateUserInterfaceItemResultPtr result; ValidateUserInterfaceItem(command, &result); std::move(callback).Run(std::move(result)); } void NativeWidgetMacNSWindowHost::WillExecuteCommand( int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) { bool will_execute = false; WillExecuteCommand(command, window_open_disposition, is_before_first_responder, &will_execute); std::move(callback).Run(will_execute); } void NativeWidgetMacNSWindowHost::ExecuteCommand( int32_t command, WindowOpenDisposition window_open_disposition, bool is_before_first_responder, ExecuteCommandCallback callback) { bool was_executed = false; ExecuteCommand(command, window_open_disposition, is_before_first_responder, &was_executed); std::move(callback).Run(was_executed); } void NativeWidgetMacNSWindowHost::HandleAccelerator( const ui::Accelerator& accelerator, bool require_priority_handler, HandleAcceleratorCallback callback) { bool was_handled = false; HandleAccelerator(accelerator, require_priority_handler, &was_handled); std::move(callback).Run(was_handled); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, DialogObserver: void NativeWidgetMacNSWindowHost::OnDialogChanged() { // Note it's only necessary to clear the TouchBar. If the OS needs it again, // a new one will be created. GetNSWindowMojo()->ClearTouchBar(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, AccessibilityFocusOverrider::Client: id NativeWidgetMacNSWindowHost::GetAccessibilityFocusedUIElement() { return [GetNativeViewAccessible() accessibilityFocusedUIElement]; } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, LayerDelegate: void NativeWidgetMacNSWindowHost::OnPaintLayer( const ui::PaintContext& context) { native_widget_mac_->GetWidget()->OnNativeWidgetPaint(context); } void NativeWidgetMacNSWindowHost::OnDeviceScaleFactorChanged( float old_device_scale_factor, float new_device_scale_factor) { native_widget_mac_->GetWidget()->DeviceScaleFactorChanged( old_device_scale_factor, new_device_scale_factor); } void NativeWidgetMacNSWindowHost::UpdateVisualState() { native_widget_mac_->GetWidget()->LayoutRootViewIfNecessary(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMacNSWindowHost, AcceleratedWidgetMac: void NativeWidgetMacNSWindowHost::AcceleratedWidgetCALayerParamsUpdated() { if (const auto* ca_layer_params = compositor_->widget()->GetCALayerParams()) GetNSWindowMojo()->SetCALayerParams(*ca_layer_params); // The VSync parameters skew over time (astonishingly quickly -- 0.1 msec per // second). If too much time has elapsed since the last time the vsync // parameters were calculated, re-calculate them. if (base::TimeTicks::Now() >= display_link_next_update_time_) { RequestVSyncParametersUpdate(); } } void NativeWidgetMacNSWindowHost::RequestVSyncParametersUpdate() { if (!display_link_ || display_link_updater_) { return; } display_link_updater_ = display_link_->RegisterCallback(base::BindRepeating( &NativeWidgetMacNSWindowHost::OnVSyncParametersUpdated, weak_factory_for_vsync_update_.GetWeakPtr())); } void NativeWidgetMacNSWindowHost::OnVSyncParametersUpdated( ui::VSyncParamsMac params) { if (compositor_ && params.display_times_valid) { compositor_->compositor()->SetDisplayVSyncParameters( params.display_timebase, params.display_interval); display_link_next_update_time_ = base::TimeTicks::Now() + base::Seconds(10); } display_link_updater_ = nullptr; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_widget_mac_ns_window_host.mm
Objective-C++
unknown
61,537
// 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_COCOA_NATIVE_WINDOW_TRACKER_COCOA_H_ #define UI_VIEWS_COCOA_NATIVE_WINDOW_TRACKER_COCOA_H_ #include "base/mac/scoped_nsobject.h" #include "ui/views/native_window_tracker.h" #include "ui/views/views_export.h" @class BridgedNativeWindowTracker; namespace views { class VIEWS_EXPORT NativeWindowTrackerCocoa : public NativeWindowTracker { public: explicit NativeWindowTrackerCocoa(gfx::NativeWindow window); NativeWindowTrackerCocoa(const NativeWindowTrackerCocoa&) = delete; NativeWindowTrackerCocoa& operator=(const NativeWindowTrackerCocoa&) = delete; ~NativeWindowTrackerCocoa() override; // NativeWindowTracker: bool WasNativeWindowDestroyed() const override; private: base::scoped_nsobject<BridgedNativeWindowTracker> bridge_; }; } // namespace views #endif // UI_VIEWS_COCOA_NATIVE_WINDOW_TRACKER_COCOA_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_window_tracker_cocoa.h
Objective-C
unknown
999
// 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/cocoa/native_window_tracker_cocoa.h" #import <AppKit/AppKit.h> #include <memory> @interface BridgedNativeWindowTracker : NSObject { @private NSWindow* _window; } - (instancetype)initWithNSWindow:(NSWindow*)window; - (bool)wasNSWindowClosed; - (void)onWindowWillClose:(NSNotification*)notification; @end @implementation BridgedNativeWindowTracker - (instancetype)initWithNSWindow:(NSWindow*)window { _window = window; NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(onWindowWillClose:) name:NSWindowWillCloseNotification object:_window]; return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } - (bool)wasNSWindowClosed { return _window == nil; } - (void)onWindowWillClose:(NSNotification*)notification { [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_window]; _window = nil; } @end namespace views { NativeWindowTrackerCocoa::NativeWindowTrackerCocoa( gfx::NativeWindow native_window) { NSWindow* window = native_window.GetNativeNSWindow(); bridge_.reset([[BridgedNativeWindowTracker alloc] initWithNSWindow:window]); } NativeWindowTrackerCocoa::~NativeWindowTrackerCocoa() {} bool NativeWindowTrackerCocoa::WasNativeWindowDestroyed() const { return [bridge_ wasNSWindowClosed]; } // static std::unique_ptr<NativeWindowTracker> NativeWindowTracker::Create( gfx::NativeWindow window) { return std::make_unique<NativeWindowTrackerCocoa>(window); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/native_window_tracker_cocoa.mm
Objective-C++
unknown
1,841
// 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_COCOA_TEXT_INPUT_HOST_H_ #define UI_VIEWS_COCOA_TEXT_INPUT_HOST_H_ #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/common/text_input_host.mojom.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "ui/views/views_export.h" namespace ui { class TextInputClient; } // namespace ui namespace views { class NativeWidgetMacNSWindowHost; class VIEWS_EXPORT TextInputHost : public remote_cocoa::mojom::TextInputHost { public: explicit TextInputHost(NativeWidgetMacNSWindowHost* host_impl); TextInputHost(const TextInputHost&) = delete; TextInputHost& operator=(const TextInputHost&) = delete; ~TextInputHost() override; void BindReceiver( mojo::PendingAssociatedReceiver<remote_cocoa::mojom::TextInputHost> receiver); // Set the current TextInputClient. void SetTextInputClient(ui::TextInputClient* new_text_input_client); // Return a pointer to the host's ui::TextInputClient. // TODO(ccameron): Remove the need for this call. ui::TextInputClient* GetTextInputClient() const; private: // remote_cocoa::mojom::TextInputHost: bool HasClient(bool* out_has_client) override; bool HasInputContext(bool* out_has_input_context) override; bool IsRTL(bool* out_is_rtl) override; bool GetSelectionRange(gfx::Range* out_range) override; bool GetSelectionText(bool* out_result, std::u16string* out_text) override; void InsertText(const std::u16string& text, bool as_character) override; void DeleteRange(const gfx::Range& range) override; void SetCompositionText(const std::u16string& text, const gfx::Range& selected_range, const gfx::Range& replacement_range) override; void ConfirmCompositionText() override; bool HasCompositionText(bool* out_has_composition_text) override; bool GetCompositionTextRange(gfx::Range* out_composition_range) override; bool GetAttributedSubstringForRange(const gfx::Range& requested_range, std::u16string* out_text, gfx::Range* out_actual_range) override; bool GetFirstRectForRange(const gfx::Range& requested_range, gfx::Rect* out_rect, gfx::Range* out_actual_range) override; // remote_cocoa::mojom::TextInputHost synchronous methods: void HasClient(HasClientCallback callback) override; void HasInputContext(HasInputContextCallback callback) override; void IsRTL(IsRTLCallback callback) override; void GetSelectionRange(GetSelectionRangeCallback callback) override; void GetSelectionText(GetSelectionTextCallback callback) override; void HasCompositionText(HasCompositionTextCallback callback) override; void GetCompositionTextRange( GetCompositionTextRangeCallback callback) override; void GetAttributedSubstringForRange( const gfx::Range& requested_range, GetAttributedSubstringForRangeCallback callback) override; void GetFirstRectForRange(const gfx::Range& requested_range, GetFirstRectForRangeCallback callback) override; // Weak. If non-null the TextInputClient of the currently focused views::View // in the hierarchy rooted at the root view of |host_impl_|. Owned by the // focused views::View. raw_ptr<ui::TextInputClient> text_input_client_ = nullptr; // The TextInputClient about to be set. Requests for a new -inputContext will // use this, but while the input is changing the NSView still needs to service // IME requests using the old |text_input_client_|. raw_ptr<ui::TextInputClient> pending_text_input_client_ = nullptr; const raw_ptr<NativeWidgetMacNSWindowHost> host_impl_; mojo::AssociatedReceiver<remote_cocoa::mojom::TextInputHost> mojo_receiver_{ this}; }; } // namespace views #endif // UI_VIEWS_COCOA_TEXT_INPUT_HOST_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/text_input_host.h
C++
unknown
4,088
// 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/cocoa/text_input_host.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "ui/accelerated_widget_mac/window_resize_helper_mac.h" #include "ui/base/ime/text_input_client.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" namespace { // Returns the boundary rectangle for composition characters in the // |requested_range|. Sets |actual_range| corresponding to the returned // rectangle. For cases, where there is no composition text or the // |requested_range| lies outside the composition range, a zero width rectangle // corresponding to the caret bounds is returned. Logic used is similar to // RenderWidgetHostViewMac::GetCachedFirstRectForCharacterRange(...). gfx::Rect GetFirstRectForRangeHelper(const ui::TextInputClient* client, const gfx::Range& requested_range, gfx::Range* actual_range) { // NSRange doesn't support reversed ranges. DCHECK(!requested_range.is_reversed()); DCHECK(actual_range); // Set up default return values, to be returned in case of unusual cases. gfx::Rect default_rect; *actual_range = gfx::Range::InvalidRange(); if (!client) return default_rect; default_rect = client->GetCaretBounds(); default_rect.set_width(0); // If possible, modify actual_range to correspond to caret position. gfx::Range selection_range; if (client->GetEditableSelectionRange(&selection_range)) { // Caret bounds correspond to end index of selection_range. *actual_range = gfx::Range(selection_range.end()); } gfx::Range composition_range; if (!client->HasCompositionText() || !client->GetCompositionTextRange(&composition_range) || !requested_range.IsBoundedBy(composition_range)) { return default_rect; } DCHECK(!composition_range.is_reversed()); const size_t from = requested_range.start() - composition_range.start(); const size_t to = requested_range.end() - composition_range.start(); // Pick the first character's bounds as the initial rectangle, then grow it to // the full |requested_range| if possible. const bool request_is_composition_end = from == composition_range.length(); const size_t first_index = request_is_composition_end ? from - 1 : from; gfx::Rect union_rect; if (!client->GetCompositionCharacterBounds(first_index, &union_rect)) return default_rect; // If requested_range is empty, return a zero width rectangle corresponding to // it. if (from == to) { if (request_is_composition_end && client->GetTextDirection() != base::i18n::RIGHT_TO_LEFT) { // In case of an empty requested range at end of composition, return the // rectangle to the right of the last compositioned character. union_rect.set_origin(union_rect.top_right()); } union_rect.set_width(0); *actual_range = requested_range; return union_rect; } // Toolkit-views textfields are always single-line, so no need to check for // line breaks. for (size_t i = from + 1; i < to; i++) { gfx::Rect current_rect; if (client->GetCompositionCharacterBounds(i, &current_rect)) { union_rect.Union(current_rect); } else { *actual_range = gfx::Range(requested_range.start(), i + composition_range.start()); return union_rect; } } *actual_range = requested_range; return union_rect; } // Returns the string corresponding to |requested_range| for the given |client|. // If a gfx::Range::InvalidRange() is passed, the full string stored by |client| // is returned. Sets |actual_range| corresponding to the returned string. std::u16string AttributedSubstringForRangeHelper( const ui::TextInputClient* client, const gfx::Range& requested_range, gfx::Range* actual_range) { // NSRange doesn't support reversed ranges. DCHECK(!requested_range.is_reversed()); DCHECK(actual_range); std::u16string substring; gfx::Range text_range; *actual_range = gfx::Range::InvalidRange(); if (!client || !client->GetTextRange(&text_range)) return substring; // gfx::Range::Intersect() behaves a bit weirdly. If B is an empty range // contained inside a non-empty range A, B intersection A returns // gfx::Range::InvalidRange(), instead of returning B. *actual_range = text_range.Contains(requested_range) ? requested_range : text_range.Intersect(requested_range); // This is a special case for which the complete string should should be // returned. NSTextView also follows this, though the same is not mentioned in // NSTextInputClient documentation. if (!requested_range.IsValid()) *actual_range = text_range; client->GetTextFromRange(*actual_range, &substring); return substring; } } // namespace namespace views { //////////////////////////////////////////////////////////////////////////////// // TextInputHost, public: TextInputHost::TextInputHost(NativeWidgetMacNSWindowHost* host_impl) : host_impl_(host_impl) {} TextInputHost::~TextInputHost() = default; void TextInputHost::BindReceiver( mojo::PendingAssociatedReceiver<remote_cocoa::mojom::TextInputHost> receiver) { mojo_receiver_.Bind(std::move(receiver), ui::WindowResizeHelperMac::Get()->task_runner()); } ui::TextInputClient* TextInputHost::GetTextInputClient() const { return text_input_client_; } void TextInputHost::SetTextInputClient( ui::TextInputClient* new_text_input_client) { if (pending_text_input_client_ == new_text_input_client) return; // This method may cause the IME window to dismiss, which may cause it to // insert text (e.g. to replace marked text with "real" text). That should // happen in the old -inputContext (which AppKit stores a reference to). // Unfortunately, the only way to invalidate the the old -inputContext is to // invoke -[NSApp updateWindows], which also wants a reference to the _new_ // -inputContext. So put the new inputContext in |pendingTextInputClient_| and // only use it for -inputContext. ui::TextInputClient* old_text_input_client = text_input_client_; // Since dismissing an IME may insert text, a misbehaving IME or a // ui::TextInputClient that acts on InsertChar() to change focus a second time // may invoke -setTextInputClient: recursively; with [NSApp updateWindows] // still on the stack. Calling [NSApp updateWindows] recursively may upset // an IME. Since the rest of this method is only to decide whether to call // updateWindows, and we're already calling it, just bail out. if (text_input_client_ != pending_text_input_client_) { pending_text_input_client_ = new_text_input_client; return; } // Start by assuming no need to invoke -updateWindows. text_input_client_ = new_text_input_client; pending_text_input_client_ = new_text_input_client; if (host_impl_->in_process_ns_window_bridge_ && host_impl_->in_process_ns_window_bridge_->NeedsUpdateWindows()) { text_input_client_ = old_text_input_client; [NSApp updateWindows]; // Note: |pending_text_input_client_| (and therefore +[NSTextInputContext // currentInputContext] may have changed if called recursively. text_input_client_ = pending_text_input_client_; } } //////////////////////////////////////////////////////////////////////////////// // TextInputHost, remote_cocoa::mojom::TextInputHost: bool TextInputHost::HasClient(bool* out_has_client) { *out_has_client = text_input_client_ != nullptr; return true; } bool TextInputHost::HasInputContext(bool* out_has_input_context) { *out_has_input_context = false; // If the textInputClient_ does not exist, return nil since this view does not // conform to NSTextInputClient protocol. if (!pending_text_input_client_) return true; // If a menu is active, and -[NSView interpretKeyEvents:] asks for the // input context, return nil. This ensures the action message is sent to // the view, rather than any NSTextInputClient a subview has installed. bool has_menu_controller = false; host_impl_->GetHasMenuController(&has_menu_controller); if (has_menu_controller) return true; // When not in an editable mode, or while entering passwords // (http://crbug.com/23219), we don't want to show IME candidate windows. // Returning nil prevents this view from getting messages defined as part of // the NSTextInputClient protocol. switch (pending_text_input_client_->GetTextInputType()) { case ui::TEXT_INPUT_TYPE_NONE: case ui::TEXT_INPUT_TYPE_PASSWORD: return true; default: *out_has_input_context = true; } return true; } bool TextInputHost::IsRTL(bool* out_is_rtl) { *out_is_rtl = text_input_client_ && text_input_client_->GetTextDirection() == base::i18n::RIGHT_TO_LEFT; return true; } bool TextInputHost::GetSelectionRange(gfx::Range* out_range) { if (!text_input_client_ || !text_input_client_->GetEditableSelectionRange(out_range)) { *out_range = gfx::Range::InvalidRange(); } return true; } bool TextInputHost::GetSelectionText(bool* out_result, std::u16string* out_text) { *out_result = false; if (!text_input_client_) return true; gfx::Range selection_range; if (!text_input_client_->GetEditableSelectionRange(&selection_range)) return true; *out_result = text_input_client_->GetTextFromRange(selection_range, out_text); return true; } void TextInputHost::InsertText(const std::u16string& text, bool as_character) { if (!text_input_client_) return; if (as_character) { // If a single character is inserted by keyDown's call to // interpretKeyEvents: then use InsertChar() to allow editing events to be // merged. We use ui::VKEY_UNKNOWN as the key code since it's not feasible // to determine the correct key code for each unicode character. Also a // correct keycode is not needed in the current context. Send ui::EF_NONE as // the key modifier since |text| already accounts for the pressed key // modifiers. text_input_client_->InsertChar(ui::KeyEvent( text[0], ui::VKEY_UNKNOWN, ui::DomCode::NONE, ui::EF_NONE)); } else { text_input_client_->InsertText( text, ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); } } void TextInputHost::DeleteRange(const gfx::Range& range) { if (!text_input_client_) return; text_input_client_->DeleteRange(range); } void TextInputHost::SetCompositionText(const std::u16string& text, const gfx::Range& selected_range, const gfx::Range& replacement_range) { if (!text_input_client_) return; text_input_client_->DeleteRange(replacement_range); ui::CompositionText composition; composition.text = text; composition.selection = selected_range; // Add an underline with text color and a transparent background to the // composition text. TODO(karandeepb): On Cocoa textfields, the target clause // of the composition has a thick underlines. The composition text also has // discontinuous underlines for different clauses. This is also supported in // the Chrome renderer. Add code to extract underlines from |text| once our // render text implementation supports thick underlines and discontinuous // underlines for consecutive characters. See http://crbug.com/612675. composition.ime_text_spans.emplace_back( ui::ImeTextSpan::Type::kComposition, 0, text.length(), ui::ImeTextSpan::Thickness::kThin, ui::ImeTextSpan::UnderlineStyle::kSolid, SK_ColorTRANSPARENT); text_input_client_->SetCompositionText(composition); } void TextInputHost::ConfirmCompositionText() { if (!text_input_client_) return; text_input_client_->ConfirmCompositionText(/* keep_selection */ false); } bool TextInputHost::HasCompositionText(bool* out_has_composition_text) { *out_has_composition_text = false; if (!text_input_client_) return true; *out_has_composition_text = text_input_client_->HasCompositionText(); return true; } bool TextInputHost::GetCompositionTextRange(gfx::Range* out_composition_range) { *out_composition_range = gfx::Range::InvalidRange(); if (!text_input_client_) return true; if (!text_input_client_->HasCompositionText()) return true; text_input_client_->GetCompositionTextRange(out_composition_range); return true; } bool TextInputHost::GetAttributedSubstringForRange( const gfx::Range& requested_range, std::u16string* out_text, gfx::Range* out_actual_range) { *out_text = AttributedSubstringForRangeHelper( text_input_client_, requested_range, out_actual_range); return true; } bool TextInputHost::GetFirstRectForRange(const gfx::Range& requested_range, gfx::Rect* out_rect, gfx::Range* out_actual_range) { *out_rect = GetFirstRectForRangeHelper(text_input_client_, requested_range, out_actual_range); return true; } //////////////////////////////////////////////////////////////////////////////// // TextInputHost, remote_cocoa::mojom::TextInputHost synchronous methods: void TextInputHost::HasClient(HasClientCallback callback) { bool has_client = false; HasClient(&has_client); std::move(callback).Run(has_client); } void TextInputHost::HasInputContext(HasInputContextCallback callback) { bool has_input_context = false; HasClient(&has_input_context); std::move(callback).Run(has_input_context); } void TextInputHost::IsRTL(IsRTLCallback callback) { bool is_rtl = false; IsRTL(&is_rtl); std::move(callback).Run(is_rtl); } void TextInputHost::GetSelectionRange(GetSelectionRangeCallback callback) { gfx::Range range = gfx::Range::InvalidRange(); GetSelectionRange(&range); std::move(callback).Run(range); } void TextInputHost::GetSelectionText(GetSelectionTextCallback callback) { bool result = false; std::u16string text; GetSelectionText(&result, &text); std::move(callback).Run(result, text); } void TextInputHost::HasCompositionText(HasCompositionTextCallback callback) { bool has_composition_text = false; HasCompositionText(&has_composition_text); std::move(callback).Run(has_composition_text); } void TextInputHost::GetCompositionTextRange( GetCompositionTextRangeCallback callback) { gfx::Range range = gfx::Range::InvalidRange(); GetCompositionTextRange(&range); std::move(callback).Run(range); } void TextInputHost::GetAttributedSubstringForRange( const gfx::Range& requested_range, GetAttributedSubstringForRangeCallback callback) { std::u16string text; gfx::Range actual_range = gfx::Range::InvalidRange(); GetAttributedSubstringForRange(requested_range, &text, &actual_range); std::move(callback).Run(text, actual_range); } void TextInputHost::GetFirstRectForRange( const gfx::Range& requested_range, GetFirstRectForRangeCallback callback) { gfx::Rect rect; gfx::Range actual_range; GetFirstRectForRange(requested_range, &rect, &actual_range); std::move(callback).Run(rect, actual_range); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/text_input_host.mm
Objective-C++
unknown
15,448
// 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. #ifndef UI_VIEWS_COCOA_TOOLTIP_MANAGER_MAC_H_ #define UI_VIEWS_COCOA_TOOLTIP_MANAGER_MAC_H_ #include "base/memory/raw_ptr.h" #include "ui/views/widget/tooltip_manager.h" namespace remote_cocoa::mojom { class NativeWidgetNSWindow; } // namespace remote_cocoa::mojom namespace views { // Manages native Cocoa tooltips for the given NativeWidgetNSWindowHostImpl. class TooltipManagerMac : public TooltipManager { public: explicit TooltipManagerMac(remote_cocoa::mojom::NativeWidgetNSWindow* bridge); TooltipManagerMac(const TooltipManagerMac&) = delete; TooltipManagerMac& operator=(const TooltipManagerMac&) = delete; ~TooltipManagerMac() override; // TooltipManager: int GetMaxWidth(const gfx::Point& location) const override; const gfx::FontList& GetFontList() const override; void UpdateTooltip() override; void TooltipTextChanged(View* view) override; private: raw_ptr<remote_cocoa::mojom::NativeWidgetNSWindow, DanglingUntriaged> bridge_; // Weak. Owned by the owner of this. }; } // namespace views #endif // UI_VIEWS_COCOA_TOOLTIP_MANAGER_MAC_H_
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/tooltip_manager_mac.h
C++
unknown
1,237
// 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/cocoa/tooltip_manager_mac.h" #include "base/no_destructor.h" #import "components/remote_cocoa/app_shim/bridged_content_view.h" #import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "ui/base/cocoa/cocoa_base_utils.h" #include "ui/gfx/font_list.h" #import "ui/gfx/mac/coordinate_conversion.h" #include "ui/gfx/platform_font_mac.h" namespace { // Max visual tooltip width in DIPs. Beyond this, Cocoa will wrap text. const int kTooltipMaxWidthPixels = 250; } // namespace namespace views { TooltipManagerMac::TooltipManagerMac( remote_cocoa::mojom::NativeWidgetNSWindow* bridge) : bridge_(bridge) {} TooltipManagerMac::~TooltipManagerMac() = default; int TooltipManagerMac::GetMaxWidth(const gfx::Point& location) const { return kTooltipMaxWidthPixels; } const gfx::FontList& TooltipManagerMac::GetFontList() const { static base::NoDestructor<gfx::FontList> font_list([]() { return gfx::Font(new gfx::PlatformFontMac( gfx::PlatformFontMac::SystemFontType::kToolTip)); }()); return *font_list; } void TooltipManagerMac::UpdateTooltip() { bridge_->UpdateTooltip(); } void TooltipManagerMac::TooltipTextChanged(View* view) { // The intensive part is View::GetTooltipHandlerForPoint(), which will be done // in [BridgedContentView updateTooltipIfRequiredAt:]. Don't do it here as // well. UpdateTooltip(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/cocoa/tooltip_manager_mac.mm
Objective-C++
unknown
1,567
// 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_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_ #define UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_ #include "third_party/skia/include/core/SkColor.h" #include "ui/views/views_export.h" namespace views { // An interface implemented by a Listener object wishing to know about the // the results from the color chooser dialog. class VIEWS_EXPORT ColorChooserListener { public: virtual void OnColorChosen(SkColor color) = 0; virtual void OnColorChooserDialogClosed() = 0; protected: virtual ~ColorChooserListener() = default; }; } // namespace views #endif // UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_
Zhao-PengFei35/chromium_src_4
ui/views/color_chooser/color_chooser_listener.h
C++
unknown
780
// 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. // // Very quick HSV primer for those unfamiliar with it: // It helps to think of HSV like this: // h is in (0,360) and draws a circle of colors, with r = 0, b = 120, g = 240 // s is in (0,1) and is the distance from the center of that circle - higher // values are more intense, with s = 0 being white, s = 1 being full color // and then HSV is the 3d space caused by projecting that circle into a // cylinder, with v in (0,1) being how far along the cylinder you are; v = 0 is // black, v = 1 is full color intensity #include <tuple> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/test/event_generator.h" #include "ui/views/background.h" #include "ui/views/color_chooser/color_chooser_listener.h" #include "ui/views/color_chooser/color_chooser_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_utils.h" namespace { class TestChooserListener : public views::ColorChooserListener { public: void OnColorChosen(SkColor color) override { color_ = color; } void OnColorChooserDialogClosed() override { closed_ = true; } private: SkColor color_ = SK_ColorTRANSPARENT; bool closed_ = false; }; class ColorChooserTest : public views::ViewsTestBase { public: ~ColorChooserTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); chooser_ = std::make_unique<views::ColorChooser>(&listener_, SK_ColorGREEN); // Icky: we can't use our own WidgetDelegate for CreateTestWidget, but we // want to follow the production code path here regardless, so we create our // own delegate, pull the contents view out of it, and stick it into the // test widget. In production Views would handle that step itself. auto delegate = chooser_->MakeWidgetDelegate(); auto* view = delegate->TransferOwnershipOfContentsView(); view->SetBounds(0, 0, 400, 300); widget_ = CreateTestWidget(views::Widget::InitParams::TYPE_WINDOW); widget_->GetContentsView()->AddChildView(std::move(view)); generator_ = std::make_unique<ui::test::EventGenerator>( views::GetRootWindow(widget_.get()), widget_->GetNativeWindow()); } void TearDown() override { generator_.reset(); widget_.reset(); ViewsTestBase::TearDown(); } views::ColorChooser* chooser() { return chooser_.get(); } ui::test::EventGenerator* generator() { return generator_.get(); } void ExpectExactHSV(float h, float s, float v) const { EXPECT_EQ(h, chooser_->hue()); EXPECT_EQ(s, chooser_->saturation()); EXPECT_EQ(v, chooser_->value()); } void ExpectApproximateHSV(float h, float s, float v) const { // At the usual size of the hue chooser it's possible to hit within // roughly 5 points of hue in either direction. EXPECT_NEAR(chooser_->hue(), h, 10.0); EXPECT_NEAR(chooser_->saturation(), s, 0.1); EXPECT_NEAR(chooser_->value(), v, 0.1); } SkColor GetShownColor() const { return chooser_->selected_color_patch_for_testing() ->background() ->get_color(); } SkColor GetTextualColor() const { std::u16string text = chooser_->textfield_for_testing()->GetText(); if (text.empty() || text[0] != '#') return SK_ColorTRANSPARENT; uint32_t color; return base::HexStringToUInt(base::UTF16ToUTF8(text.substr(1)), &color) ? SkColorSetA(color, SK_AlphaOPAQUE) : SK_ColorTRANSPARENT; } void TypeColor(const std::string& color) { chooser_->textfield_for_testing()->SetText(base::UTF8ToUTF16(color)); // Synthesize ContentsChanged, since Textfield normally doesn't deliver it // for SetText, only for user-typed text. chooser_->ContentsChanged(chooser_->textfield_for_testing(), chooser_->textfield_for_testing()->GetText()); } void PressMouseAt(views::View* view, const gfx::Point& p) { #if 0 // TODO(ellyjones): Why doesn't this work? const gfx::Point po = view->GetBoundsInScreen().origin(); generator_->MoveMouseTo(po + p.OffsetFromOrigin()); generator_->ClickLeftButton(); #endif ui::MouseEvent press(ui::ET_MOUSE_PRESSED, gfx::Point(view->x() + p.x(), view->y() + p.y()), gfx::Point(0, 0), base::TimeTicks::Now(), 0, 0); view->OnMousePressed(press); } private: TestChooserListener listener_; std::unique_ptr<views::ColorChooser> chooser_; std::unique_ptr<views::Widget> widget_; std::unique_ptr<ui::test::EventGenerator> generator_; }; TEST_F(ColorChooserTest, ShowsInitialColor) { ExpectExactHSV(120, 1, 1); EXPECT_EQ(GetShownColor(), SK_ColorGREEN); EXPECT_EQ(GetTextualColor(), SK_ColorGREEN); } TEST_F(ColorChooserTest, AdjustingTextAdjustsShown) { TypeColor("#ff0000"); ExpectExactHSV(0, 1, 1); EXPECT_EQ(GetShownColor(), SK_ColorRED); TypeColor("0000ff"); ExpectExactHSV(240, 1, 1); EXPECT_EQ(GetShownColor(), SK_ColorBLUE); } TEST_F(ColorChooserTest, HueSliderChangesHue) { ExpectExactHSV(120, 1, 1); views::View* hv = chooser()->hue_view_for_testing(); PressMouseAt(hv, gfx::Point(1, hv->height())); ExpectApproximateHSV(0, 1, 1); PressMouseAt(hv, gfx::Point(1, (hv->height() * 3) / 4)); ExpectApproximateHSV(90, 1, 1); PressMouseAt(hv, gfx::Point(1, hv->height() / 2)); ExpectApproximateHSV(180, 1, 1); PressMouseAt(hv, gfx::Point(1, hv->height() / 4)); ExpectApproximateHSV(270, 1, 1); } // Missing tests, TODO: // TEST_F(ColorChooserTest, SatValueChooserChangesSatValue) // TEST_F(ColorChooserTest, UpdateFromWebUpdatesShownValues) // TEST_F(ColorChooserTest, AdjustingTextAffectsHue) // TEST_F(ColorChooserTest, AdjustingTextAffectsSatValue) } // namespace
Zhao-PengFei35/chromium_src_4
ui/views/color_chooser/color_chooser_unittest.cc
C++
unknown
6,018
// 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/color_chooser/color_chooser_view.h" #include <stdint.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "base/check.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_flags.h" #include "cc/paint/paint_shader.h" #include "skia/ext/skia_utils_base.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/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_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/insets.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/color_chooser/color_chooser_listener.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/layout/box_layout.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace { constexpr int kHueBarWidth = 20; constexpr int kSaturationValueSize = 200; constexpr int kMarginWidth = 5; constexpr int kSaturationValueIndicatorSize = 6; constexpr int kHueIndicatorSize = 5; constexpr int kBorderWidth = 1; constexpr int kTextfieldLengthInChars = 14; std::u16string GetColorText(SkColor color) { return base::ASCIIToUTF16(skia::SkColorToHexString(color)); } bool GetColorFromText(const std::u16string& text, SkColor* result) { if (text.size() != 6 && !(text.size() == 7 && text[0] == '#')) return false; std::string input = base::UTF16ToUTF8((text.size() == 6) ? text : text.substr(1)); std::array<uint8_t, 3> hex; if (!base::HexStringToSpan(input, hex)) return false; *result = SkColorSetRGB(hex[0], hex[1], hex[2]); return true; } // A view that processes mouse events and gesture events using a common // interface. class LocatedEventHandlerView : public views::View { public: METADATA_HEADER(LocatedEventHandlerView); LocatedEventHandlerView(const LocatedEventHandlerView&) = delete; LocatedEventHandlerView& operator=(const LocatedEventHandlerView&) = delete; ~LocatedEventHandlerView() override = default; protected: LocatedEventHandlerView() = default; // Handles an event (mouse or gesture) at the specified location. virtual void ProcessEventAtLocation(const gfx::Point& location) = 0; // views::View bool OnMousePressed(const ui::MouseEvent& event) override { ProcessEventAtLocation(event.location()); return true; } bool OnMouseDragged(const ui::MouseEvent& event) override { ProcessEventAtLocation(event.location()); return true; } void OnGestureEvent(ui::GestureEvent* event) override { if (event->type() == ui::ET_GESTURE_TAP || event->type() == ui::ET_GESTURE_TAP_DOWN || event->IsScrollGestureEvent()) { ProcessEventAtLocation(event->location()); event->SetHandled(); } } }; BEGIN_METADATA(LocatedEventHandlerView, views::View) END_METADATA void DrawGradientRect(const gfx::Rect& rect, SkColor start_color, SkColor end_color, bool is_horizontal, gfx::Canvas* canvas) { // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. SkColor4f colors[2] = {SkColor4f::FromColor(start_color), SkColor4f::FromColor(end_color)}; SkPoint points[2]; points[0].iset(0, 0); if (is_horizontal) points[1].iset(rect.width() + 1, 0); else points[1].iset(0, rect.height() + 1); cc::PaintFlags flags; flags.setShader(cc::PaintShader::MakeLinearGradient(points, colors, nullptr, 2, SkTileMode::kClamp)); canvas->DrawRect(rect, flags); } } // namespace namespace views { //////////////////////////////////////////////////////////////////////////////// // HueView // // The class to choose the hue of the color. It draws a vertical bar and // the indicator for the currently selected hue. class HueView : public LocatedEventHandlerView { public: METADATA_HEADER(HueView); using HueChangedCallback = base::RepeatingCallback<void(SkScalar)>; explicit HueView(const HueChangedCallback& changed_callback); HueView(const HueView&) = delete; HueView& operator=(const HueView&) = delete; ~HueView() override = default; // views::View void OnThemeChanged() override; void OnHueChanged(SkScalar hue); private: // LocatedEventHandlerView void ProcessEventAtLocation(const gfx::Point& point) override; // views::View gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; HueChangedCallback changed_callback_; int level_ = 0; SkColor background_color_; SkColor indicator_color_; }; HueView::HueView(const HueChangedCallback& changed_callback) : changed_callback_(changed_callback) {} void HueView::OnThemeChanged() { LocatedEventHandlerView::OnThemeChanged(); background_color_ = GetColorProvider()->GetColor(ui::kColorWindowBackground); indicator_color_ = GetColorProvider()->GetColor(ui::kColorMenuDropmarker); SchedulePaint(); } void HueView::OnHueChanged(SkScalar hue) { SkScalar height = SkIntToScalar(kSaturationValueSize - 1); SkScalar hue_max = SkIntToScalar(360); int level = (hue_max - hue) * height / hue_max; level += kBorderWidth; if (level_ != level) { level_ = level; SchedulePaint(); } } void HueView::ProcessEventAtLocation(const gfx::Point& point) { level_ = std::max(kBorderWidth, std::min(height() - 1 - kBorderWidth, point.y())); int base_height = kSaturationValueSize - 1; changed_callback_.Run(360.f * (base_height - (level_ - kBorderWidth)) / base_height); SchedulePaint(); } gfx::Size HueView::CalculatePreferredSize() const { // We put indicators on the both sides of the hue bar. return gfx::Size(kHueBarWidth + kHueIndicatorSize * 2 + kBorderWidth * 2, kSaturationValueSize + kBorderWidth * 2); } void HueView::OnPaint(gfx::Canvas* canvas) { SkScalar hsv[3]; // In the hue bar, saturation and value for the color should be always 100%. hsv[1] = SK_Scalar1; hsv[2] = SK_Scalar1; canvas->FillRect(gfx::Rect(kHueIndicatorSize, 0, kHueBarWidth + kBorderWidth, height() - 1), background_color_); int base_left = kHueIndicatorSize + kBorderWidth; for (int y = 0; y < kSaturationValueSize; ++y) { hsv[0] = 360.f * (kSaturationValueSize - 1 - y) / (kSaturationValueSize - 1); canvas->FillRect(gfx::Rect(base_left, y + kBorderWidth, kHueBarWidth, 1), SkHSVToColor(hsv)); } // Put the triangular indicators besides. SkPath left_indicator_path; SkPath right_indicator_path; left_indicator_path.moveTo(SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); left_indicator_path.lineTo(kHueIndicatorSize, SkIntToScalar(level_)); left_indicator_path.lineTo(SK_ScalarHalf, SkIntToScalar(level_ + kHueIndicatorSize)); left_indicator_path.lineTo(SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); right_indicator_path.moveTo(SkIntToScalar(width()) - SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); right_indicator_path.lineTo( SkIntToScalar(width() - kHueIndicatorSize) - SK_ScalarHalf, SkIntToScalar(level_)); right_indicator_path.lineTo(SkIntToScalar(width()) - SK_ScalarHalf, SkIntToScalar(level_ + kHueIndicatorSize)); right_indicator_path.lineTo(SkIntToScalar(width()) - SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); cc::PaintFlags indicator_flags; indicator_flags.setColor(indicator_color_); indicator_flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawPath(left_indicator_path, indicator_flags); canvas->DrawPath(right_indicator_path, indicator_flags); } BEGIN_METADATA(HueView, LocatedEventHandlerView) END_METADATA //////////////////////////////////////////////////////////////////////////////// // SaturationValueView // // The class to choose the saturation and the value of the color. It draws // a square area and the indicator for the currently selected saturation and // value. class SaturationValueView : public LocatedEventHandlerView { public: METADATA_HEADER(SaturationValueView); using SaturationValueChangedCallback = base::RepeatingCallback<void(SkScalar, SkScalar)>; explicit SaturationValueView( const SaturationValueChangedCallback& changed_callback); SaturationValueView(const SaturationValueView&) = delete; SaturationValueView& operator=(const SaturationValueView&) = delete; ~SaturationValueView() override = default; // views::View void OnThemeChanged() override; void OnHueChanged(SkScalar hue); void OnSaturationValueChanged(SkScalar saturation, SkScalar value); private: // LocatedEventHandlerView void ProcessEventAtLocation(const gfx::Point& point) override; // views::View gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; void UpdateMarkerColor(); SaturationValueChangedCallback changed_callback_; SkScalar hue_ = 0; SkScalar saturation_ = 0; SkScalar value_ = 0; gfx::Point marker_position_; SkColor marker_color_; }; SaturationValueView::SaturationValueView( const SaturationValueChangedCallback& changed_callback) : changed_callback_(changed_callback), marker_color_(gfx::kPlaceholderColor) { SetBorder(CreateSolidBorder(kBorderWidth, gfx::kPlaceholderColor)); } void SaturationValueView::OnThemeChanged() { LocatedEventHandlerView::OnThemeChanged(); GetBorder()->set_color( GetColorProvider()->GetColor(ui::kColorFocusableBorderUnfocused)); SchedulePaint(); } void SaturationValueView::OnHueChanged(SkScalar hue) { if (hue_ != hue) { hue_ = hue; UpdateMarkerColor(); SchedulePaint(); } } void SaturationValueView::OnSaturationValueChanged(SkScalar saturation, SkScalar value) { if (saturation_ == saturation && value_ == value) return; saturation_ = saturation; value_ = value; SkScalar scalar_size = SkIntToScalar(kSaturationValueSize - 1); int x = SkScalarFloorToInt(saturation * scalar_size) + kBorderWidth; int y = SkScalarFloorToInt((SK_Scalar1 - value) * scalar_size) + kBorderWidth; if (gfx::Point(x, y) == marker_position_) return; marker_position_.set_x(x); marker_position_.set_y(y); UpdateMarkerColor(); SchedulePaint(); } void SaturationValueView::ProcessEventAtLocation(const gfx::Point& point) { SkScalar scalar_size = SkIntToScalar(kSaturationValueSize - 1); SkScalar saturation = (point.x() - kBorderWidth) / scalar_size; SkScalar value = SK_Scalar1 - (point.y() - kBorderWidth) / scalar_size; saturation = std::clamp(saturation, 0.0f, SK_Scalar1); value = std::clamp(value, 0.0f, SK_Scalar1); OnSaturationValueChanged(saturation, value); changed_callback_.Run(saturation, value); } gfx::Size SaturationValueView::CalculatePreferredSize() const { return gfx::Size(kSaturationValueSize + kBorderWidth * 2, kSaturationValueSize + kBorderWidth * 2); } void SaturationValueView::OnPaint(gfx::Canvas* canvas) { gfx::Rect color_bounds = bounds(); color_bounds.Inset(GetInsets()); // Paints horizontal gradient first for saturation. SkScalar hsv[3] = {hue_, SK_Scalar1, SK_Scalar1}; SkScalar left_hsv[3] = {hue_, 0, SK_Scalar1}; DrawGradientRect(color_bounds, SkHSVToColor(255, left_hsv), SkHSVToColor(255, hsv), true /* is_horizontal */, canvas); // Overlays vertical gradient for value. SkScalar hsv_bottom[3] = {0, SK_Scalar1, 0}; DrawGradientRect(color_bounds, SK_ColorTRANSPARENT, SkHSVToColor(255, hsv_bottom), false /* is_horizontal */, canvas); // Draw the crosshair marker. canvas->FillRect( gfx::Rect(marker_position_.x(), marker_position_.y() - kSaturationValueIndicatorSize, 1, kSaturationValueIndicatorSize * 2 + 1), marker_color_); canvas->FillRect( gfx::Rect(marker_position_.x() - kSaturationValueIndicatorSize, marker_position_.y(), kSaturationValueIndicatorSize * 2 + 1, 1), marker_color_); OnPaintBorder(canvas); } void SaturationValueView::UpdateMarkerColor() { SkScalar hsv[3] = {hue_, saturation_, value_}; marker_color_ = color_utils::GetColorWithMaxContrast(SkHSVToColor(hsv)); } BEGIN_METADATA(SaturationValueView, LocatedEventHandlerView) END_METADATA //////////////////////////////////////////////////////////////////////////////// // SelectedColorPatchView // // A view to simply show the selected color in a rectangle. class SelectedColorPatchView : public views::View { public: METADATA_HEADER(SelectedColorPatchView); SelectedColorPatchView(); SelectedColorPatchView(const SelectedColorPatchView&) = delete; SelectedColorPatchView& operator=(const SelectedColorPatchView&) = delete; ~SelectedColorPatchView() override = default; void SetColor(SkColor color); }; SelectedColorPatchView::SelectedColorPatchView() { SetVisible(true); SetBorder(CreateThemedSolidBorder(kBorderWidth, ui::kColorFocusableBorderUnfocused)); } void SelectedColorPatchView::SetColor(SkColor color) { if (!background()) SetBackground(CreateSolidBackground(color)); else background()->SetNativeControlColor(color); SchedulePaint(); } BEGIN_METADATA(SelectedColorPatchView, views::View) END_METADATA std::unique_ptr<View> ColorChooser::BuildView() { auto view = std::make_unique<View>(); tracker_.SetView(view.get()); view->SetBackground(CreateThemedSolidBackground(ui::kColorWindowBackground)); view->SetLayoutManager( std::make_unique<BoxLayout>(BoxLayout::Orientation::kVertical, gfx::Insets(kMarginWidth), kMarginWidth)); auto container = std::make_unique<View>(); container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kMarginWidth)); saturation_value_ = container->AddChildView( std::make_unique<SaturationValueView>(base::BindRepeating( &ColorChooser::OnSaturationValueChosen, this->AsWeakPtr()))); hue_ = container->AddChildView(std::make_unique<HueView>( base::BindRepeating(&ColorChooser::OnHueChosen, this->AsWeakPtr()))); view->AddChildView(std::move(container)); auto container2 = std::make_unique<View>(); BoxLayout* layout = container2->SetLayoutManager(std::make_unique<views::BoxLayout>( BoxLayout::Orientation::kHorizontal, gfx::Insets(), kMarginWidth)); auto textfield = std::make_unique<Textfield>(); textfield->set_controller(this); textfield->SetDefaultWidthInChars(kTextfieldLengthInChars); textfield->SetAccessibleName( l10n_util::GetStringUTF16(IDS_APP_ACCNAME_COLOR_CHOOSER_HEX_INPUT)); textfield_ = container2->AddChildView(std::move(textfield)); selected_color_patch_ = container2->AddChildView(std::make_unique<SelectedColorPatchView>()); layout->SetFlexForView(selected_color_patch_, 1); view->AddChildView(std::move(container2)); OnColorChanged(initial_color_); return view; } bool ColorChooser::IsViewAttached() const { return tracker_.view(); } void ColorChooser::OnColorChanged(SkColor color) { SetColor(color); if (IsViewAttached()) { hue_->OnHueChanged(hue()); saturation_value_->OnHueChanged(hue()); saturation_value_->OnSaturationValueChanged(saturation(), value()); selected_color_patch_->SetColor(color); textfield_->SetText(GetColorText(color)); } } void ColorChooser::OnHueChosen(SkScalar hue) { SetHue(hue); SkColor color = GetColor(); saturation_value_->OnHueChanged(hue); selected_color_patch_->SetColor(color); textfield_->SetText(GetColorText(color)); } void ColorChooser::OnSaturationValueChosen(SkScalar saturation, SkScalar value) { SetSaturationValue(saturation, value); SkColor color = GetColor(); selected_color_patch_->SetColor(color); textfield_->SetText(GetColorText(color)); } View* ColorChooser::hue_view_for_testing() { return hue_; } View* ColorChooser::saturation_value_view_for_testing() { return saturation_value_; } Textfield* ColorChooser::textfield_for_testing() { return textfield_; } View* ColorChooser::selected_color_patch_for_testing() { return selected_color_patch_; } void ColorChooser::ContentsChanged(Textfield* sender, const std::u16string& new_contents) { DCHECK(IsViewAttached()); SkColor color = gfx::kPlaceholderColor; if (GetColorFromText(new_contents, &color)) { SetColor(color); hue_->OnHueChanged(hue()); saturation_value_->OnHueChanged(hue()); saturation_value_->OnSaturationValueChanged(saturation(), value()); selected_color_patch_->SetColor(color); } } bool ColorChooser::HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) { DCHECK(IsViewAttached()); if (key_event.type() != ui::ET_KEY_PRESSED || (key_event.key_code() != ui::VKEY_RETURN && key_event.key_code() != ui::VKEY_ESCAPE)) return false; tracker_.view()->GetWidget()->Close(); return true; } std::unique_ptr<WidgetDelegate> ColorChooser::MakeWidgetDelegate() { DCHECK(!IsViewAttached()); auto delegate = std::make_unique<WidgetDelegate>(); delegate->SetCanMinimize(false); delegate->SetContentsView(BuildView()); delegate->SetInitiallyFocusedView(textfield_); delegate->SetModalType(ui::MODAL_TYPE_WINDOW); delegate->SetOwnedByWidget(true); delegate->RegisterWindowClosingCallback( base::BindOnce(&ColorChooser::OnViewClosing, this->AsWeakPtr())); return delegate; } ColorChooser::ColorChooser(ColorChooserListener* listener, SkColor initial) : listener_(listener), initial_color_(initial) {} ColorChooser::~ColorChooser() = default; void ColorChooser::SetColor(SkColor color) { SkColorToHSV(color, hsv_); listener_->OnColorChosen(GetColor()); } void ColorChooser::SetHue(SkScalar hue) { hsv_[0] = hue; listener_->OnColorChosen(GetColor()); } void ColorChooser::SetSaturationValue(SkScalar saturation, SkScalar value) { hsv_[1] = saturation; hsv_[2] = value; listener_->OnColorChosen(GetColor()); } SkColor ColorChooser::GetColor() const { return SkHSVToColor(255, hsv_); } void ColorChooser::OnViewClosing() { listener_->OnColorChooserDialogClosed(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/color_chooser/color_chooser_view.cc
C++
unknown
19,342
// 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_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_ #define UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkScalar.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/view.h" #include "ui/views/view_tracker.h" #include "ui/views/views_export.h" namespace views { class ColorChooserListener; class Textfield; class WidgetDelegate; class HueView; class SaturationValueView; class SelectedColorPatchView; // ColorChooser provides the UI to choose a color by mouse and/or keyboard. // It is typically used for <input type="color">. Currently the user can // choose a color by dragging over the bar for hue and the area for saturation // and value. // // All public methods on ColorChooser are safe to call before, during, or after // the existence of the corresponding Widget/Views/etc. class VIEWS_EXPORT ColorChooser : public TextfieldController, public base::SupportsWeakPtr<ColorChooser> { public: ColorChooser(ColorChooserListener* listener, SkColor initial_color); ~ColorChooser() override; // Construct the WidgetDelegate that should be used to show the actual dialog // for this ColorChooser. It is only safe to call this once per ColorChooser // instance. std::unique_ptr<WidgetDelegate> MakeWidgetDelegate(); SkColor GetColor() const; SkScalar hue() const { return hsv_[0]; } SkScalar saturation() const { return hsv_[1]; } SkScalar value() const { return hsv_[2]; } bool IsViewAttached() const; // Called when its color value is changed in the web contents. void OnColorChanged(SkColor color); // TextfieldController overrides, public for testing: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) override; View* hue_view_for_testing(); View* saturation_value_view_for_testing(); Textfield* textfield_for_testing(); View* selected_color_patch_for_testing(); private: std::unique_ptr<View> BuildView(); void SetColor(SkColor color); void SetHue(SkScalar hue); void SetSaturationValue(SkScalar saturation, SkScalar value); void OnViewClosing(); // Called when the user chooses a hue from the UI. void OnHueChosen(SkScalar hue); // Called when the user chooses saturation/value from the UI. void OnSaturationValueChosen(SkScalar saturation, SkScalar value); // The current color in HSV coordinate. SkScalar hsv_[3]; raw_ptr<ColorChooserListener> listener_; ViewTracker tracker_; // Child views. These are owned as part of the normal views hierarchy. // The view of hue chooser. raw_ptr<HueView> hue_ = nullptr; // The view of saturation/value choosing area. raw_ptr<SaturationValueView> saturation_value_ = nullptr; // The rectangle to denote the selected color. raw_ptr<SelectedColorPatchView> selected_color_patch_ = nullptr; // The textfield to write the color explicitly. raw_ptr<Textfield> textfield_ = nullptr; SkColor initial_color_; }; } // namespace views #endif // UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/color_chooser/color_chooser_view.h
C++
unknown
3,479
// 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/context_menu_controller.h" #include "base/auto_reset.h" namespace views { ContextMenuController::ContextMenuController() = default; ContextMenuController::~ContextMenuController() = default; void ContextMenuController::ShowContextMenuForView( View* source, const gfx::Point& point, ui::MenuSourceType source_type) { // Use a boolean flag to early-exit out of re-entrant behavior. if (is_opening_) return; is_opening_ = true; // We might get deleted while showing the context menu (including as a result // of showing it). If so, we need to make sure we're not accessing // |is_opening_|. auto weak_ptr = weak_factory_.GetWeakPtr(); ShowContextMenuForViewImpl(source, point, source_type); if (!weak_ptr) return; is_opening_ = false; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/context_menu_controller.cc
C++
unknown
969
// 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_CONTEXT_MENU_CONTROLLER_H_ #define UI_VIEWS_CONTEXT_MENU_CONTROLLER_H_ #include "base/memory/weak_ptr.h" #include "ui/base/ui_base_types.h" #include "ui/views/views_export.h" namespace gfx { class Point; } namespace views { class View; // ContextMenuController is responsible for showing the context menu for a // View. To use a ContextMenuController invoke set_context_menu_controller on a // View. When the appropriate user gesture occurs ShowContextMenu is invoked // on the ContextMenuController. // // Setting a ContextMenuController on a view makes the view process mouse // events. // // It is up to subclasses that do their own mouse processing to invoke // the appropriate ContextMenuController method, typically by invoking super's // implementation for mouse processing. class VIEWS_EXPORT ContextMenuController { public: ContextMenuController(); ContextMenuController(const ContextMenuController&) = delete; ContextMenuController& operator=(const ContextMenuController&) = delete; // Invoked to show the context menu for |source|. |point| is in screen // coordinates. This method also prevents reentrant calls. void ShowContextMenuForView(View* source, const gfx::Point& point, ui::MenuSourceType source_type); protected: virtual ~ContextMenuController(); private: // Subclasses should override this method. virtual void ShowContextMenuForViewImpl(View* source, const gfx::Point& point, ui::MenuSourceType source_type) = 0; // Used as a flag to prevent a re-entrancy in ShowContextMenuForView(). // This is most relevant to Linux, where spawning the textfield context menu // spins a nested message loop that processes input events, which may attempt // to trigger another context menu. bool is_opening_ = false; base::WeakPtrFactory<ContextMenuController> weak_factory_{this}; }; } // namespace views #endif // UI_VIEWS_CONTEXT_MENU_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/views/context_menu_controller.h
C++
unknown
2,212
// 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/animated_image_view.h" #include <utility> #include "base/check.h" #include "base/trace_event/trace_event.h" #include "cc/paint/skottie_wrapper.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/compositor/compositor.h" #include "ui/gfx/canvas.h" #include "ui/views/widget/widget.h" namespace views { namespace { bool AreAnimatedImagesEqual(const lottie::Animation& animation_1, const lottie::Animation& animation_2) { // In rare cases this may return false, even if the animated images are backed // by the same resource file. return animation_1.skottie() == animation_2.skottie(); } } // namespace AnimatedImageView::AnimatedImageView() = default; AnimatedImageView::~AnimatedImageView() = default; void AnimatedImageView::SetAnimatedImage( std::unique_ptr<lottie::Animation> animated_image) { if (animated_image_ && AreAnimatedImagesEqual(*animated_image, *animated_image_)) { Stop(); return; } gfx::Size preferred_size(GetPreferredSize()); animated_image_ = std::move(animated_image); // Stop the animation to reset it. Stop(); if (preferred_size != GetPreferredSize()) PreferredSizeChanged(); SchedulePaint(); } void AnimatedImageView::Play( absl::optional<lottie::Animation::PlaybackConfig> playback_config) { DCHECK(animated_image_); if (state_ == State::kPlaying) return; state_ = State::kPlaying; if (!playback_config) { playback_config = lottie::Animation::PlaybackConfig::CreateDefault(*animated_image_); } set_check_active_duration(playback_config->style != lottie::Animation::Style::kLoop); SetCompositorFromWidget(); animated_image_->Start(std::move(playback_config)); } void AnimatedImageView::Stop() { if (state_ == State::kStopped) return; DCHECK(animated_image_); ClearCurrentCompositor(); animated_image_->Stop(); state_ = State::kStopped; } gfx::Size AnimatedImageView::GetImageSize() const { return image_size_.value_or( animated_image_ ? animated_image_->GetOriginalSize() : gfx::Size()); } void AnimatedImageView::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); if (!animated_image_) return; canvas->Save(); gfx::Vector2d translation = GetImageBounds().origin().OffsetFromOrigin(); translation.Add(additional_translation_); canvas->Translate(std::move(translation)); if (!previous_timestamp_.is_null() && state_ != State::kStopped) { animated_image_->Paint(canvas, previous_timestamp_, GetImageSize()); } else { // OnPaint may be called before clock tick was received; in that case just // paint the first frame. animated_image_->PaintFrame(canvas, 0, GetImageSize()); } canvas->Restore(); } void AnimatedImageView::NativeViewHierarchyChanged() { ui::Compositor* compositor = GetWidget()->GetCompositor(); DCHECK(compositor); if (compositor_ != compositor) { ClearCurrentCompositor(); // Restore the Play() state with the new compositor. if (state_ == State::kPlaying) SetCompositorFromWidget(); } } void AnimatedImageView::RemovedFromWidget() { if (compositor_) { Stop(); ClearCurrentCompositor(); } } void AnimatedImageView::OnAnimationStep(base::TimeTicks timestamp) { TRACE_EVENT1("views", "AnimatedImageView::OnAnimationStep", "timestamp", timestamp); previous_timestamp_ = timestamp; SchedulePaint(); } void AnimatedImageView::OnCompositingShuttingDown(ui::Compositor* compositor) { if (compositor_ == compositor) { Stop(); ClearCurrentCompositor(); } } void AnimatedImageView::SetCompositorFromWidget() { DCHECK(!compositor_); auto* widget = GetWidget(); DCHECK(widget); compositor_ = widget->GetCompositor(); DCHECK(!compositor_->HasAnimationObserver(this)); compositor_->AddAnimationObserver(this); } void AnimatedImageView::ClearCurrentCompositor() { if (compositor_) { DCHECK(compositor_->HasAnimationObserver(this)); compositor_->RemoveAnimationObserver(this); compositor_ = nullptr; } } BEGIN_METADATA(AnimatedImageView, ImageViewBase) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/animated_image_view.cc
C++
unknown
4,331
// 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_ANIMATED_IMAGE_VIEW_H_ #define UI_VIEWS_CONTROLS_ANIMATED_IMAGE_VIEW_H_ #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/compositor/compositor_animation_observer.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/lottie/animation.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 ui { class Compositor; } namespace views { ///////////////////////////////////////////////////////////////////////////// // // AnimatedImageView class. // // An AnimatedImageView can display a skia vector animation. The animation paint // size can be set via SetImageSize. The animation is stopped by default. // Use this over AnimatedIconView if you want to play a skottie animation file. // ///////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT AnimatedImageView : public ImageViewBase, public ui::CompositorAnimationObserver { public: METADATA_HEADER(AnimatedImageView); enum class State { kPlaying, // The animation is currently playing. kStopped // The animation is stopped and paint will raster the first // frame. }; AnimatedImageView(); AnimatedImageView(const AnimatedImageView&) = delete; AnimatedImageView& operator=(const AnimatedImageView&) = delete; ~AnimatedImageView() override; // Set the animated image that should be displayed. Setting an animated image // will result in stopping the current animation. void SetAnimatedImage(std::unique_ptr<lottie::Animation> animated_image); // Plays the animation and must only be called when this view has // access to a widget. // // If a null |playback_config| is provided, the default one is used. void Play(absl::optional<lottie::Animation::PlaybackConfig> playback_config = absl::nullopt); // Stops any animation and resets it to the start frame. void Stop(); // May return null if SetAnimatedImage() has not been called. lottie::Animation* animated_image() { return animated_image_.get(); } // Sets additional translation that will be applied to all future rendered // animation frames. The term "additional" is used because the provided // translation is applied on top of the translation that ImageViewBase already // applies to align the animation appropriately within the view's boundaries. // // Note this is not the same as translating the entire View. This only // translates the animation within the existing content bounds of the View. By // default, there is no additional translation. void SetAdditionalTranslation(gfx::Vector2d additional_translation) { additional_translation_ = std::move(additional_translation); } private: // Overridden from View: void OnPaint(gfx::Canvas* canvas) override; void NativeViewHierarchyChanged() override; void RemovedFromWidget() override; // Overridden from ui::CompositorAnimationObserver: void OnAnimationStep(base::TimeTicks timestamp) override; void OnCompositingShuttingDown(ui::Compositor* compositor) override; // Overridden from ImageViewBase: gfx::Size GetImageSize() const override; void SetCompositorFromWidget(); void ClearCurrentCompositor(); // The current state of the animation. State state_ = State::kStopped; // The compositor associated with the widget of this view. raw_ptr<ui::Compositor> compositor_ = nullptr; // The most recent timestamp at which a paint was scheduled for this view. base::TimeTicks previous_timestamp_; // The underlying lottie animation. std::unique_ptr<lottie::Animation> animated_image_; gfx::Vector2d additional_translation_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, AnimatedImageView, ImageViewBase) VIEW_BUILDER_PROPERTY(std::unique_ptr<lottie::Animation>, AnimatedImage) VIEW_BUILDER_PROPERTY(gfx::Vector2d, AdditionalTranslation) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, AnimatedImageView) #endif // UI_VIEWS_CONTROLS_ANIMATED_IMAGE_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/animated_image_view.h
C++
unknown
4,428
// 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/animated_image_view.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "cc/paint/display_item_list.h" #include "cc/paint/paint_op_buffer_iterator.h" #include "cc/test/skia_common.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/paint_context.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/lottie/animation.h" #include "ui/views/paint_info.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/widget/widget.h" namespace views { namespace { using ::testing::FloatEq; using ::testing::NotNull; template <typename T> const T* FindPaintOp(const cc::PaintRecord& paint_record, cc::PaintOpType paint_op_type) { for (const cc::PaintOp& op : paint_record) { if (op.GetType() == paint_op_type) return static_cast<const T*>(&op); if (op.GetType() == cc::PaintOpType::DrawRecord) { const T* record_op_result = FindPaintOp<T>( static_cast<const cc::DrawRecordOp&>(op).record, paint_op_type); if (record_op_result) return static_cast<const T*>(record_op_result); } } return nullptr; } class AnimatedImageViewTest : public ViewsTestBase { protected: static constexpr int kDefaultWidthAndHeight = 100; static constexpr gfx::Size kDefaultSize = gfx::Size(kDefaultWidthAndHeight, kDefaultWidthAndHeight); void SetUp() override { ViewsTestBase::SetUp(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(kDefaultSize); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget_.Init(std::move(params)); view_ = widget_.SetContentsView(std::make_unique<AnimatedImageView>()); view_->SetUseDefaultFillLayout(true); widget_.Show(); } void TearDown() override { widget_.Close(); ViewsTestBase::TearDown(); } std::unique_ptr<lottie::Animation> CreateAnimationWithSize( const gfx::Size& size) { return std::make_unique<lottie::Animation>( cc::CreateSkottie(size, /*duration_secs=*/1)); } cc::PaintRecord Paint(const gfx::Rect& invalidation_rect) { auto display_list = base::MakeRefCounted<cc::DisplayItemList>(); ui::PaintContext paint_context(display_list.get(), /*device_scale_factor=*/1.f, invalidation_rect, /*is_pixel_canvas=*/true); view_->Paint(PaintInfo::CreateRootPaintInfo(paint_context, invalidation_rect.size())); RunPendingMessages(); return display_list->FinalizeAndReleaseAsRecord(); } Widget widget_; raw_ptr<AnimatedImageView> view_; }; TEST_F(AnimatedImageViewTest, PaintsWithAdditionalTranslation) { view_->SetAnimatedImage(CreateAnimationWithSize(gfx::Size(80, 80))); view_->SetVerticalAlignment(ImageViewBase::Alignment::kCenter); view_->SetHorizontalAlignment(ImageViewBase::Alignment::kCenter); views::test::RunScheduledLayout(view_); view_->Play(); static constexpr float kExpectedDefaultOrigin = (kDefaultWidthAndHeight - 80) / 2; // Default should be no extra translation. cc::PaintRecord paint_record = Paint(view_->bounds()); const cc::TranslateOp* translate_op = FindPaintOp<cc::TranslateOp>(paint_record, cc::PaintOpType::Translate); ASSERT_THAT(translate_op, NotNull()); EXPECT_THAT(translate_op->dx, FloatEq(kExpectedDefaultOrigin)); EXPECT_THAT(translate_op->dy, FloatEq(kExpectedDefaultOrigin)); view_->SetAdditionalTranslation(gfx::Vector2d(5, 5)); paint_record = Paint(view_->bounds()); translate_op = FindPaintOp<cc::TranslateOp>(paint_record, cc::PaintOpType::Translate); ASSERT_THAT(translate_op, NotNull()); EXPECT_THAT(translate_op->dx, FloatEq(kExpectedDefaultOrigin + 5)); EXPECT_THAT(translate_op->dy, FloatEq(kExpectedDefaultOrigin + 5)); view_->SetAdditionalTranslation(gfx::Vector2d(5, -5)); paint_record = Paint(view_->bounds()); translate_op = FindPaintOp<cc::TranslateOp>(paint_record, cc::PaintOpType::Translate); ASSERT_THAT(translate_op, NotNull()); EXPECT_THAT(translate_op->dx, FloatEq(kExpectedDefaultOrigin + 5)); EXPECT_THAT(translate_op->dy, FloatEq(kExpectedDefaultOrigin - 5)); view_->SetAdditionalTranslation(gfx::Vector2d(-5, 5)); paint_record = Paint(view_->bounds()); translate_op = FindPaintOp<cc::TranslateOp>(paint_record, cc::PaintOpType::Translate); ASSERT_THAT(translate_op, NotNull()); EXPECT_THAT(translate_op->dx, FloatEq(kExpectedDefaultOrigin - 5)); EXPECT_THAT(translate_op->dy, FloatEq(kExpectedDefaultOrigin + 5)); view_->SetAdditionalTranslation(gfx::Vector2d(-5, -5)); paint_record = Paint(view_->bounds()); translate_op = FindPaintOp<cc::TranslateOp>(paint_record, cc::PaintOpType::Translate); ASSERT_THAT(translate_op, NotNull()); EXPECT_THAT(translate_op->dx, FloatEq(kExpectedDefaultOrigin - 5)); EXPECT_THAT(translate_op->dy, FloatEq(kExpectedDefaultOrigin - 5)); } } // namespace } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/animated_image_view_unittest.cc
C++
unknown
5,389
// 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/badge.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/badge_painter.h" #include "ui/views/controls/label.h" namespace views { Badge::Badge(const std::u16string& text) : text_(text) {} Badge::~Badge() = default; std::u16string Badge::GetText() const { return text_; } void Badge::SetText(const std::u16string& text) { text_ = text; OnPropertyChanged(&text_, kPropertyEffectsPreferredSizeChanged); } gfx::Size Badge::CalculatePreferredSize() const { return BadgePainter::GetBadgeSize(text_, Label::GetDefaultFontList()); } void Badge::OnPaint(gfx::Canvas* canvas) { BadgePainter::PaintBadge(canvas, this, 0, 0, text_, Label::GetDefaultFontList()); } BEGIN_METADATA(Badge, View) ADD_PROPERTY_METADATA(std::u16string, Text) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/badge.cc
C++
unknown
1,000
// 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_BADGE_H_ #define UI_VIEWS_CONTROLS_BADGE_H_ #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { // A badge that displays a small piece of infromational text on a square blue // background. class VIEWS_EXPORT Badge : public View { public: METADATA_HEADER(Badge); explicit Badge(const std::u16string& text = std::u16string()); Badge(const Badge&) = delete; Badge& operator=(const Badge&) = delete; ~Badge() override; std::u16string GetText() const; void SetText(const std::u16string& text); // View: gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; private: std::u16string text_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Badge, View) VIEW_BUILDER_PROPERTY(std::u16string, Text) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Badge) #endif // UI_VIEWS_CONTROLS_BADGE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/badge.h
C++
unknown
1,114
// 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/base_control_test_widget.h" #include <memory> #include <utility> #include "build/build_config.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_MAC) #include "ui/display/mac/test/test_screen_mac.h" #include "ui/display/screen.h" #endif namespace views::test { BaseControlTestWidget::BaseControlTestWidget() = default; BaseControlTestWidget::~BaseControlTestWidget() = default; void BaseControlTestWidget::SetUp() { #if BUILDFLAG(IS_MAC) test_screen_ = std::make_unique<display::test::TestScreenMac>(gfx::Size()); // Purposely not use ScopedScreenOverride, in which GetScreen() will // create a native screen. display::Screen::SetScreenInstance(test_screen_.get()); #endif ViewsTestBase::SetUp(); widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200); widget_->Init(std::move(params)); auto* container = widget_->SetContentsView(std::make_unique<View>()); CreateWidgetContent(container); widget_->Show(); } void BaseControlTestWidget::TearDown() { widget_.reset(); ViewsTestBase::TearDown(); #if BUILDFLAG(IS_MAC) display::Screen::SetScreenInstance(nullptr); #endif } void BaseControlTestWidget::CreateWidgetContent(View* container) {} } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/controls/base_control_test_widget.cc
C++
unknown
1,496
// 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_BASE_CONTROL_TEST_WIDGET_H_ #define UI_VIEWS_CONTROLS_BASE_CONTROL_TEST_WIDGET_H_ #include "build/build_config.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/unique_widget_ptr.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_utils.h" #if BUILDFLAG(IS_MAC) #include <memory> namespace display::test { class TestScreen; } // namespace display::test #endif namespace views::test { class BaseControlTestWidget : public ViewsTestBase { public: BaseControlTestWidget(); BaseControlTestWidget(const BaseControlTestWidget&) = delete; BaseControlTestWidget& operator=(const BaseControlTestWidget&) = delete; ~BaseControlTestWidget() override; // ViewsTestBase: void SetUp() override; void TearDown() override; protected: virtual void CreateWidgetContent(View* container); Widget* widget() { return widget_.get(); } private: UniqueWidgetPtr widget_; #if BUILDFLAG(IS_MAC) // Need a test screen to work with the event generator to correctly track // cursor locations. See https://crbug.com/1071633. Consider moving this // into ViewsTestHelperMac in the future. std::unique_ptr<display::test::TestScreen> test_screen_; #endif }; } // namespace views::test #endif // UI_VIEWS_CONTROLS_BASE_CONTROL_TEST_WIDGET_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/base_control_test_widget.h
C++
unknown
1,492
// 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. #include "ui/views/controls/button/button.h" #include <utility> #include "base/debug/alias.h" #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/class_property.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/animation/throb_animation.h" #include "ui/gfx/color_palette.h" #include "ui/native_theme/native_theme.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/controls/button/button_controller.h" #include "ui/views/controls/button/button_controller_delegate.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/interaction/element_tracker_views.h" #include "ui/views/painter.h" #include "ui/views/style/platform_style.h" #include "ui/views/view_class_properties.h" #if defined(USE_AURA) #include "ui/aura/client/capture_client.h" #include "ui/aura/window.h" #endif namespace views { namespace { DEFINE_UI_CLASS_PROPERTY_KEY(bool, kIsButtonProperty, false) } // namespace Button::DefaultButtonControllerDelegate::DefaultButtonControllerDelegate( Button* button) : ButtonControllerDelegate(button) {} Button::DefaultButtonControllerDelegate::~DefaultButtonControllerDelegate() = default; void Button::DefaultButtonControllerDelegate::RequestFocusFromEvent() { button()->RequestFocusFromEvent(); } void Button::DefaultButtonControllerDelegate::NotifyClick( const ui::Event& event) { button()->NotifyClick(event); // Avoid outgoing tail calls to generate better stack frames for a crash. // https://crbug.com/1215247 base::debug::Alias(nullptr); } void Button::DefaultButtonControllerDelegate::OnClickCanceled( const ui::Event& event) { button()->OnClickCanceled(event); } bool Button::DefaultButtonControllerDelegate::IsTriggerableEvent( const ui::Event& event) { return button()->IsTriggerableEvent(event); } bool Button::DefaultButtonControllerDelegate::ShouldEnterPushedState( const ui::Event& event) { return button()->ShouldEnterPushedState(event); } bool Button::DefaultButtonControllerDelegate::ShouldEnterHoveredState() { return button()->ShouldEnterHoveredState(); } InkDrop* Button::DefaultButtonControllerDelegate::GetInkDrop() { return InkDrop::Get(button()->ink_drop_view())->GetInkDrop(); } int Button::DefaultButtonControllerDelegate::GetDragOperations( const gfx::Point& press_pt) { return button()->GetDragOperations(press_pt); } bool Button::DefaultButtonControllerDelegate::InDrag() { return button()->InDrag(); } Button::PressedCallback::PressedCallback( Button::PressedCallback::Callback callback) : callback_(std::move(callback)) {} Button::PressedCallback::PressedCallback(base::RepeatingClosure closure) : callback_( base::BindRepeating([](base::RepeatingClosure closure, const ui::Event& event) { closure.Run(); }, std::move(closure))) {} Button::PressedCallback::PressedCallback(const PressedCallback&) = default; Button::PressedCallback::PressedCallback(PressedCallback&&) = default; Button::PressedCallback& Button::PressedCallback::operator=( const PressedCallback&) = default; Button::PressedCallback& Button::PressedCallback::operator=(PressedCallback&&) = default; Button::PressedCallback::~PressedCallback() = default; Button::ScopedAnchorHighlight::ScopedAnchorHighlight( base::WeakPtr<Button> button) : button_(button) {} Button::ScopedAnchorHighlight::~ScopedAnchorHighlight() { if (button_) { button_->ReleaseAnchorHighlight(); } } Button::ScopedAnchorHighlight::ScopedAnchorHighlight( Button::ScopedAnchorHighlight&&) = default; // We need to implement this one manually because the default move assignment // operator does not call the destructor on `this`. That leads to us failing to // release our reference on `button_`. Button::ScopedAnchorHighlight& Button::ScopedAnchorHighlight::operator=( Button::ScopedAnchorHighlight&& other) { if (button_) { button_->ReleaseAnchorHighlight(); } button_ = std::move(other.button_); return *this; } // static constexpr Button::ButtonState Button::kButtonStates[STATE_COUNT]; // static const Button* Button::AsButton(const views::View* view) { return AsButton(const_cast<View*>(view)); } // static Button* Button::AsButton(views::View* view) { if (view && view->GetProperty(kIsButtonProperty)) return static_cast<Button*>(view); return nullptr; } // static Button::ButtonState Button::GetButtonStateFrom(ui::NativeTheme::State state) { switch (state) { case ui::NativeTheme::kDisabled: return Button::STATE_DISABLED; case ui::NativeTheme::kHovered: return Button::STATE_HOVERED; case ui::NativeTheme::kNormal: return Button::STATE_NORMAL; case ui::NativeTheme::kPressed: return Button::STATE_PRESSED; case ui::NativeTheme::kNumStates: NOTREACHED_NORETURN(); } return Button::STATE_NORMAL; } Button::~Button() = default; void Button::SetTooltipText(const std::u16string& tooltip_text) { if (tooltip_text == tooltip_text_) return; if (GetAccessibleName().empty() || GetAccessibleName() == tooltip_text_) { SetAccessibleName(tooltip_text); } tooltip_text_ = tooltip_text; OnSetTooltipText(tooltip_text); TooltipTextChanged(); OnPropertyChanged(&tooltip_text_, kPropertyEffectsNone); } std::u16string Button::GetTooltipText() const { return tooltip_text_; } void Button::SetCallback(PressedCallback callback) { callback_ = std::move(callback); } void Button::AdjustAccessibleName(std::u16string& new_name, ax::mojom::NameFrom& name_from) { if (new_name.empty()) { new_name = tooltip_text_; } } Button::ButtonState Button::GetState() const { return state_; } void Button::SetState(ButtonState state) { if (state == state_) return; if (animate_on_state_change_) { if ((state_ == STATE_HOVERED) && (state == STATE_NORMAL)) { // For HOVERED -> NORMAL, animate from hovered (1) to not hovered (0). hover_animation_.Hide(); } else if (state != STATE_HOVERED) { // For HOVERED -> PRESSED/DISABLED, or any transition not involving // HOVERED at all, simply set the state to not hovered (0). hover_animation_.Reset(); } else if (state_ == STATE_NORMAL) { // For NORMAL -> HOVERED, animate from not hovered (0) to hovered (1). hover_animation_.Show(); } else { // For PRESSED/DISABLED -> HOVERED, simply set the state to hovered (1). hover_animation_.Reset(1); } } ButtonState old_state = state_; state_ = state; StateChanged(old_state); OnPropertyChanged(&state_, kPropertyEffectsPaint); } int Button::GetTag() const { return tag_; } void Button::SetTag(int tag) { if (tag_ == tag) return; tag_ = tag; OnPropertyChanged(&tag_, kPropertyEffectsNone); } void Button::SetAnimationDuration(base::TimeDelta duration) { hover_animation_.SetSlideDuration(duration); } void Button::SetTriggerableEventFlags(int triggerable_event_flags) { if (triggerable_event_flags == triggerable_event_flags_) return; triggerable_event_flags_ = triggerable_event_flags; OnPropertyChanged(&triggerable_event_flags_, kPropertyEffectsNone); } int Button::GetTriggerableEventFlags() const { return triggerable_event_flags_; } void Button::SetRequestFocusOnPress(bool value) { // On Mac, buttons should not request focus on a mouse press. Hence keep the // default value i.e. false. #if !BUILDFLAG(IS_MAC) if (request_focus_on_press_ == value) return; request_focus_on_press_ = value; OnPropertyChanged(&request_focus_on_press_, kPropertyEffectsNone); #endif } bool Button::GetRequestFocusOnPress() const { return request_focus_on_press_; } void Button::SetAnimateOnStateChange(bool value) { if (value == animate_on_state_change_) return; animate_on_state_change_ = value; OnPropertyChanged(&animate_on_state_change_, kPropertyEffectsNone); } bool Button::GetAnimateOnStateChange() const { return animate_on_state_change_; } void Button::SetHideInkDropWhenShowingContextMenu(bool value) { if (value == hide_ink_drop_when_showing_context_menu_) return; hide_ink_drop_when_showing_context_menu_ = value; OnPropertyChanged(&hide_ink_drop_when_showing_context_menu_, kPropertyEffectsNone); } bool Button::GetHideInkDropWhenShowingContextMenu() const { return hide_ink_drop_when_showing_context_menu_; } void Button::SetShowInkDropWhenHotTracked(bool value) { if (value == show_ink_drop_when_hot_tracked_) return; show_ink_drop_when_hot_tracked_ = value; OnPropertyChanged(&show_ink_drop_when_hot_tracked_, kPropertyEffectsNone); } bool Button::GetShowInkDropWhenHotTracked() const { return show_ink_drop_when_hot_tracked_; } void Button::SetHasInkDropActionOnClick(bool value) { if (value == has_ink_drop_action_on_click_) return; has_ink_drop_action_on_click_ = value; OnPropertyChanged(&has_ink_drop_action_on_click_, kPropertyEffectsNone); } bool Button::GetHasInkDropActionOnClick() const { return has_ink_drop_action_on_click_; } void Button::SetInstallFocusRingOnFocus(bool install) { if (install == GetInstallFocusRingOnFocus()) return; if (install) { FocusRing::Install(this); } else { FocusRing::Remove(this); } } bool Button::GetInstallFocusRingOnFocus() const { return FocusRing::Get(this) != nullptr; } void Button::SetHotTracked(bool is_hot_tracked) { if (state_ != STATE_DISABLED) { SetState(is_hot_tracked ? STATE_HOVERED : STATE_NORMAL); if (show_ink_drop_when_hot_tracked_) { InkDrop::Get(ink_drop_view_) ->AnimateToState(is_hot_tracked ? views::InkDropState::ACTIVATED : views::InkDropState::HIDDEN, nullptr); } } if (is_hot_tracked) NotifyAccessibilityEvent(ax::mojom::Event::kHover, true); } bool Button::IsHotTracked() const { return state_ == STATE_HOVERED; } void Button::SetFocusPainter(std::unique_ptr<Painter> focus_painter) { focus_painter_ = std::move(focus_painter); } void Button::SetHighlighted(bool highlighted) { InkDrop::Get(ink_drop_view_) ->AnimateToState(highlighted ? views::InkDropState::ACTIVATED : views::InkDropState::DEACTIVATED, nullptr); } Button::ScopedAnchorHighlight Button::AddAnchorHighlight() { if (0 == anchor_count_++) { SetHighlighted(true); } return ScopedAnchorHighlight(GetWeakPtr()); } base::CallbackListSubscription Button::AddStateChangedCallback( PropertyChangedCallback callback) { return AddPropertyChangedCallback(&state_, std::move(callback)); } Button::KeyClickAction Button::GetKeyClickActionForEvent( const ui::KeyEvent& event) { if (event.key_code() == ui::VKEY_SPACE) return PlatformStyle::kKeyClickActionOnSpace; // Note that default buttons also have VKEY_RETURN installed as an accelerator // in LabelButton::SetIsDefault(). On platforms where // PlatformStyle::kReturnClicksFocusedControl, the logic here will take // precedence over that. if (event.key_code() == ui::VKEY_RETURN && PlatformStyle::kReturnClicksFocusedControl) return KeyClickAction::kOnKeyPress; return KeyClickAction::kNone; } void Button::SetButtonController( std::unique_ptr<ButtonController> button_controller) { button_controller_ = std::move(button_controller); } gfx::Point Button::GetMenuPosition() const { gfx::Rect lb = GetLocalBounds(); // Offset of the associated menu position. constexpr gfx::Vector2d kMenuOffset{-2, -4}; // The position of the menu depends on whether or not the locale is // right-to-left. gfx::Point menu_position(lb.right(), lb.bottom()); if (base::i18n::IsRTL()) menu_position.set_x(lb.x()); View::ConvertPointToScreen(this, &menu_position); if (base::i18n::IsRTL()) menu_position.Offset(-kMenuOffset.x(), kMenuOffset.y()); else menu_position += kMenuOffset; DCHECK(GetWidget()); const int max_x_coordinate = GetWidget()->GetWorkAreaBoundsInScreen().right() - 1; if (max_x_coordinate && max_x_coordinate <= menu_position.x()) menu_position.set_x(max_x_coordinate - 1); return menu_position; } void Button::SetInkDropView(View* view) { if (ink_drop_view_ == view) { return; } InkDrop::Remove(ink_drop_view_); ink_drop_view_ = view; } bool Button::OnMousePressed(const ui::MouseEvent& event) { return button_controller_->OnMousePressed(event); } bool Button::OnMouseDragged(const ui::MouseEvent& event) { if (state_ != STATE_DISABLED) { const bool should_enter_pushed = ShouldEnterPushedState(event); const bool should_show_pending = should_enter_pushed && button_controller_->notify_action() == ButtonController::NotifyAction::kOnRelease && !InDrag(); if (HitTestPoint(event.location())) { SetState(should_enter_pushed ? STATE_PRESSED : STATE_HOVERED); if (should_show_pending && InkDrop::Get(ink_drop_view_)->GetInkDrop()->GetTargetInkDropState() == views::InkDropState::HIDDEN) { InkDrop::Get(ink_drop_view_) ->AnimateToState(views::InkDropState::ACTION_PENDING, &event); } } else { SetState(STATE_NORMAL); if (should_show_pending && InkDrop::Get(ink_drop_view_)->GetInkDrop()->GetTargetInkDropState() == views::InkDropState::ACTION_PENDING) { InkDrop::Get(ink_drop_view_) ->AnimateToState(views::InkDropState::HIDDEN, &event); } } } return true; } void Button::OnMouseReleased(const ui::MouseEvent& event) { button_controller_->OnMouseReleased(event); } void Button::OnMouseCaptureLost() { // Starting a drag results in a MouseCaptureLost. Reset button state. // TODO(varkha): Reset the state even while in drag. The same logic may // applies everywhere so gather any feedback and update. if (state_ != STATE_DISABLED) SetState(STATE_NORMAL); InkDrop::Get(ink_drop_view_) ->AnimateToState(views::InkDropState::HIDDEN, nullptr /* event */); InkDrop::Get(ink_drop_view_)->GetInkDrop()->SetHovered(false); View::OnMouseCaptureLost(); } void Button::OnMouseEntered(const ui::MouseEvent& event) { button_controller_->OnMouseEntered(event); } void Button::OnMouseExited(const ui::MouseEvent& event) { button_controller_->OnMouseExited(event); } void Button::OnMouseMoved(const ui::MouseEvent& event) { button_controller_->OnMouseMoved(event); } bool Button::OnKeyPressed(const ui::KeyEvent& event) { return button_controller_->OnKeyPressed(event); } bool Button::OnKeyReleased(const ui::KeyEvent& event) { return button_controller_->OnKeyReleased(event); } void Button::OnGestureEvent(ui::GestureEvent* event) { button_controller_->OnGestureEvent(event); } bool Button::AcceleratorPressed(const ui::Accelerator& accelerator) { SetState(STATE_NORMAL); NotifyClick(accelerator.ToKeyEvent()); return true; } bool Button::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { // If this button is focused and the user presses space or enter, don't let // that be treated as an accelerator if there is a key click action // corresponding to it. return GetKeyClickActionForEvent(event) != KeyClickAction::kNone; } std::u16string Button::GetTooltipText(const gfx::Point& p) const { return tooltip_text_; } void Button::ShowContextMenu(const gfx::Point& p, ui::MenuSourceType source_type) { if (!context_menu_controller()) return; // We're about to show the context menu. Showing the context menu likely means // we won't get a mouse exited and reset state. Reset it now to be sure. if (state_ != STATE_DISABLED) SetState(STATE_NORMAL); if (hide_ink_drop_when_showing_context_menu_) { InkDrop::Get(ink_drop_view_)->GetInkDrop()->SetHovered(false); InkDrop::Get(ink_drop_view_) ->AnimateToState(InkDropState::HIDDEN, nullptr /* event */); } View::ShowContextMenu(p, source_type); } void Button::OnDragDone() { // Only reset the state to normal if the button isn't currently disabled // (since disabled buttons may still be able to be dragged). if (state_ != STATE_DISABLED) SetState(STATE_NORMAL); InkDrop::Get(ink_drop_view_) ->AnimateToState(InkDropState::HIDDEN, nullptr /* event */); } void Button::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); PaintButtonContents(canvas); Painter::PaintFocusPainter(this, canvas, focus_painter_.get()); } void Button::GetAccessibleNodeData(ui::AXNodeData* node_data) { View::GetAccessibleNodeData(node_data); if (!GetEnabled()) node_data->SetRestriction(ax::mojom::Restriction::kDisabled); switch (state_) { case STATE_HOVERED: node_data->AddState(ax::mojom::State::kHovered); break; case STATE_PRESSED: node_data->SetCheckedState(ax::mojom::CheckedState::kTrue); break; case STATE_DISABLED: node_data->SetRestriction(ax::mojom::Restriction::kDisabled); break; case STATE_NORMAL: case STATE_COUNT: // No additional accessibility node_data set for this button node_data. break; } if (GetEnabled()) node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kPress); button_controller_->UpdateAccessibleNodeData(node_data); } void Button::VisibilityChanged(View* starting_from, bool visible) { View::VisibilityChanged(starting_from, visible); if (state_ == STATE_DISABLED) return; SetState(visible && ShouldEnterHoveredState() ? STATE_HOVERED : STATE_NORMAL); } void Button::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) { if (!details.is_add && state_ != STATE_DISABLED && details.child == this) SetState(STATE_NORMAL); View::ViewHierarchyChanged(details); } void Button::OnFocus() { View::OnFocus(); if (focus_painter_) SchedulePaint(); } void Button::OnBlur() { View::OnBlur(); if (IsHotTracked() || state_ == STATE_PRESSED) { SetState(STATE_NORMAL); if (InkDrop::Get(ink_drop_view_)->GetInkDrop()->GetTargetInkDropState() != views::InkDropState::HIDDEN) { InkDrop::Get(ink_drop_view_) ->AnimateToState(views::InkDropState::HIDDEN, nullptr /* event */); } // TODO(bruthig) : Fix Buttons to work well when multiple input // methods are interacting with a button. e.g. By animating to HIDDEN here // it is possible for a Mouse Release to trigger an action however there // would be no visual cue to the user that this will occur. } if (focus_painter_) SchedulePaint(); } void Button::AnimationProgressed(const gfx::Animation* animation) { SchedulePaint(); } Button::Button(PressedCallback callback) : AnimationDelegateViews(this), callback_(std::move(callback)) { InkDrop::Install(this, std::make_unique<InkDropHost>(this)); SetFocusBehavior(PlatformStyle::kDefaultFocusBehavior); SetProperty(kIsButtonProperty, true); hover_animation_.SetSlideDuration(base::Milliseconds(150)); SetInstallFocusRingOnFocus(true); button_controller_ = std::make_unique<ButtonController>( this, std::make_unique<DefaultButtonControllerDelegate>(this)); InkDrop::Get(ink_drop_view_) ->SetCreateInkDropCallback(base::BindRepeating( [](Button* button) { std::unique_ptr<InkDrop> ink_drop = InkDrop::CreateInkDropForFloodFillRipple(InkDrop::Get(button)); ink_drop->SetShowHighlightOnFocus(!FocusRing::Get(button)); return ink_drop; }, base::Unretained(this))); // TODO(pbos): Investigate not setting a default color so that we can DCHECK // if one hasn't been set. InkDrop::Get(ink_drop_view_)->SetBaseColor(gfx::kPlaceholderColor); SetAccessibilityProperties(ax::mojom::Role::kButton); } void Button::RequestFocusFromEvent() { if (request_focus_on_press_) RequestFocus(); } void Button::NotifyClick(const ui::Event& event) { if (has_ink_drop_action_on_click_) { InkDrop::Get(ink_drop_view_) ->AnimateToState(InkDropState::ACTION_TRIGGERED, ui::LocatedEvent::FromIfValid(&event)); } // If we have an associated help context ID, notify that system that we have // been activated. const ui::ElementIdentifier element_id = GetProperty(kElementIdentifierKey); if (element_id) { views::ElementTrackerViews::GetInstance()->NotifyViewActivated(element_id, this); } if (callback_) callback_.Run(event); } void Button::OnClickCanceled(const ui::Event& event) { if (ShouldUpdateInkDropOnClickCanceled()) { if (InkDrop::Get(ink_drop_view_)->GetInkDrop()->GetTargetInkDropState() == views::InkDropState::ACTION_PENDING || InkDrop::Get(ink_drop_view_)->GetInkDrop()->GetTargetInkDropState() == views::InkDropState::ALTERNATE_ACTION_PENDING) { InkDrop::Get(ink_drop_view_) ->AnimateToState(views::InkDropState::HIDDEN, ui::LocatedEvent::FromIfValid(&event)); } } } void Button::OnSetTooltipText(const std::u16string& tooltip_text) {} void Button::StateChanged(ButtonState old_state) {} bool Button::IsTriggerableEvent(const ui::Event& event) { return button_controller_->IsTriggerableEvent(event); } bool Button::ShouldUpdateInkDropOnClickCanceled() const { return true; } bool Button::ShouldEnterPushedState(const ui::Event& event) { return IsTriggerableEvent(event); } void Button::PaintButtonContents(gfx::Canvas* canvas) {} bool Button::ShouldEnterHoveredState() { if (!GetVisible()) return false; bool check_mouse_position = true; #if defined(USE_AURA) // If another window has capture, we shouldn't check the current mouse // position because the button won't receive any mouse events - so if the // mouse was hovered, the button would be stuck in a hovered state (since it // would never receive OnMouseExited). const Widget* widget = GetWidget(); if (widget && widget->GetNativeWindow()) { aura::Window* root_window = widget->GetNativeWindow()->GetRootWindow(); aura::client::CaptureClient* capture_client = aura::client::GetCaptureClient(root_window); aura::Window* capture_window = capture_client ? capture_client->GetGlobalCaptureWindow() : nullptr; check_mouse_position = !capture_window || capture_window == root_window; } #endif return check_mouse_position && IsMouseHovered(); } base::WeakPtr<Button> Button::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void Button::OnEnabledChanged() { if (GetEnabled() ? (state_ != STATE_DISABLED) : (state_ == STATE_DISABLED)) return; if (GetEnabled()) { bool should_enter_hover_state = ShouldEnterHoveredState(); SetState(should_enter_hover_state ? STATE_HOVERED : STATE_NORMAL); InkDrop::Get(ink_drop_view_) ->GetInkDrop() ->SetHovered(should_enter_hover_state); } else { SetState(STATE_DISABLED); InkDrop::Get(ink_drop_view_)->GetInkDrop()->SetHovered(false); } } void Button::ReleaseAnchorHighlight() { if (0 == --anchor_count_) { SetHighlighted(false); } } BEGIN_METADATA(Button, View) ADD_PROPERTY_METADATA(PressedCallback, Callback) ADD_PROPERTY_METADATA(bool, AnimateOnStateChange) ADD_PROPERTY_METADATA(bool, HasInkDropActionOnClick) ADD_PROPERTY_METADATA(bool, HideInkDropWhenShowingContextMenu) ADD_PROPERTY_METADATA(bool, InstallFocusRingOnFocus) ADD_PROPERTY_METADATA(bool, RequestFocusOnPress) ADD_PROPERTY_METADATA(ButtonState, State) ADD_PROPERTY_METADATA(int, Tag) ADD_PROPERTY_METADATA(std::u16string, TooltipText) ADD_PROPERTY_METADATA(int, TriggerableEventFlags) END_METADATA } // namespace views DEFINE_ENUM_CONVERTERS(views::Button::ButtonState, {views::Button::STATE_NORMAL, u"STATE_NORMAL"}, {views::Button::STATE_HOVERED, u"STATE_HOVERED"}, {views::Button::STATE_PRESSED, u"STATE_PRESSED"}, {views::Button::STATE_DISABLED, u"STATE_DISABLED"})
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button.cc
C++
unknown
25,016
// 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_BUTTON_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_BUTTON_H_ #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "ui/events/event_constants.h" #include "ui/gfx/animation/throb_animation.h" #include "ui/native_theme/native_theme.h" #include "ui/views/animation/animation_delegate_views.h" #include "ui/views/animation/ink_drop_host.h" #include "ui/views/animation/ink_drop_state.h" #include "ui/views/controls/button/button_controller_delegate.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/painter.h" namespace views { namespace test { class ButtonTestApi; } class Button; class ButtonController; class Event; // A View representing a button. A Button is focusable by default and will // be part of the focus chain. class VIEWS_EXPORT Button : public View, public AnimationDelegateViews { public: // Button states for various button sub-types. enum ButtonState { STATE_NORMAL = 0, STATE_HOVERED, STATE_PRESSED, STATE_DISABLED, STATE_COUNT, }; // An enum describing the events on which a button should be clicked for a // given key event. enum class KeyClickAction { kOnKeyPress, kOnKeyRelease, kNone, }; // TODO(cyan): Consider having Button implement ButtonControllerDelegate. class VIEWS_EXPORT DefaultButtonControllerDelegate : public ButtonControllerDelegate { public: explicit DefaultButtonControllerDelegate(Button* button); DefaultButtonControllerDelegate(const DefaultButtonControllerDelegate&) = delete; DefaultButtonControllerDelegate& operator=( const DefaultButtonControllerDelegate&) = delete; ~DefaultButtonControllerDelegate() override; // views::ButtonControllerDelegate: void RequestFocusFromEvent() override; void NotifyClick(const ui::Event& event) override; void OnClickCanceled(const ui::Event& event) override; bool IsTriggerableEvent(const ui::Event& event) override; bool ShouldEnterPushedState(const ui::Event& event) override; bool ShouldEnterHoveredState() override; InkDrop* GetInkDrop() override; int GetDragOperations(const gfx::Point& press_pt) override; bool InDrag() override; }; // PressedCallback wraps a one-arg callback type with multiple constructors to // allow callers to specify a RepeatingClosure if they don't care about the // callback arg. // TODO(crbug.com/772945): Re-evaluate if this class can/should be converted // to a type alias + various helpers or overloads to support the // RepeatingClosure case. class VIEWS_EXPORT PressedCallback { public: using Callback = base::RepeatingCallback<void(const ui::Event& event)>; // 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. PressedCallback(Callback callback = Callback()); // NOLINT PressedCallback(base::RepeatingClosure closure); // NOLINT PressedCallback(const PressedCallback&); PressedCallback(PressedCallback&&); PressedCallback& operator=(const PressedCallback&); PressedCallback& operator=(PressedCallback&&); ~PressedCallback(); explicit operator bool() const { return !!callback_; } void Run(const ui::Event& event) { callback_.Run(event); } private: Callback callback_; }; // This is used to ensure that multiple overlapping elements anchored on this // button correctly handle highlighting. class VIEWS_EXPORT ScopedAnchorHighlight { public: explicit ScopedAnchorHighlight(base::WeakPtr<Button> button); ~ScopedAnchorHighlight(); ScopedAnchorHighlight(ScopedAnchorHighlight&&); ScopedAnchorHighlight& operator=(ScopedAnchorHighlight&&); private: base::WeakPtr<Button> button_; }; static constexpr ButtonState kButtonStates[STATE_COUNT] = { ButtonState::STATE_NORMAL, ButtonState::STATE_HOVERED, ButtonState::STATE_PRESSED, ButtonState::STATE_DISABLED}; METADATA_HEADER(Button); Button(const Button&) = delete; Button& operator=(const Button&) = delete; ~Button() override; static const Button* AsButton(const View* view); static Button* AsButton(View* view); static ButtonState GetButtonStateFrom(ui::NativeTheme::State state); void SetTooltipText(const std::u16string& tooltip_text); std::u16string GetTooltipText() const; // Tag is now a property. These accessors are deprecated. Use GetTag() and // SetTag() below or even better, use SetID()/GetID() from the ancestor. int tag() const { return tag_; } void set_tag(int tag) { tag_ = tag; } virtual void SetCallback(PressedCallback callback); void AdjustAccessibleName(std::u16string& new_name, ax::mojom::NameFrom& name_from) override; // Get/sets the current display state of the button. ButtonState GetState() const; // Clients passing in STATE_DISABLED should consider calling // SetEnabled(false) instead because the enabled flag can affect other things // like event dispatching, focus traversals, etc. Calling SetEnabled(false) // will also set the state of |this| to STATE_DISABLED. void SetState(ButtonState state); // Set how long the hover animation will last for. void SetAnimationDuration(base::TimeDelta duration); void SetTriggerableEventFlags(int triggerable_event_flags); int GetTriggerableEventFlags() const; // Sets whether |RequestFocus| should be invoked on a mouse press. The default // is false. void SetRequestFocusOnPress(bool value); bool GetRequestFocusOnPress() const; // See description above field. void SetAnimateOnStateChange(bool value); bool GetAnimateOnStateChange() const; void SetHideInkDropWhenShowingContextMenu(bool value); bool GetHideInkDropWhenShowingContextMenu() const; void SetShowInkDropWhenHotTracked(bool value); bool GetShowInkDropWhenHotTracked() const; void SetHasInkDropActionOnClick(bool value); bool GetHasInkDropActionOnClick() const; void SetInstallFocusRingOnFocus(bool install_focus_ring_on_focus); bool GetInstallFocusRingOnFocus() const; void SetHotTracked(bool is_hot_tracked); bool IsHotTracked() const; // TODO(crbug/1266066): These property accessors and tag_ field should be // removed and use SetID()/GetID from the ancestor View class. void SetTag(int value); int GetTag() const; void SetFocusPainter(std::unique_ptr<Painter> focus_painter); // Highlights the ink drop for the button. void SetHighlighted(bool highlighted); // Menus, bubbles, and IPH should call this when they anchor. This ensures // that highlighting is handled correctly with multiple anchored elements. // TODO(crbug/1428097): Migrate callers of SetHighlighted to this function, // where appropriate. ScopedAnchorHighlight AddAnchorHighlight(); base::CallbackListSubscription AddStateChangedCallback( PropertyChangedCallback callback); // 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 OnMouseCaptureLost() override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; void OnMouseMoved(const ui::MouseEvent& event) override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnKeyReleased(const ui::KeyEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; bool AcceleratorPressed(const ui::Accelerator& accelerator) override; bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override; std::u16string GetTooltipText(const gfx::Point& p) const override; void ShowContextMenu(const gfx::Point& p, ui::MenuSourceType source_type) override; void OnDragDone() override; // Instead of overriding this, subclasses that want custom painting should use // PaintButtonContents. void OnPaint(gfx::Canvas* canvas) final; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void VisibilityChanged(View* starting_from, bool is_visible) override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; void OnFocus() override; void OnBlur() override; // Overridden from views::AnimationDelegateViews: void AnimationProgressed(const gfx::Animation* animation) override; // Returns the click action for the given key event. // Subclasses may override this method to support default actions for key // events. // TODO(cyan): Move this into the ButtonController. virtual KeyClickAction GetKeyClickActionForEvent(const ui::KeyEvent& event); ButtonController* button_controller() const { return button_controller_.get(); } void SetButtonController(std::unique_ptr<ButtonController> button_controller); gfx::Point GetMenuPosition() const; View* ink_drop_view() const { return ink_drop_view_; } void SetInkDropView(View* view); protected: explicit Button(PressedCallback callback = PressedCallback()); // Called when the button has been clicked or tapped and should request focus // if necessary. virtual void RequestFocusFromEvent(); // Cause the button to notify the listener that a click occurred. virtual void NotifyClick(const ui::Event& event); // Called when a button gets released without triggering an action. // Note: This is only wired up for mouse button events and not gesture // events. virtual void OnClickCanceled(const ui::Event& event); // Called when the tooltip is set. virtual void OnSetTooltipText(const std::u16string& tooltip_text); // Invoked from SetState() when SetState() is passed a value that differs from // the current node_data. Button's implementation of StateChanged() does // nothing; this method is provided for subclasses that wish to do something // on state changes. virtual void StateChanged(ButtonState old_state); // Returns true if the event is one that can trigger notifying the listener. // This implementation returns true if the left mouse button is down. // TODO(cyan): Remove this method and move the implementation into // ButtonController. virtual bool IsTriggerableEvent(const ui::Event& event); // Returns true if the ink drop should be updated by Button when // OnClickCanceled() is called. This method is provided for subclasses. // If the method is overriden and returns false, the subclass is responsible // will be responsible for updating the ink drop. virtual bool ShouldUpdateInkDropOnClickCanceled() const; // Returns true if the button should become pressed when the user // holds the mouse down over the button. For this implementation, // we simply return IsTriggerableEvent(event). virtual bool ShouldEnterPushedState(const ui::Event& event); // Override to paint custom button contents. Any background or border set on // the view will be painted before this is called and |focus_painter_| will be // painted afterwards. virtual void PaintButtonContents(gfx::Canvas* canvas); // Returns true if the button should enter hovered state; that is, if the // mouse is over the button, and no other window has capture (which would // prevent the button from receiving MouseExited events and updating its // node_data). This does not take into account enabled node_data. bool ShouldEnterHoveredState(); const gfx::ThrobAnimation& hover_animation() const { return hover_animation_; } // Getter used by metadata only. const PressedCallback& GetCallback() const { return callback_; } base::WeakPtr<Button> GetWeakPtr(); private: friend class test::ButtonTestApi; friend class ScopedAnchorHighlight; FRIEND_TEST_ALL_PREFIXES(BlueButtonTest, Border); void OnEnabledChanged(); void ReleaseAnchorHighlight(); // The text shown in a tooltip. std::u16string tooltip_text_; // The button's listener. Notified when clicked. PressedCallback callback_; // The id tag associated with this button. Used to disambiguate buttons. // TODO(pbos): See if this can be removed, e.g. by replacing with SetID(). int tag_ = -1; ButtonState state_ = STATE_NORMAL; gfx::ThrobAnimation hover_animation_{this}; // Should we animate when the state changes? bool animate_on_state_change_ = false; // Mouse event flags which can trigger button actions. int triggerable_event_flags_ = ui::EF_LEFT_MOUSE_BUTTON; // See description above setter. bool request_focus_on_press_ = false; // True when a button click should trigger an animation action on // ink_drop_delegate(). bool has_ink_drop_action_on_click_ = false; // When true, the ink drop ripple and hover will be hidden prior to showing // the context menu. bool hide_ink_drop_when_showing_context_menu_ = true; // When true, the ink drop ripple will be shown when setting state to hot // tracked with SetHotTracked(). bool show_ink_drop_when_hot_tracked_ = false; // |ink_drop_view_| is generally the button, but can be overridden for special // cases (e.g. Checkbox) where the InkDrop may be more appropriately installed // on a child view of the button. raw_ptr<View> ink_drop_view_ = this; std::unique_ptr<Painter> focus_painter_; // ButtonController is responsible for handling events sent to the Button and // related state changes from the events. // TODO(cyan): Make sure all state changes are handled within // ButtonController. std::unique_ptr<ButtonController> button_controller_; base::CallbackListSubscription enabled_changed_subscription_{ AddEnabledChangedCallback(base::BindRepeating(&Button::OnEnabledChanged, base::Unretained(this)))}; size_t anchor_count_ = 0; base::WeakPtrFactory<Button> weak_ptr_factory_{this}; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Button, View) VIEW_BUILDER_PROPERTY(Button::PressedCallback, Callback) VIEW_BUILDER_PROPERTY(base::TimeDelta, AnimationDuration) VIEW_BUILDER_PROPERTY(bool, AnimateOnStateChange) VIEW_BUILDER_PROPERTY(bool, HasInkDropActionOnClick) VIEW_BUILDER_PROPERTY(bool, HideInkDropWhenShowingContextMenu) VIEW_BUILDER_PROPERTY(bool, InstallFocusRingOnFocus) VIEW_BUILDER_PROPERTY(bool, RequestFocusOnPress) VIEW_BUILDER_PROPERTY(Button::ButtonState, State) VIEW_BUILDER_PROPERTY(int, Tag) VIEW_BUILDER_PROPERTY(std::u16string, TooltipText) VIEW_BUILDER_PROPERTY(int, TriggerableEventFlags) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Button) #endif // UI_VIEWS_CONTROLS_BUTTON_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button.h
C++
unknown
14,989
// 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/button/button_controller.h" #include <memory> #include <utility> #include "ui/accessibility/ax_node_data.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/controls/button/button_controller_delegate.h" namespace views { ButtonController::ButtonController( Button* button, std::unique_ptr<ButtonControllerDelegate> delegate) : button_(button), button_controller_delegate_(std::move(delegate)) {} ButtonController::~ButtonController() = default; bool ButtonController::OnMousePressed(const ui::MouseEvent& event) { if (button_->GetState() == Button::STATE_DISABLED) return true; if (button_->GetState() != Button::STATE_PRESSED && button_controller_delegate_->ShouldEnterPushedState(event) && button_->HitTestPoint(event.location())) { button_->SetState(Button::STATE_PRESSED); InkDrop::Get(button()->ink_drop_view()) ->AnimateToState(views::InkDropState::ACTION_PENDING, &event); } button_controller_delegate_->RequestFocusFromEvent(); if (button_controller_delegate_->IsTriggerableEvent(event) && notify_action_ == ButtonController::NotifyAction::kOnPress) { button_controller_delegate_->NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). } return true; } void ButtonController::OnMouseReleased(const ui::MouseEvent& event) { if (button_->GetState() != Button::STATE_DISABLED) { if (!button_->HitTestPoint(event.location())) { button_->SetState(Button::STATE_NORMAL); } else { button_->SetState(Button::STATE_HOVERED); if (button_controller_delegate_->IsTriggerableEvent(event) && notify_action_ == ButtonController::NotifyAction::kOnRelease) { button_controller_delegate_->NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). return; } } } if (notify_action_ == ButtonController::NotifyAction::kOnRelease) button_controller_delegate_->OnClickCanceled(event); } void ButtonController::OnMouseMoved(const ui::MouseEvent& event) { if (button_->GetState() != Button::STATE_DISABLED) { button_->SetState(button_->HitTestPoint(event.location()) ? Button::STATE_HOVERED : Button::STATE_NORMAL); } } void ButtonController::OnMouseEntered(const ui::MouseEvent& event) { if (button_->GetState() != Button::STATE_DISABLED) button_->SetState(Button::STATE_HOVERED); } void ButtonController::OnMouseExited(const ui::MouseEvent& event) { // Starting a drag results in a MouseExited, we need to ignore it. if (button_->GetState() != Button::STATE_DISABLED && !button_controller_delegate_->InDrag()) button_->SetState(Button::STATE_NORMAL); } bool ButtonController::OnKeyPressed(const ui::KeyEvent& event) { if (button_->GetState() == Button::STATE_DISABLED) return false; switch (button_->GetKeyClickActionForEvent(event)) { case Button::KeyClickAction::kOnKeyRelease: button_->SetState(Button::STATE_PRESSED); if (button_controller_delegate_->GetInkDrop()->GetTargetInkDropState() != InkDropState::ACTION_PENDING) { InkDrop::Get(button()->ink_drop_view()) ->AnimateToState(InkDropState::ACTION_PENDING, nullptr /* event */); } return true; case Button::KeyClickAction::kOnKeyPress: button_->SetState(Button::STATE_NORMAL); button_controller_delegate_->NotifyClick(event); return true; case Button::KeyClickAction::kNone: return false; } NOTREACHED_NORETURN(); } bool ButtonController::OnKeyReleased(const ui::KeyEvent& event) { const bool click_button = button_->GetState() == Button::STATE_PRESSED && button_->GetKeyClickActionForEvent(event) == Button::KeyClickAction::kOnKeyRelease; if (!click_button) return false; button_->SetState(Button::STATE_NORMAL); button_controller_delegate_->NotifyClick(event); return true; } void ButtonController::OnGestureEvent(ui::GestureEvent* event) { if (button_->GetState() == Button::STATE_DISABLED) return; if (event->type() == ui::ET_GESTURE_TAP && button_controller_delegate_->IsTriggerableEvent(*event)) { // A GESTURE_END event is issued immediately after ET_GESTURE_TAP and will // set the state to STATE_NORMAL beginning the fade out animation. button_->SetState(Button::STATE_HOVERED); button_controller_delegate_->NotifyClick(*event); event->SetHandled(); } else if (event->type() == ui::ET_GESTURE_TAP_DOWN && button_controller_delegate_->ShouldEnterPushedState(*event)) { button_->SetState(Button::STATE_PRESSED); button_controller_delegate_->RequestFocusFromEvent(); event->SetHandled(); } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL || event->type() == ui::ET_GESTURE_END) { button_->SetState(Button::STATE_NORMAL); } } void ButtonController::UpdateAccessibleNodeData(ui::AXNodeData* node_data) {} bool ButtonController::IsTriggerableEvent(const ui::Event& event) { return event.type() == ui::ET_GESTURE_TAP_DOWN || event.type() == ui::ET_GESTURE_TAP || (event.IsMouseEvent() && (button_->GetTriggerableEventFlags() & event.flags()) != 0); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button_controller.cc
C++
unknown
5,556
// 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_BUTTON_BUTTON_CONTROLLER_H_ #define UI_VIEWS_CONTROLS_BUTTON_BUTTON_CONTROLLER_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "ui/events/event.h" #include "ui/views/controls/button/button.h" namespace views { // Handles logic not related to the visual aspects of a Button such as event // handling and state changes. class VIEWS_EXPORT ButtonController { public: ButtonController(Button* button, std::unique_ptr<ButtonControllerDelegate> delegate); ButtonController(const ButtonController&) = delete; ButtonController& operator=(const ButtonController&) = delete; virtual ~ButtonController(); // An enum describing the events on which a button should notify its listener. enum class NotifyAction { kOnPress, kOnRelease, }; Button* button() { return button_; } // Sets the event on which the button's listener should be notified. void set_notify_action(NotifyAction notify_action) { notify_action_ = notify_action; } NotifyAction notify_action() const { return notify_action_; } // Methods that parallel View::On<Event> handlers: virtual bool OnMousePressed(const ui::MouseEvent& event); virtual void OnMouseReleased(const ui::MouseEvent& event); virtual void OnMouseMoved(const ui::MouseEvent& event); virtual void OnMouseEntered(const ui::MouseEvent& event); virtual void OnMouseExited(const ui::MouseEvent& event); virtual bool OnKeyPressed(const ui::KeyEvent& event); virtual bool OnKeyReleased(const ui::KeyEvent& event); virtual void OnGestureEvent(ui::GestureEvent* event); // Updates |node_data| for a button based on the functionality. virtual void UpdateAccessibleNodeData(ui::AXNodeData* node_data); // Methods that parallel respective methods in Button: virtual bool IsTriggerableEvent(const ui::Event& event); protected: ButtonControllerDelegate* delegate() { return button_controller_delegate_.get(); } private: const raw_ptr<Button> button_; // TODO(cyan): Remove |button_| and access everything via the delegate. std::unique_ptr<ButtonControllerDelegate> button_controller_delegate_; // The event on which the button's listener should be notified. NotifyAction notify_action_ = NotifyAction::kOnRelease; }; } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_BUTTON_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button_controller.h
C++
unknown
2,508
// 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_BUTTON_BUTTON_CONTROLLER_DELEGATE_H_ #define UI_VIEWS_CONTROLS_BUTTON_BUTTON_CONTROLLER_DELEGATE_H_ #include "base/memory/raw_ptr.h" namespace views { class Button; // Captures the Button and View methods required for sharing the logic in // ButtonController between different Button types. class VIEWS_EXPORT ButtonControllerDelegate { public: explicit ButtonControllerDelegate(Button* button) : button_(button) {} ButtonControllerDelegate(const ButtonControllerDelegate&) = delete; ButtonControllerDelegate& operator=(const ButtonControllerDelegate&) = delete; virtual ~ButtonControllerDelegate() = default; // Parallels methods in views::Button: virtual void RequestFocusFromEvent() = 0; virtual void NotifyClick(const ui::Event& event) = 0; virtual void OnClickCanceled(const ui::Event& event) = 0; virtual bool IsTriggerableEvent(const ui::Event& event) = 0; virtual bool ShouldEnterPushedState(const ui::Event& event) = 0; virtual bool ShouldEnterHoveredState() = 0; // Parallels method views::InkDropEventHandler::GetInkDrop: virtual InkDrop* GetInkDrop() = 0; // Parallels methods in views::View: virtual int GetDragOperations(const gfx::Point& press_pt) = 0; virtual bool InDrag() = 0; protected: Button* button() { return button_; } private: raw_ptr<Button> button_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_BUTTON_CONTROLLER_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button_controller_delegate.h
C++
unknown
1,590
// 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/button.h" #include <memory> #include <string> #include <utility> #include "base/functional/bind.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "build/build_config.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/layout.h" #include "ui/display/screen.h" #include "ui/events/event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/views/animation/ink_drop_host.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/test/ink_drop_host_test_api.h" #include "ui/views/animation/test/test_ink_drop.h" #include "ui/views/animation/test/test_ink_drop_host.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/link.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/view_metadata_test_utils.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget_utils.h" #if defined(USE_AURA) #include "ui/aura/test/test_cursor_client.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #endif namespace views { using test::InkDropHostTestApi; using test::TestInkDrop; namespace { // 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 {} }; class TestButton : public Button { public: explicit TestButton(bool has_ink_drop_action_on_click) : Button(base::BindRepeating([](bool* pressed) { *pressed = true; }, &pressed_)) { SetHasInkDropActionOnClick(has_ink_drop_action_on_click); } TestButton(const TestButton&) = delete; TestButton& operator=(const TestButton&) = delete; ~TestButton() override = default; KeyClickAction GetKeyClickActionForEvent(const ui::KeyEvent& event) override { if (custom_key_click_action_ == KeyClickAction::kNone) return Button::GetKeyClickActionForEvent(event); return custom_key_click_action_; } // Button: void OnClickCanceled(const ui::Event& event) override { canceled_ = true; } bool pressed() const { return pressed_; } bool canceled() const { return canceled_; } void set_custom_key_click_action(KeyClickAction custom_key_click_action) { custom_key_click_action_ = custom_key_click_action; } void Reset() { pressed_ = false; canceled_ = false; } // Raised visibility of OnFocus() to public using Button::OnFocus; private: bool pressed_ = false; bool canceled_ = false; KeyClickAction custom_key_click_action_ = KeyClickAction::kNone; }; class TestButtonObserver { public: explicit TestButtonObserver(Button* button) { highlighted_changed_subscription_ = InkDrop::Get(button)->AddHighlightedChangedCallback(base::BindRepeating( [](TestButtonObserver* obs) { obs->highlighted_changed_ = true; }, base::Unretained(this))); state_changed_subscription_ = button->AddStateChangedCallback(base::BindRepeating( [](TestButtonObserver* obs) { obs->state_changed_ = true; }, base::Unretained(this))); } TestButtonObserver(const TestButtonObserver&) = delete; TestButtonObserver& operator=(const TestButtonObserver&) = delete; ~TestButtonObserver() = default; void Reset() { highlighted_changed_ = false; state_changed_ = false; } bool highlighted_changed() const { return highlighted_changed_; } bool state_changed() const { return state_changed_; } private: bool highlighted_changed_ = false; bool state_changed_ = false; base::CallbackListSubscription highlighted_changed_subscription_; base::CallbackListSubscription state_changed_subscription_; }; TestInkDrop* AddTestInkDrop(TestButton* button) { auto owned_ink_drop = std::make_unique<TestInkDrop>(); TestInkDrop* ink_drop = owned_ink_drop.get(); InkDrop::Get(button)->SetMode(views::InkDropHost::InkDropMode::ON); InkDropHostTestApi(InkDrop::Get(button)) .SetInkDrop(std::move(owned_ink_drop)); return ink_drop; } } // namespace class ButtonTest : public ViewsTestBase { public: ButtonTest() = default; ButtonTest(const ButtonTest&) = delete; ButtonTest& operator=(const ButtonTest&) = delete; ~ButtonTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); // Create a widget so that the Button 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<TestButton>(false)); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget())); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } TestInkDrop* CreateButtonWithInkDrop(bool has_ink_drop_action_on_click) { button_ = widget()->SetContentsView( std::make_unique<TestButton>(has_ink_drop_action_on_click)); return AddTestInkDrop(button_); } void CreateButtonWithObserver() { button_ = widget()->SetContentsView(std::make_unique<TestButton>(false)); InkDrop::Get(button_)->SetMode(views::InkDropHost::InkDropMode::ON); button_observer_ = std::make_unique<TestButtonObserver>(button_); } protected: Widget* widget() { return widget_.get(); } TestButton* button() { return button_; } TestButtonObserver* button_observer() { return button_observer_.get(); } ui::test::EventGenerator* event_generator() { return event_generator_.get(); } void SetDraggedView(View* dragged_view) { widget_->dragged_view_ = dragged_view; } private: std::unique_ptr<Widget> widget_; raw_ptr<TestButton> button_; std::unique_ptr<TestButtonObserver> button_observer_; std::unique_ptr<ui::test::EventGenerator> event_generator_; }; // Iterate through the metadata for Button to ensure it all works. TEST_F(ButtonTest, MetadataTest) { test::TestViewMetadata(button()); } // Tests that hover state changes correctly when visibility/enableness changes. TEST_F(ButtonTest, HoverStateOnVisibilityChange) { event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); event_generator()->PressLeftButton(); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); event_generator()->ReleaseLeftButton(); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); button()->SetEnabled(false); EXPECT_EQ(Button::STATE_DISABLED, button()->GetState()); button()->SetEnabled(true); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); button()->SetVisible(false); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetVisible(true); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); #if defined(USE_AURA) { // If another widget has capture, the button should ignore mouse position // and not enter hovered state. Widget second_widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(700, 700, 10, 10); second_widget.Init(std::move(params)); second_widget.Show(); second_widget.GetNativeWindow()->SetCapture(); button()->SetEnabled(false); EXPECT_EQ(Button::STATE_DISABLED, button()->GetState()); button()->SetEnabled(true); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetVisible(false); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetVisible(true); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); } #endif // Disabling cursor events occurs for touch events and the Ash magnifier. There // is no touch on desktop Mac. Tracked in http://crbug.com/445520. #if !BUILDFLAG(IS_MAC) || defined(USE_AURA) aura::test::TestCursorClient cursor_client(GetRootWindow(widget())); // In Aura views, no new hover effects are invoked if mouse events // are disabled. cursor_client.DisableMouseEvents(); button()->SetEnabled(false); EXPECT_EQ(Button::STATE_DISABLED, button()->GetState()); button()->SetEnabled(true); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetVisible(false); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetVisible(true); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); #endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA) } // Tests that the hover state is preserved during a view hierarchy update of a // button's child View. TEST_F(ButtonTest, HoverStatePreservedOnDescendantViewHierarchyChange) { event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); Label* child = new Label(std::u16string()); button()->AddChildView(child); delete child; EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); } // Tests the different types of NotifyActions. TEST_F(ButtonTest, NotifyAction) { gfx::Point center(10, 10); // By default the button should notify the callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); EXPECT_FALSE(button()->pressed()); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); EXPECT_TRUE(button()->pressed()); // Set the notify action to happen on mouse press. button()->Reset(); button()->button_controller()->set_notify_action( ButtonController::NotifyAction::kOnPress); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); EXPECT_TRUE(button()->pressed()); // The button should no longer notify on mouse release. button()->Reset(); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); EXPECT_FALSE(button()->pressed()); } // Tests that OnClickCanceled gets called when NotifyClick is not expected // anymore. TEST_F(ButtonTest, NotifyActionNoClick) { gfx::Point center(10, 10); // By default the button should notify the callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); EXPECT_FALSE(button()->canceled()); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); EXPECT_TRUE(button()->canceled()); // Set the notify action to happen on mouse press. button()->Reset(); button()->button_controller()->set_notify_action( ButtonController::NotifyAction::kOnPress); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); // OnClickCanceled is only sent on mouse release. EXPECT_FALSE(button()->canceled()); // The button should no longer notify on mouse release. button()->Reset(); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); EXPECT_FALSE(button()->canceled()); } // No touch on desktop Mac. Tracked in http://crbug.com/445520. #if !BUILDFLAG(IS_MAC) || defined(USE_AURA) namespace { void PerformGesture(Button* button, ui::EventType event_type) { ui::GestureEventDetails gesture_details(event_type); ui::GestureEvent gesture_event(0, 0, 0, base::TimeTicks(), gesture_details); button->OnGestureEvent(&gesture_event); } } // namespace // Tests that gesture events correctly change the button state. TEST_F(ButtonTest, GestureEventsSetState) { aura::test::TestCursorClient cursor_client(GetRootWindow(widget())); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); PerformGesture(button(), ui::ET_GESTURE_TAP_DOWN); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); PerformGesture(button(), ui::ET_GESTURE_SHOW_PRESS); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); PerformGesture(button(), ui::ET_GESTURE_TAP_CANCEL); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); } // Tests that if the button was disabled in its button press handler, gesture // events will not revert the disabled state back to normal. // https://crbug.com/1084241. TEST_F(ButtonTest, GestureEventsRespectDisabledState) { button()->SetCallback(base::BindRepeating( [](TestButton* button) { button->SetEnabled(false); }, button())); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); event_generator()->GestureTapAt(button()->GetBoundsInScreen().CenterPoint()); EXPECT_EQ(Button::STATE_DISABLED, button()->GetState()); } #endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA) // Ensure subclasses of Button are correctly recognized as Button. TEST_F(ButtonTest, AsButton) { std::u16string text; LabelButton label_button(Button::PressedCallback(), text); EXPECT_TRUE(Button::AsButton(&label_button)); ImageButton image_button; EXPECT_TRUE(Button::AsButton(&image_button)); Checkbox checkbox(text); EXPECT_TRUE(Button::AsButton(&checkbox)); RadioButton radio_button(text, 0); EXPECT_TRUE(Button::AsButton(&radio_button)); MenuButton menu_button(Button::PressedCallback(), text); EXPECT_TRUE(Button::AsButton(&menu_button)); ToggleButton toggle_button; EXPECT_TRUE(Button::AsButton(&toggle_button)); Label label; EXPECT_FALSE(Button::AsButton(&label)); Link link; EXPECT_FALSE(Button::AsButton(&link)); Textfield textfield; EXPECT_FALSE(Button::AsButton(&textfield)); } // Tests that pressing a button shows the ink drop and releasing the button // does not hide the ink drop. // Note: Ink drop is not hidden upon release because Button descendants // may enter a different ink drop state. TEST_F(ButtonTest, ButtonClickTogglesInkDrop) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); event_generator()->PressLeftButton(); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); event_generator()->ReleaseLeftButton(); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); } // Tests that pressing a button shows and releasing capture hides ink drop. // Releasing capture should also reset PRESSED button state to NORMAL. TEST_F(ButtonTest, CaptureLossHidesInkDrop) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); event_generator()->PressLeftButton(); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); EXPECT_EQ(Button::ButtonState::STATE_PRESSED, button()->GetState()); SetDraggedView(button()); widget()->SetCapture(button()); widget()->ReleaseCapture(); SetDraggedView(nullptr); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); EXPECT_EQ(Button::ButtonState::STATE_NORMAL, button()->GetState()); } TEST_F(ButtonTest, HideInkDropWhenShowingContextMenu) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); TestContextMenuController context_menu_controller; button()->set_context_menu_controller(&context_menu_controller); button()->SetHideInkDropWhenShowingContextMenu(true); ink_drop->SetHovered(true); ink_drop->AnimateToState(InkDropState::ACTION_PENDING); button()->ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE); EXPECT_FALSE(ink_drop->is_hovered()); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, DontHideInkDropWhenShowingContextMenu) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); TestContextMenuController context_menu_controller; button()->set_context_menu_controller(&context_menu_controller); button()->SetHideInkDropWhenShowingContextMenu(false); ink_drop->SetHovered(true); ink_drop->AnimateToState(InkDropState::ACTION_PENDING); button()->ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE); EXPECT_TRUE(ink_drop->is_hovered()); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, HideInkDropOnBlur) { gfx::Point center(10, 10); TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); button()->OnFocus(); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); button()->OnBlur(); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_TRUE(button()->pressed()); } TEST_F(ButtonTest, HideInkDropHighlightOnDisable) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(ink_drop->is_hovered()); button()->SetEnabled(false); EXPECT_FALSE(ink_drop->is_hovered()); button()->SetEnabled(true); EXPECT_TRUE(ink_drop->is_hovered()); } TEST_F(ButtonTest, InkDropAfterTryingToShowContextMenu) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); button()->set_context_menu_controller(nullptr); ink_drop->SetHovered(true); ink_drop->AnimateToState(InkDropState::ACTION_PENDING); button()->ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE); EXPECT_TRUE(ink_drop->is_hovered()); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, HideInkDropHighlightWhenRemoved) { View* contents_view = widget()->SetContentsView(std::make_unique<View>()); TestButton* button = contents_view->AddChildView(std::make_unique<TestButton>(false)); button->SetBounds(0, 0, 200, 200); TestInkDrop* ink_drop = AddTestInkDrop(button); // Make sure that the button ink drop is hidden after the button gets removed. event_generator()->MoveMouseTo(button->GetBoundsInScreen().origin()); event_generator()->MoveMouseBy(2, 2); EXPECT_TRUE(ink_drop->is_hovered()); // Set ink-drop state to ACTIVATED to make sure that removing the container // sets it back to HIDDEN. ink_drop->AnimateToState(InkDropState::ACTIVATED); auto owned_button = contents_view->RemoveChildViewT(button); button = nullptr; EXPECT_FALSE(ink_drop->is_hovered()); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); // Make sure hiding the ink drop happens even if the button is indirectly // being removed. View* parent_view = contents_view->AddChildView(std::make_unique<View>()); parent_view->SetBounds(0, 0, 400, 400); button = parent_view->AddChildView(std::move(owned_button)); // Trigger hovering and then remove from the indirect parent. This should // propagate down to Button which should remove the highlight effect. EXPECT_FALSE(ink_drop->is_hovered()); event_generator()->MoveMouseBy(8, 8); EXPECT_TRUE(ink_drop->is_hovered()); // Set ink-drop state to ACTIVATED to make sure that removing the container // sets it back to HIDDEN. ink_drop->AnimateToState(InkDropState::ACTIVATED); auto owned_parent = contents_view->RemoveChildViewT(parent_view); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); EXPECT_FALSE(ink_drop->is_hovered()); } // Tests that when button is set to notify on release, dragging mouse out and // back transitions ink drop states correctly. TEST_F(ButtonTest, InkDropShowHideOnMouseDraggedNotifyOnRelease) { gfx::Point center(10, 10); gfx::Point oob(-1, -1); TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); button()->button_controller()->set_notify_action( ButtonController::NotifyAction::kOnRelease); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); button()->OnMouseReleased( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_FALSE(button()->pressed()); } // Tests that when button is set to notify on press, dragging mouse out and back // does not change the ink drop state. TEST_F(ButtonTest, InkDropShowHideOnMouseDraggedNotifyOnPress) { gfx::Point center(10, 10); gfx::Point oob(-1, -1); TestInkDrop* ink_drop = CreateButtonWithInkDrop(true); button()->button_controller()->set_notify_action( ButtonController::NotifyAction::kOnPress); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop->GetTargetInkDropState()); EXPECT_TRUE(button()->pressed()); button()->OnMouseDragged( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop->GetTargetInkDropState()); button()->OnMouseReleased( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, InkDropStaysHiddenWhileDragging) { gfx::Point center(10, 10); gfx::Point oob(-1, -1); TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop->GetTargetInkDropState()); SetDraggedView(button()); widget()->SetCapture(button()); widget()->ReleaseCapture(); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged( ui::MouseEvent(ui::ET_MOUSE_PRESSED, oob, oob, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); button()->OnMouseDragged(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_EQ(InkDropState::HIDDEN, ink_drop->GetTargetInkDropState()); SetDraggedView(nullptr); } // Ensure PressedCallback is dynamically settable. TEST_F(ButtonTest, SetCallback) { bool pressed = false; button()->SetCallback( base::BindRepeating([](bool* pressed) { *pressed = true; }, &pressed)); const 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)); // Default button controller notifies callback at mouse release. button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_TRUE(pressed); } // VisibilityTestButton tests to see if an ink drop or a layer has been added to // the button at any point during the visibility state changes of its Widget. class VisibilityTestButton : public TestButton { public: VisibilityTestButton() : TestButton(false) {} ~VisibilityTestButton() override { if (layer()) ADD_FAILURE(); } void AddLayerToRegion(ui::Layer* layer, views::LayerRegion region) override { ADD_FAILURE(); } void RemoveLayerFromRegions(ui::Layer* layer) override { ADD_FAILURE(); } }; // Test that hiding or closing a Widget doesn't attempt to add a layer due to // changed visibility states. TEST_F(ButtonTest, NoLayerAddedForWidgetVisibilityChanges) { VisibilityTestButton* button = widget()->SetContentsView(std::make_unique<VisibilityTestButton>()); // Ensure no layers are created during construction. EXPECT_TRUE(button->GetVisible()); EXPECT_FALSE(button->layer()); // Ensure no layers are created when hiding the widget. widget()->Hide(); EXPECT_FALSE(button->layer()); // Ensure no layers are created when the widget is reshown. widget()->Show(); EXPECT_FALSE(button->layer()); // Ensure no layers are created during the closing of the Widget. widget()->Close(); // Start an asynchronous close. EXPECT_FALSE(button->layer()); // Ensure no layers are created following the Widget's destruction. base::RunLoop().RunUntilIdle(); // Complete the Close(). } // Verify that the Space key clicks the button on key-press on Mac, and // key-release on other platforms. TEST_F(ButtonTest, ActionOnSpace) { // Give focus to the button. button()->RequestFocus(); EXPECT_TRUE(button()->HasFocus()); ui::KeyEvent space_press(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE); EXPECT_TRUE(button()->OnKeyPressed(space_press)); #if BUILDFLAG(IS_MAC) EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_TRUE(button()->pressed()); #else EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); EXPECT_FALSE(button()->pressed()); #endif ui::KeyEvent space_release(ui::ET_KEY_RELEASED, ui::VKEY_SPACE, ui::EF_NONE); #if BUILDFLAG(IS_MAC) EXPECT_FALSE(button()->OnKeyReleased(space_release)); #else EXPECT_TRUE(button()->OnKeyReleased(space_release)); #endif EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_TRUE(button()->pressed()); } // Verify that the Return key clicks the button on key-press on all platforms // except Mac. On Mac, the Return key performs the default action associated // with a dialog, even if a button has focus. TEST_F(ButtonTest, ActionOnReturn) { // Give focus to the button. button()->RequestFocus(); EXPECT_TRUE(button()->HasFocus()); ui::KeyEvent return_press(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE); #if BUILDFLAG(IS_MAC) EXPECT_FALSE(button()->OnKeyPressed(return_press)); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_FALSE(button()->pressed()); #else EXPECT_TRUE(button()->OnKeyPressed(return_press)); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_TRUE(button()->pressed()); #endif ui::KeyEvent return_release(ui::ET_KEY_RELEASED, ui::VKEY_RETURN, ui::EF_NONE); EXPECT_FALSE(button()->OnKeyReleased(return_release)); } // Verify that a subclass may customize the action for a key pressed event. TEST_F(ButtonTest, CustomActionOnKeyPressedEvent) { // Give focus to the button. button()->RequestFocus(); EXPECT_TRUE(button()->HasFocus()); // Set the button to handle any key pressed event as kOnKeyPress. button()->set_custom_key_click_action(Button::KeyClickAction::kOnKeyPress); ui::KeyEvent control_press(ui::ET_KEY_PRESSED, ui::VKEY_CONTROL, ui::EF_NONE); EXPECT_TRUE(button()->OnKeyPressed(control_press)); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_TRUE(button()->pressed()); ui::KeyEvent control_release(ui::ET_KEY_RELEASED, ui::VKEY_CONTROL, ui::EF_NONE); EXPECT_FALSE(button()->OnKeyReleased(control_release)); } // Verifies that button activation highlight state changes trigger property // change callbacks. TEST_F(ButtonTest, ChangingHighlightStateNotifiesCallback) { CreateButtonWithObserver(); EXPECT_FALSE(button_observer()->highlighted_changed()); EXPECT_FALSE(InkDrop::Get(button())->GetHighlighted()); button()->SetHighlighted(/*highlighted=*/true); EXPECT_TRUE(button_observer()->highlighted_changed()); EXPECT_TRUE(InkDrop::Get(button())->GetHighlighted()); button_observer()->Reset(); EXPECT_FALSE(button_observer()->highlighted_changed()); EXPECT_TRUE(InkDrop::Get(button())->GetHighlighted()); button()->SetHighlighted(/*highlighted=*/false); EXPECT_TRUE(button_observer()->highlighted_changed()); EXPECT_FALSE(InkDrop::Get(button())->GetHighlighted()); } // Verifies that button state changes trigger property change callbacks. TEST_F(ButtonTest, ClickingButtonNotifiesObserverOfStateChanges) { CreateButtonWithObserver(); EXPECT_FALSE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); event_generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); event_generator()->PressLeftButton(); EXPECT_TRUE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); button_observer()->Reset(); EXPECT_FALSE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); event_generator()->ReleaseLeftButton(); EXPECT_TRUE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); } // Verifies that direct calls to Button::SetState() trigger property change // callbacks. TEST_F(ButtonTest, SetStateNotifiesObserver) { CreateButtonWithObserver(); EXPECT_FALSE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); button()->SetState(Button::STATE_HOVERED); EXPECT_TRUE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); button_observer()->Reset(); EXPECT_FALSE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); button()->SetState(Button::STATE_NORMAL); EXPECT_TRUE(button_observer()->state_changed()); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); } // Verifies setting the tooltip text will call NotifyAccessibilityEvent. TEST_F(ButtonTest, SetTooltipTextNotifiesAccessibilityEvent) { std::u16string test_tooltip_text = u"Test Tooltip Text"; test::AXEventCounter counter(views::AXEventManager::Get()); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged)); button()->SetTooltipText(test_tooltip_text); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged)); EXPECT_EQ(test_tooltip_text, button()->GetTooltipText(gfx::Point())); ui::AXNodeData data; button()->GetAccessibleNodeData(&data); const std::string& name = data.GetStringAttribute(ax::mojom::StringAttribute::kName); EXPECT_EQ(test_tooltip_text, base::ASCIIToUTF16(name)); } TEST_F(ButtonTest, AccessibleRole) { ui::AXNodeData data; button()->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kButton); EXPECT_EQ(button()->GetAccessibleRole(), ax::mojom::Role::kButton); button()->SetAccessibleRole(ax::mojom::Role::kCheckBox); data = ui::AXNodeData(); button()->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kCheckBox); EXPECT_EQ(button()->GetAccessibleRole(), ax::mojom::Role::kCheckBox); } TEST_F(ButtonTest, AnchorHighlightSetsHiglight) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); Button::ScopedAnchorHighlight highlight = button()->AddAnchorHighlight(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, AnchorHighlightDestructionClearsHighlight) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); absl::optional<Button::ScopedAnchorHighlight> highlight = button()->AddAnchorHighlight(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); highlight.reset(); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, NestedAnchorHighlights) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); absl::optional<Button::ScopedAnchorHighlight> highlight1 = button()->AddAnchorHighlight(); absl::optional<Button::ScopedAnchorHighlight> highlight2 = button()->AddAnchorHighlight(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); highlight2.reset(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); highlight1.reset(); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, OverlappingAnchorHighlights) { TestInkDrop* ink_drop = CreateButtonWithInkDrop(false); absl::optional<Button::ScopedAnchorHighlight> highlight1 = button()->AddAnchorHighlight(); absl::optional<Button::ScopedAnchorHighlight> highlight2 = button()->AddAnchorHighlight(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); highlight1.reset(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop->GetTargetInkDropState()); highlight2.reset(); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop->GetTargetInkDropState()); } TEST_F(ButtonTest, AnchorHighlightsCanOutliveButton) { CreateButtonWithInkDrop(false); absl::optional<Button::ScopedAnchorHighlight> highlight = button()->AddAnchorHighlight(); // Creating a new button will destroy the old one CreateButtonWithInkDrop(false); highlight.reset(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/button_unittest.cc
C++
unknown
36,270
// 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/checkbox.h" #include <stddef.h> #include <memory> #include <utility> #include "base/functional/bind.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/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/skia_conversions.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/native_theme/native_theme.h" #include "ui/views/accessibility/view_accessibility.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_painted_layer_delegates.h" #include "ui/views/animation/ink_drop_ripple.h" #include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/painter.h" #include "ui/views/resources/grit/views_resources.h" #include "ui/views/style/platform_style.h" #include "ui/views/style/typography.h" #include "ui/views/vector_icons.h" namespace views { namespace { constexpr gfx::Size kCheckboxInkDropSize = gfx::Size(24, 24); } class Checkbox::FocusRingHighlightPathGenerator : public views::HighlightPathGenerator { public: SkPath GetHighlightPath(const views::View* view) override { SkPath path; auto* checkbox = static_cast<const views::Checkbox*>(view); if (checkbox->image()->bounds().IsEmpty()) return path; return checkbox->GetFocusRingPath(); } }; Checkbox::Checkbox(const std::u16string& label, PressedCallback callback, int button_context) : LabelButton(std::move(callback), label, button_context) { SetImageCentered(false); SetHorizontalAlignment(gfx::ALIGN_LEFT); SetRequestFocusOnPress(false); InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON); SetHasInkDropActionOnClick(true); InkDrop::UseInkDropWithoutAutoHighlight(InkDrop::Get(this), /*highlight_on_hover=*/false); InkDrop::Get(this)->SetCreateRippleCallback(base::BindRepeating( [](Checkbox* host) { // The "small" size is 21dp, the large size is 1.33 * 21dp = 28dp. return InkDrop::Get(host)->CreateSquareRipple( host->image()->GetMirroredContentsBounds().CenterPoint(), gfx::Size(21, 21)); }, this)); InkDrop::Get(this)->SetBaseColorCallback(base::BindRepeating( [](Checkbox* host) { // Usually ink-drop ripples match the text color. Checkboxes use the // color of the unchecked, enabled icon. return host->GetIconImageColor(IconState::ENABLED); }, this)); // Limit the checkbox height to match the legacy appearance. const gfx::Size preferred_size(LabelButton::CalculatePreferredSize()); SetMinSize(gfx::Size(0, preferred_size.height() + 4)); // Checkboxes always have a focus ring, even when the platform otherwise // doesn't generally use them for buttons. SetInstallFocusRingOnFocus(true); FocusRing::Get(this)->SetPathGenerator( std::make_unique<FocusRingHighlightPathGenerator>()); // Avoid the default ink-drop mask to allow the ripple effect to extend beyond // the checkbox view (otherwise it gets clipped which looks weird). views::InstallEmptyHighlightPathGenerator(this); if (features::IsChromeRefresh2023()) { InkDrop::Install(image(), std::make_unique<InkDropHost>(image())); SetInkDropView(image()); InkDrop::Get(image())->SetMode(InkDropHost::InkDropMode::ON); // Allow ImageView to capture mouse events in order for InkDrop effects to // trigger. image()->SetCanProcessEventsWithinSubtree(true); // Avoid the default ink-drop mask to allow the InkDrop effect to extend // beyond the image view (otherwise it gets clipped which looks weird). views::InstallEmptyHighlightPathGenerator(image()); InkDrop::Get(image())->SetCreateHighlightCallback(base::BindRepeating( [](ImageView* host) { int radius = InkDropHost::GetLargeSize(kCheckboxInkDropSize).width() / 2; return std::make_unique<views::InkDropHighlight>( gfx::PointF(host->GetContentsBounds().CenterPoint()), std::make_unique<CircleLayerDelegate>( views::InkDrop::Get(host)->GetBaseColor(), radius)); }, image())); InkDrop::Get(image())->SetCreateRippleCallback(base::BindRepeating( [](ImageView* host) { return InkDrop::Get(host)->CreateSquareRipple( host->GetContentsBounds().CenterPoint(), kCheckboxInkDropSize); }, image())); // Usually ink-drop ripples match the text color. Checkboxes use the // color of the unchecked, enabled icon. InkDrop::Get(image())->SetBaseColorId( ui::kColorCheckboxForegroundUnchecked); } } Checkbox::~Checkbox() = default; void Checkbox::SetChecked(bool checked) { if (GetChecked() == checked) return; checked_ = checked; NotifyAccessibilityEvent(ax::mojom::Event::kCheckedStateChanged, true); UpdateImage(); OnPropertyChanged(&checked_, kPropertyEffectsNone); } bool Checkbox::GetChecked() const { return checked_; } base::CallbackListSubscription Checkbox::AddCheckedChangedCallback( PropertyChangedCallback callback) { return AddPropertyChangedCallback(&checked_, callback); } void Checkbox::SetMultiLine(bool multi_line) { if (GetMultiLine() == multi_line) return; label()->SetMultiLine(multi_line); // TODO(pkasting): Remove this and forward callback subscriptions to the // underlying label property when Label is converted to properties. OnPropertyChanged(this, kPropertyEffectsNone); } bool Checkbox::GetMultiLine() const { return label()->GetMultiLine(); } void Checkbox::SetCheckedIconImageColor(SkColor color) { checked_icon_image_color_ = color; } void Checkbox::GetAccessibleNodeData(ui::AXNodeData* node_data) { LabelButton::GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kCheckBox; const ax::mojom::CheckedState checked_state = GetChecked() ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse; node_data->SetCheckedState(checked_state); if (GetEnabled()) { node_data->SetDefaultActionVerb(GetChecked() ? ax::mojom::DefaultActionVerb::kUncheck : ax::mojom::DefaultActionVerb::kCheck); } } gfx::ImageSkia Checkbox::GetImage(ButtonState for_state) const { int icon_state = 0; if (GetChecked()) icon_state |= IconState::CHECKED; if (for_state != STATE_DISABLED) icon_state |= IconState::ENABLED; return gfx::CreateVectorIcon(GetVectorIcon(), 16, GetIconImageColor(icon_state)); } std::unique_ptr<LabelButtonBorder> Checkbox::CreateDefaultBorder() const { std::unique_ptr<LabelButtonBorder> border = LabelButton::CreateDefaultBorder(); border->set_insets( LayoutProvider::Get()->GetInsetsMetric(INSETS_CHECKBOX_RADIO_BUTTON)); return border; } void Checkbox::OnThemeChanged() { LabelButton::OnThemeChanged(); } SkPath Checkbox::GetFocusRingPath() const { SkPath path; gfx::Rect bounds = image()->GetMirroredContentsBounds(); // Correct for slight discrepancy between visual image bounds and view bounds. if (features::IsChromeRefresh2023()) { bounds.Inset(2); } else { bounds.Inset(1); } path.addRect(RectToSkRect(bounds)); return path; } SkColor Checkbox::GetIconImageColor(int icon_state) const { SkColor active_color = GetColorProvider()->GetColor((icon_state & IconState::CHECKED) ? ui::kColorCheckboxForegroundChecked : ui::kColorCheckboxForegroundUnchecked); // Use the overridden checked icon image color instead if set. if (icon_state & IconState::CHECKED && checked_icon_image_color_.has_value()) active_color = checked_icon_image_color_.value(); // TODO(crbug.com/1394575): Replace return statement with the following once // CR2023 is launched if (features::IsChromeRefresh2023()) { return (icon_state & IconState::ENABLED) ? active_color : GetColorProvider()->GetColor( ui::kColorCheckboxForegroundDisabled); } return (icon_state & IconState::ENABLED) ? active_color : color_utils::BlendTowardMaxContrast(active_color, gfx::kDisabledControlAlpha); } const gfx::VectorIcon& Checkbox::GetVectorIcon() const { if (features::IsChromeRefresh2023()) { return GetChecked() ? kCheckboxActiveCr2023Icon : kCheckboxNormalCr2023Icon; } return GetChecked() ? kCheckboxActiveIcon : kCheckboxNormalIcon; } void Checkbox::NotifyClick(const ui::Event& event) { SetChecked(!GetChecked()); LabelButton::NotifyClick(event); } ui::NativeTheme::Part Checkbox::GetThemePart() const { return ui::NativeTheme::kCheckbox; } void Checkbox::GetExtraParams(ui::NativeTheme::ExtraParams* params) const { LabelButton::GetExtraParams(params); params->button.checked = GetChecked(); } BEGIN_METADATA(Checkbox, LabelButton) ADD_PROPERTY_METADATA(bool, Checked) ADD_PROPERTY_METADATA(bool, MultiLine) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/checkbox.cc
C++
unknown
9,848
// 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_CHECKBOX_H_ #define UI_VIEWS_CONTROLS_BUTTON_CHECKBOX_H_ #include <memory> #include <string> #include "cc/paint/paint_flags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/metadata/view_factory.h" namespace gfx { struct VectorIcon; } namespace views { // A native themed class representing a checkbox. This class does not use // platform specific objects to replicate the native platforms looks and feel. class VIEWS_EXPORT Checkbox : public LabelButton { public: METADATA_HEADER(Checkbox); explicit Checkbox(const std::u16string& label = std::u16string(), PressedCallback callback = PressedCallback(), int button_context = style::CONTEXT_BUTTON); Checkbox(const Checkbox&) = delete; Checkbox& operator=(const Checkbox&) = delete; ~Checkbox() override; // Sets/Gets whether or not the checkbox is checked. virtual void SetChecked(bool checked); bool GetChecked() const; [[nodiscard]] base::CallbackListSubscription AddCheckedChangedCallback( PropertyChangedCallback callback); void SetMultiLine(bool multi_line); bool GetMultiLine() const; void SetCheckedIconImageColor(SkColor color); // LabelButton: void GetAccessibleNodeData(ui::AXNodeData* node_data) override; gfx::ImageSkia GetImage(ButtonState for_state) const override; std::unique_ptr<LabelButtonBorder> CreateDefaultBorder() const override; protected: // Bitmask constants for GetIconImageColor. enum IconState { CHECKED = 0b1, ENABLED = 0b10 }; // LabelButton: void OnThemeChanged() override; // Returns the path to draw the focus ring around for this Checkbox. virtual SkPath GetFocusRingPath() const; // |icon_state| is a bitmask using the IconState enum. virtual SkColor GetIconImageColor(int icon_state) const; // Gets the vector icon to use based on the current state of |checked_|. virtual const gfx::VectorIcon& GetVectorIcon() const; private: class FocusRingHighlightPathGenerator; // Button: void NotifyClick(const ui::Event& event) override; ui::NativeTheme::Part GetThemePart() const override; void GetExtraParams(ui::NativeTheme::ExtraParams* params) const override; // True if the checkbox is checked. bool checked_ = false; absl::optional<SkColor> checked_icon_image_color_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Checkbox, LabelButton) VIEW_BUILDER_PROPERTY(bool, Checked) VIEW_BUILDER_PROPERTY(bool, MultiLine) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Checkbox) #endif // UI_VIEWS_CONTROLS_BUTTON_CHECKBOX_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/checkbox.h
C++
unknown
2,862
// 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/button/checkbox.h" #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/styled_label.h" #include "ui/views/test/views_test_base.h" namespace views { class CheckboxTest : public ViewsTestBase { public: CheckboxTest() = default; CheckboxTest(const CheckboxTest&) = delete; CheckboxTest& operator=(const CheckboxTest&) = delete; ~CheckboxTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); // Create a widget so that the Checkbox can query the hover state // correctly. widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); widget_->Init(std::move(params)); widget_->Show(); checkbox_ = widget_->SetContentsView(std::make_unique<Checkbox>()); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } protected: Checkbox* checkbox() { return checkbox_; } private: std::unique_ptr<Widget> widget_; raw_ptr<Checkbox> checkbox_ = nullptr; }; TEST_F(CheckboxTest, AccessibilityTest) { const std::u16string label_text = u"Some label"; StyledLabel label; label.SetText(label_text); checkbox()->SetAccessibleName(&label); // Use `ViewAccessibility::GetAccessibleNodeData` so that we can get the // label's accessible id to compare with the checkbox's labelled-by id. ui::AXNodeData label_data; label.GetViewAccessibility().GetAccessibleNodeData(&label_data); ui::AXNodeData ax_data; checkbox()->GetAccessibleNodeData(&ax_data); EXPECT_EQ(ax_data.GetString16Attribute(ax::mojom::StringAttribute::kName), label_text); EXPECT_EQ(checkbox()->GetAccessibleName(), label_text); EXPECT_EQ(ax_data.GetNameFrom(), ax::mojom::NameFrom::kRelatedElement); EXPECT_EQ(ax_data.GetIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds)[0], label_data.id); EXPECT_EQ(ax_data.role, ax::mojom::Role::kCheckBox); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/checkbox_unittest.cc
C++
unknown
2,498
// 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/image_button.h" #include <utility> #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.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/gfx/animation/throb_animation.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/scoped_canvas.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/background.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/painter.h" #include "ui/views/widget/widget.h" namespace views { // Default button size if no image is set. This is ignored if there is an image, // and exists for historical reasons (any number of clients could depend on this // behaviour). static constexpr int kDefaultWidth = 16; static constexpr int kDefaultHeight = 14; //////////////////////////////////////////////////////////////////////////////// // ImageButton, public: ImageButton::ImageButton(PressedCallback callback) : Button(std::move(callback)) { // By default, we request that the gfx::Canvas passed to our View::OnPaint() // implementation is flipped horizontally so that the button's images are // mirrored when the UI directionality is right-to-left. SetFlipCanvasOnPaintForRTLUI(true); views::FocusRing::Get(this)->SetOutsetFocusRingDisabled(true); } ImageButton::~ImageButton() = default; gfx::ImageSkia ImageButton::GetImage(ButtonState state) const { return images_[state].Rasterize(GetColorProvider()); } void ImageButton::SetImage(ButtonState for_state, const gfx::ImageSkia* image) { SetImage(for_state, image ? *image : gfx::ImageSkia()); } void ImageButton::SetImage(ButtonState for_state, const gfx::ImageSkia& image) { SetImageModel(for_state, ui::ImageModel::FromImageSkia(image)); } void ImageButton::SetImageModel(ButtonState for_state, const ui::ImageModel& image_model) { if (for_state == STATE_HOVERED) SetAnimateOnStateChange(!image_model.IsEmpty()); const gfx::Size old_preferred_size = GetPreferredSize(); images_[for_state] = image_model; if (old_preferred_size != GetPreferredSize()) PreferredSizeChanged(); // Even if |for_state| isn't the current state this image could be painted; // see |GetImageToPaint()|. So, always repaint. SchedulePaint(); } void ImageButton::SetBackgroundImage(SkColor color, const gfx::ImageSkia* image, const gfx::ImageSkia* mask) { if (image == nullptr || mask == nullptr) { background_image_ = gfx::ImageSkia(); return; } background_image_ = gfx::ImageSkiaOperations::CreateButtonBackground(color, *image, *mask); } ImageButton::HorizontalAlignment ImageButton::GetImageHorizontalAlignment() const { return h_alignment_; } ImageButton::VerticalAlignment ImageButton::GetImageVerticalAlignment() const { return v_alignment_; } void ImageButton::SetImageHorizontalAlignment(HorizontalAlignment h_alignment) { if (GetImageHorizontalAlignment() == h_alignment) return; h_alignment_ = h_alignment; OnPropertyChanged(&h_alignment_, kPropertyEffectsPaint); } void ImageButton::SetImageVerticalAlignment(VerticalAlignment v_alignment) { if (GetImageVerticalAlignment() == v_alignment) return; v_alignment_ = v_alignment; OnPropertyChanged(&v_alignment_, kPropertyEffectsPaint); } gfx::Size ImageButton::GetMinimumImageSize() const { return minimum_image_size_; } void ImageButton::SetMinimumImageSize(const gfx::Size& size) { if (GetMinimumImageSize() == size) return; minimum_image_size_ = size; OnPropertyChanged(&minimum_image_size_, kPropertyEffectsPreferredSizeChanged); } //////////////////////////////////////////////////////////////////////////////// // ImageButton, View overrides: gfx::Size ImageButton::CalculatePreferredSize() const { gfx::Size size(kDefaultWidth, kDefaultHeight); if (!images_[STATE_NORMAL].IsEmpty()) size = images_[STATE_NORMAL].Size(); size.SetToMax(GetMinimumImageSize()); gfx::Insets insets = GetInsets(); size.Enlarge(insets.width(), insets.height()); return size; } views::PaintInfo::ScaleType ImageButton::GetPaintScaleType() const { // ImageButton contains an image which is rastered at the device scale factor. // By default, the paint commands are recorded at a scale factor slighlty // 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 and 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 ImageButton::OnThemeChanged() { Button::OnThemeChanged(); // If we have any `ImageModel`s, they may need repaint upon a `ColorProvider` // change. SchedulePaint(); } // static std::unique_ptr<ImageButton> ImageButton::CreateIconButton( PressedCallback callback, const gfx::VectorIcon& icon, const std::u16string& accessible_name, MaterialIconStyle icon_style) { const int kSmallIconSize = 14; const int kLargeIconSize = 20; int icon_size = (icon_style == MaterialIconStyle::kLarge) ? kLargeIconSize : kSmallIconSize; // Icon images have padding between the image and image border. To account // for that padding, add a general padding value. This value might be // incorrect depending on the icon image. icon_size += LayoutProvider::Get()->GetDistanceMetric(DISTANCE_VECTOR_ICON_PADDING); std::unique_ptr<ImageButton> icon_button = std::make_unique<ImageButton>(callback); icon_button->SetImageModel( ButtonState::STATE_NORMAL, ui::ImageModel::FromVectorIcon(icon, ui::kColorIcon, icon_size)); icon_button->SetImageModel( ButtonState::STATE_HOVERED, ui::ImageModel::FromVectorIcon(icon, ui::kColorIcon, icon_size)); icon_button->SetImageModel( ButtonState::STATE_PRESSED, ui::ImageModel::FromVectorIcon(icon, ui::kColorIcon, icon_size)); icon_button->SetImageModel( ButtonState::STATE_DISABLED, ui::ImageModel::FromVectorIcon(icon, ui::kColorIconDisabled, icon_size)); const gfx::Insets target_insets = LayoutProvider::Get()->GetInsetsMetric(InsetsMetric::INSETS_ICON_BUTTON); icon_button->SetBorder(views::CreateEmptyBorder(target_insets)); const int kSmallIconButtonSize = 24; const int kLargeIconButtonSize = 32; int button_size = (icon_style == MaterialIconStyle::kLarge) ? kLargeIconButtonSize : kSmallIconButtonSize; const int highlight_radius = LayoutProvider::Get()->GetCornerRadiusMetric( views::Emphasis::kMaximum, gfx::Size(button_size, button_size)); views::InstallRoundRectHighlightPathGenerator( icon_button.get(), gfx::Insets(), highlight_radius); InkDrop::Get(icon_button.get())->SetMode(views::InkDropHost::InkDropMode::ON); icon_button->SetHasInkDropActionOnClick(true); icon_button->SetShowInkDropWhenHotTracked(true); InkDrop::Get(icon_button.get()) ->SetBaseColorCallback(base::BindRepeating( [](ImageButton* host) { return host->GetColorProvider()->GetColor( ui::kColorSysOnSurfaceSubtle); }, icon_button.get())); icon_button->SetAccessibleName(accessible_name); return icon_button; } void ImageButton::PaintButtonContents(gfx::Canvas* canvas) { // TODO(estade|tdanderson|bruthig): The ink drop layer should be positioned // behind the button's image which means the image needs to be painted to its // own layer instead of to the Canvas. gfx::ImageSkia img = GetImageToPaint(); if (!img.isNull()) { gfx::ScopedCanvas scoped(canvas); if (draw_image_mirrored_) { canvas->Translate(gfx::Vector2d(width(), 0)); canvas->Scale(-1, 1); } if (!background_image_.isNull()) { // The background image alignment is the same as for the image. gfx::Point background_position = ComputeImagePaintPosition(background_image_); canvas->DrawImageInt(background_image_, background_position.x(), background_position.y()); } gfx::Point position = ComputeImagePaintPosition(img); canvas->DrawImageInt(img, position.x(), position.y()); } } //////////////////////////////////////////////////////////////////////////////// // ImageButton, protected: gfx::ImageSkia ImageButton::GetImageToPaint() { const auto* const color_provider = GetColorProvider(); if (!images_[STATE_HOVERED].IsEmpty() && hover_animation().is_animating()) { return gfx::ImageSkiaOperations::CreateBlendedImage( images_[STATE_NORMAL].Rasterize(color_provider), images_[STATE_HOVERED].Rasterize(color_provider), hover_animation().GetCurrentValue()); } const auto img = images_[GetState()].Rasterize(color_provider); return !img.isNull() ? img : images_[STATE_NORMAL].Rasterize(color_provider); } //////////////////////////////////////////////////////////////////////////////// // ImageButton, private: const gfx::Point ImageButton::ComputeImagePaintPosition( const gfx::ImageSkia& image) const { HorizontalAlignment h_alignment = GetImageHorizontalAlignment(); VerticalAlignment v_alignment = GetImageVerticalAlignment(); if (draw_image_mirrored_) { if (h_alignment == ALIGN_RIGHT) h_alignment = ALIGN_LEFT; else if (h_alignment == ALIGN_LEFT) h_alignment = ALIGN_RIGHT; } const gfx::Rect rect = GetContentsBounds(); int x = 0; if (h_alignment == ALIGN_CENTER) x = (rect.width() - image.width()) / 2; else if (h_alignment == ALIGN_RIGHT) x = rect.width() - image.width(); int y = 0; if (v_alignment == ALIGN_MIDDLE) y = (rect.height() - image.height()) / 2; else if (v_alignment == ALIGN_BOTTOM) y = rect.height() - image.height(); return rect.origin() + gfx::Vector2d(x, y); } //////////////////////////////////////////////////////////////////////////////// // ToggleImageButton, public: ToggleImageButton::ToggleImageButton(PressedCallback callback) : ImageButton(std::move(callback)) {} ToggleImageButton::~ToggleImageButton() = default; bool ToggleImageButton::GetToggled() const { return toggled_; } void ToggleImageButton::SetToggled(bool toggled) { if (toggled == toggled_) return; for (int i = 0; i < STATE_COUNT; ++i) std::swap(images_[i], alternate_images_[i]); toggled_ = toggled; OnPropertyChanged(&toggled_, kPropertyEffectsPaint); NotifyAccessibilityEvent(ax::mojom::Event::kCheckedStateChanged, true); } void ToggleImageButton::SetToggledImage(ButtonState image_state, const gfx::ImageSkia* image) { SetToggledImageModel(image_state, ui::ImageModel::FromImageSkia( image ? *image : gfx::ImageSkia())); } void ToggleImageButton::SetToggledImageModel( ButtonState image_state, const ui::ImageModel& image_model) { if (toggled_) { images_[image_state] = image_model; if (GetState() == image_state) SchedulePaint(); } else { alternate_images_[image_state] = image_model; } } void ToggleImageButton::SetToggledBackground(std::unique_ptr<Background> b) { toggled_background_ = std::move(b); SchedulePaint(); } std::u16string ToggleImageButton::GetToggledTooltipText() const { return toggled_tooltip_text_; } void ToggleImageButton::SetToggledTooltipText(const std::u16string& tooltip) { if (tooltip == toggled_tooltip_text_) return; toggled_tooltip_text_ = tooltip; OnPropertyChanged(&toggled_tooltip_text_, kPropertyEffectsNone); } std::u16string ToggleImageButton::GetToggledAccessibleName() const { return toggled_accessible_name_; } void ToggleImageButton::SetToggledAccessibleName(const std::u16string& name) { if (name == toggled_accessible_name_) return; toggled_accessible_name_ = name; OnPropertyChanged(&toggled_accessible_name_, kPropertyEffectsNone); } //////////////////////////////////////////////////////////////////////////////// // ToggleImageButton, ImageButton overrides: gfx::ImageSkia ToggleImageButton::GetImage(ButtonState image_state) const { if (toggled_) return alternate_images_[image_state].Rasterize(GetColorProvider()); return images_[image_state].Rasterize(GetColorProvider()); } void ToggleImageButton::SetImageModel(ButtonState image_state, const ui::ImageModel& image_model) { if (toggled_) { alternate_images_[image_state] = image_model; } else { images_[image_state] = image_model; if (GetState() == image_state) SchedulePaint(); } PreferredSizeChanged(); } void ToggleImageButton::OnPaintBackground(gfx::Canvas* canvas) { if (toggled_ && toggled_background_) { TRACE_EVENT0("views", "View::OnPaintBackground"); toggled_background_->Paint(canvas, this); } else { ImageButton::OnPaintBackground(canvas); } } //////////////////////////////////////////////////////////////////////////////// // ToggleImageButton, View overrides: std::u16string ToggleImageButton::GetTooltipText(const gfx::Point& p) const { return (!toggled_ || toggled_tooltip_text_.empty()) ? Button::GetTooltipText(p) : toggled_tooltip_text_; } void ToggleImageButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { ImageButton::GetAccessibleNodeData(node_data); if (!toggled_) return; if (!toggled_accessible_name_.empty()) { node_data->SetName(toggled_accessible_name_); } else if (!toggled_tooltip_text_.empty()) { node_data->SetName(toggled_tooltip_text_); } // Use the visual pressed image as a cue for making this control into an // accessible toggle button. if ((toggled_ && !images_[ButtonState::STATE_NORMAL].IsEmpty()) || (!toggled_ && !alternate_images_[ButtonState::STATE_NORMAL].IsEmpty())) { node_data->role = ax::mojom::Role::kToggleButton; node_data->SetCheckedState(toggled_ ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse); } } BEGIN_METADATA(ImageButton, Button) ADD_PROPERTY_METADATA(HorizontalAlignment, ImageHorizontalAlignment) ADD_PROPERTY_METADATA(VerticalAlignment, ImageVerticalAlignment) ADD_PROPERTY_METADATA(gfx::Size, MinimumImageSize) END_METADATA BEGIN_METADATA(ToggleImageButton, ImageButton) ADD_PROPERTY_METADATA(bool, Toggled) ADD_PROPERTY_METADATA(std::unique_ptr<Background>, ToggledBackground) ADD_PROPERTY_METADATA(std::u16string, ToggledTooltipText) ADD_PROPERTY_METADATA(std::u16string, ToggledAccessibleName) END_METADATA } // namespace views DEFINE_ENUM_CONVERTERS( views::ImageButton::HorizontalAlignment, {views::ImageButton::HorizontalAlignment::ALIGN_LEFT, u"ALIGN_LEFT"}, {views::ImageButton::HorizontalAlignment::ALIGN_CENTER, u"ALIGN_CENTER"}, {views::ImageButton::HorizontalAlignment::ALIGN_RIGHT, u"ALIGN_RIGHT"}) DEFINE_ENUM_CONVERTERS( views::ImageButton::VerticalAlignment, {views::ImageButton::VerticalAlignment::ALIGN_TOP, u"ALIGN_TOP"}, {views::ImageButton::VerticalAlignment::ALIGN_MIDDLE, u"ALIGN_MIDDLE"}, {views::ImageButton::VerticalAlignment::ALIGN_BOTTOM, u"ALIGN_BOTTOM"})
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button.cc
C++
unknown
15,907
// 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_IMAGE_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_ #include <memory> #include <utility> #include "base/gtest_prod_util.h" #include "ui/base/layout.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/button.h" #include "ui/views/metadata/view_factory.h" namespace views { class VIEWS_EXPORT ImageButton : public Button { public: METADATA_HEADER(ImageButton); // An enum describing the horizontal alignment of images on Buttons. enum HorizontalAlignment { ALIGN_LEFT = 0, ALIGN_CENTER, ALIGN_RIGHT }; // An enum describing the vertical alignment of images on Buttons. enum VerticalAlignment { ALIGN_TOP = 0, ALIGN_MIDDLE, ALIGN_BOTTOM }; explicit ImageButton(PressedCallback callback = PressedCallback()); ImageButton(const ImageButton&) = delete; ImageButton& operator=(const ImageButton&) = delete; ~ImageButton() override; // Returns the image for a given |state|. virtual gfx::ImageSkia GetImage(ButtonState state) const; // Set the image the button should use for the provided state. void SetImage(ButtonState state, const gfx::ImageSkia* image); // As above, but takes a const ref. TODO(estade): all callers should be // updated to use this version, and then the implementations can be // consolidated. // TODO(http://crbug.com/1100034) prefer SetImageModel over SetImage(). void SetImage(ButtonState state, const gfx::ImageSkia& image); virtual void SetImageModel(ButtonState state, const ui::ImageModel& image_model); // Set the background details. The background image uses the same alignment // as the image. void SetBackgroundImage(SkColor color, const gfx::ImageSkia* image, const gfx::ImageSkia* mask); // How the image is laid out within the button's bounds. HorizontalAlignment GetImageHorizontalAlignment() const; VerticalAlignment GetImageVerticalAlignment() const; void SetImageHorizontalAlignment(HorizontalAlignment h_alignment); void SetImageVerticalAlignment(VerticalAlignment v_alignment); // The minimum size of the contents (not including the border). The contents // will be at least this size, but may be larger if the image itself is // larger. gfx::Size GetMinimumImageSize() const; void SetMinimumImageSize(const gfx::Size& size); // Whether we should draw our images resources horizontally flipped. void SetDrawImageMirrored(bool mirrored) { draw_image_mirrored_ = mirrored; } // Overridden from View: gfx::Size CalculatePreferredSize() const override; views::PaintInfo::ScaleType GetPaintScaleType() const override; void OnThemeChanged() override; enum class MaterialIconStyle { kSmall, kLarge }; // Static method to create a Icon button with Google Material style // guidelines. static std::unique_ptr<ImageButton> CreateIconButton( PressedCallback callback, const gfx::VectorIcon& icon, const std::u16string& accessible_name, MaterialIconStyle icon_style = MaterialIconStyle::kLarge); protected: // Overridden from Button: void PaintButtonContents(gfx::Canvas* canvas) override; // Returns the image to paint. This is invoked from paint and returns a value // from images. virtual gfx::ImageSkia GetImageToPaint(); // Updates button background for |scale_factor|. void UpdateButtonBackground(ui::ResourceScaleFactor scale_factor); // The images used to render the different states of this button. ui::ImageModel images_[STATE_COUNT]; gfx::ImageSkia background_image_; private: FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, Basics); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, ImagePositionWithBorder); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, LeftAlignedMirrored); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, RightAlignedMirrored); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, ImagePositionWithBackground); FRIEND_TEST_ALL_PREFIXES(ImageButtonFactoryTest, CreateVectorImageButton); // Returns the correct position of the image for painting. const gfx::Point ComputeImagePaintPosition(const gfx::ImageSkia& image) const; // Image alignment. HorizontalAlignment h_alignment_ = ALIGN_LEFT; VerticalAlignment v_alignment_ = ALIGN_TOP; gfx::Size minimum_image_size_; // Whether we draw our resources horizontally flipped. This can happen in the // linux titlebar, where image resources were designed to be flipped so a // small curved corner in the close button designed to fit into the frame // resources. bool draw_image_mirrored_ = false; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ImageButton, Button) VIEW_BUILDER_PROPERTY(bool, DrawImageMirrored) VIEW_BUILDER_PROPERTY(ImageButton::HorizontalAlignment, ImageHorizontalAlignment) VIEW_BUILDER_PROPERTY(ImageButton::VerticalAlignment, ImageVerticalAlignment) VIEW_BUILDER_PROPERTY(gfx::Size, MinimumImageSize) VIEW_BUILDER_OVERLOAD_METHOD(SetImage, Button::ButtonState, const gfx::ImageSkia*) VIEW_BUILDER_OVERLOAD_METHOD(SetImage, Button::ButtonState, const gfx::ImageSkia&) VIEW_BUILDER_METHOD(SetImageModel, Button::ButtonState, const ui::ImageModel&) END_VIEW_BUILDER //////////////////////////////////////////////////////////////////////////////// // // ToggleImageButton // // A toggle-able ImageButton. It swaps out its graphics when toggled. // //////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ToggleImageButton : public ImageButton { public: METADATA_HEADER(ToggleImageButton); explicit ToggleImageButton(PressedCallback callback = PressedCallback()); ToggleImageButton(const ToggleImageButton&) = delete; ToggleImageButton& operator=(const ToggleImageButton&) = delete; ~ToggleImageButton() override; // Change the toggled state. bool GetToggled() const; void SetToggled(bool toggled); // Like ImageButton::SetImage(), but to set the graphics used for the // "has been toggled" state. Must be called for each button state // before the button is toggled. void SetToggledImage(ButtonState state, const gfx::ImageSkia* image); void SetToggledImageModel(ButtonState state, const ui::ImageModel& image_model); // Like Views::SetBackground(), but to set the background color used for the // "has been toggled" state. void SetToggledBackground(std::unique_ptr<Background> b); Background* GetToggledBackground() const { return toggled_background_.get(); } // Get/Set the tooltip text displayed when the button is toggled. std::u16string GetToggledTooltipText() const; void SetToggledTooltipText(const std::u16string& tooltip); // Get/Set the accessible text used when the button is toggled. std::u16string GetToggledAccessibleName() const; void SetToggledAccessibleName(const std::u16string& name); // Overridden from ImageButton: gfx::ImageSkia GetImage(ButtonState state) const override; void SetImageModel(ButtonState state, const ui::ImageModel& image_model) override; // Overridden from View: std::u16string GetTooltipText(const gfx::Point& p) const override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void OnPaintBackground(gfx::Canvas* canvas) override; private: // The parent class's images_ member is used for the current images, // and this array is used to hold the alternative images. // We swap between the two when toggling. ui::ImageModel alternate_images_[STATE_COUNT]; // True if the button is currently toggled. bool toggled_ = false; std::unique_ptr<Background> toggled_background_; // The parent class's tooltip_text_ is displayed when not toggled, and // this one is shown when toggled. std::u16string toggled_tooltip_text_; // The parent class's accessibility data is used when not toggled, and this // one is used when toggled. std::u16string toggled_accessible_name_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ToggleImageButton, ImageButton) VIEW_BUILDER_PROPERTY(bool, Toggled) VIEW_BUILDER_PROPERTY(std::unique_ptr<Background>, ToggledBackground) VIEW_BUILDER_PROPERTY(std::u16string, ToggledTooltipText) VIEW_BUILDER_PROPERTY(std::u16string, ToggledAccessibleName) VIEW_BUILDER_METHOD(SetToggledImageModel, Button::ButtonState, const ui::ImageModel&) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ImageButton) DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ToggleImageButton) #endif // UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button.h
C++
unknown
8,873
// 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/image_button_factory.h" #include <memory> #include <utility> #include "base/memory/raw_ref.h" #include "ui/base/models/image_model.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_types.h" #include "ui/gfx/vector_icon_utils.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/border.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/painter.h" namespace views { namespace { class ColorTrackingVectorImageButton : public ImageButton { public: ColorTrackingVectorImageButton(PressedCallback callback, const gfx::VectorIcon& icon, int dip_size) : ImageButton(std::move(callback)), icon_(icon), dip_size_(dip_size) {} // ImageButton: void OnThemeChanged() override { ImageButton::OnThemeChanged(); const ui::ColorProvider* cp = GetColorProvider(); const SkColor color = cp->GetColor(ui::kColorIcon); const SkColor disabled_color = cp->GetColor(ui::kColorIconDisabled); SetImageFromVectorIconWithColor(this, *icon_, dip_size_, color, disabled_color); } private: const raw_ref<const gfx::VectorIcon> icon_; int dip_size_; }; } // namespace std::unique_ptr<ImageButton> CreateVectorImageButtonWithNativeTheme( Button::PressedCallback callback, const gfx::VectorIcon& icon, absl::optional<int> dip_size) { // We can't use `value_or` as that ALWAYS evaluates the false case, which is // undefined for some valid and commonly used Chrome vector icons. const int dip_size_value = dip_size.has_value() ? dip_size.value() : GetDefaultSizeOfVectorIcon(icon); auto button = std::make_unique<ColorTrackingVectorImageButton>( std::move(callback), icon, dip_size_value); ConfigureVectorImageButton(button.get()); return button; } std::unique_ptr<ImageButton> CreateVectorImageButton( Button::PressedCallback callback) { auto button = std::make_unique<ImageButton>(std::move(callback)); ConfigureVectorImageButton(button.get()); return button; } std::unique_ptr<ToggleImageButton> CreateVectorToggleImageButton( Button::PressedCallback callback) { auto button = std::make_unique<ToggleImageButton>(std::move(callback)); ConfigureVectorImageButton(button.get()); return button; } void ConfigureVectorImageButton(ImageButton* button) { InkDrop::Get(button)->SetMode(views::InkDropHost::InkDropMode::ON); button->SetHasInkDropActionOnClick(true); button->SetImageHorizontalAlignment(ImageButton::ALIGN_CENTER); button->SetImageVerticalAlignment(ImageButton::ALIGN_MIDDLE); button->SetBorder(CreateEmptyBorder( LayoutProvider::Get()->GetInsetsMetric(INSETS_VECTOR_IMAGE_BUTTON))); } void SetImageFromVectorIconWithColor(ImageButton* button, const gfx::VectorIcon& icon, SkColor icon_color, SkColor icon_disabled_color) { SetImageFromVectorIconWithColor(button, icon, GetDefaultSizeOfVectorIcon(icon), icon_color, icon_disabled_color); } void SetImageFromVectorIconWithColor(ImageButton* button, const gfx::VectorIcon& icon, int dip_size, SkColor icon_color, SkColor icon_disabled_color) { const ui::ImageModel& normal_image = ui::ImageModel::FromVectorIcon(icon, icon_color, dip_size); const ui::ImageModel& disabled_image = ui::ImageModel::FromVectorIcon(icon, icon_disabled_color, dip_size); button->SetImageModel(Button::STATE_NORMAL, normal_image); button->SetImageModel(Button::STATE_DISABLED, disabled_image); InkDrop::Get(button)->SetBaseColor(icon_color); } void SetToggledImageFromVectorIconWithColor(ToggleImageButton* button, const gfx::VectorIcon& icon, int dip_size, SkColor icon_color, SkColor disabled_color) { const ui::ImageModel& normal_image = ui::ImageModel::FromVectorIcon(icon, icon_color, dip_size); const ui::ImageModel& disabled_image = ui::ImageModel::FromVectorIcon(icon, disabled_color, dip_size); button->SetToggledImageModel(Button::STATE_NORMAL, normal_image); button->SetToggledImageModel(Button::STATE_DISABLED, disabled_image); } void SetImageFromVectorIconWithColorId( ImageButton* button, const gfx::VectorIcon& icon, ui::ColorId icon_color_id, ui::ColorId icon_disabled_color_id, absl::optional<int> icon_size /*=nullopt*/) { int dip_size = icon_size.has_value() ? icon_size.value() : GetDefaultSizeOfVectorIcon(icon); const ui::ImageModel& normal_image = ui::ImageModel::FromVectorIcon(icon, icon_color_id, dip_size); const ui::ImageModel& disabled_image = ui::ImageModel::FromVectorIcon(icon, icon_disabled_color_id, dip_size); button->SetImageModel(Button::STATE_NORMAL, normal_image); button->SetImageModel(Button::STATE_DISABLED, disabled_image); InkDrop::Get(button)->SetBaseColorId(icon_color_id); } void SetToggledImageFromVectorIconWithColorId( ToggleImageButton* button, const gfx::VectorIcon& icon, ui::ColorId icon_color_id, ui::ColorId icon_disabled_color_id) { int dip_size = GetDefaultSizeOfVectorIcon(icon); const ui::ImageModel& normal_image = ui::ImageModel::FromVectorIcon(icon, icon_color_id, dip_size); const ui::ImageModel& disabled_image = ui::ImageModel::FromVectorIcon(icon, icon_disabled_color_id, dip_size); button->SetToggledImageModel(Button::STATE_NORMAL, normal_image); button->SetToggledImageModel(Button::STATE_DISABLED, disabled_image); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button_factory.cc
C++
unknown
6,387
// 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. // #ifndef UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_FACTORY_H_ #define UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_FACTORY_H_ #include <memory> #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_id.h" #include "ui/views/controls/button/button.h" #include "ui/views/views_export.h" namespace gfx { struct VectorIcon; } namespace views { class ImageButton; class ToggleImageButton; // Creates an ImageButton with an ink drop and a centered image built from a // vector icon that tracks color changes in NativeTheme. VIEWS_EXPORT std::unique_ptr<ImageButton> CreateVectorImageButtonWithNativeTheme( Button::PressedCallback callback, const gfx::VectorIcon& icon, absl::optional<int> dip_size = absl::nullopt); // Creates an ImageButton with an ink drop and a centered image in preparation // for applying a vector icon with SetImageFromVectorIcon below. VIEWS_EXPORT std::unique_ptr<ImageButton> CreateVectorImageButton( Button::PressedCallback callback); // Creates a ToggleImageButton with an ink drop and a centered image in // preparation for applying a vector icon from SetImageFromVectorIcon below. VIEWS_EXPORT std::unique_ptr<ToggleImageButton> CreateVectorToggleImageButton( Button::PressedCallback callback); // Configures an existing ImageButton with an ink drop and a centered image in // preparation for applying a vector icon with SetImageFromVectorIcon below. VIEWS_EXPORT void ConfigureVectorImageButton(ImageButton* button); // Sets images on |button| for STATE_NORMAL and STATE_DISABLED from the given // vector icon and colors. VIEWS_EXPORT void SetImageFromVectorIconWithColor(ImageButton* button, const gfx::VectorIcon& icon, SkColor icon_color, SkColor icon_disabled_color); // As above, but creates the images at the given size. VIEWS_EXPORT void SetImageFromVectorIconWithColor(ImageButton* button, const gfx::VectorIcon& icon, int dip_size, SkColor icon_color, SkColor icon_disabled_color); // As above, but sets the toggled images for a toggled image button // with a given icon color instead of deriving from a text color. VIEWS_EXPORT void SetToggledImageFromVectorIconWithColor( ToggleImageButton* button, const gfx::VectorIcon& icon, int dip_size, SkColor icon_color, SkColor disabled_color); // Sets images on |button| for STATE_NORMAL and STATE_DISABLED with the default // size from the given vector icon and colors, VIEWS_EXPORT void SetImageFromVectorIconWithColorId( ImageButton* button, const gfx::VectorIcon& icon, ui::ColorId icon_color_id, ui::ColorId icon_disabled_color_id, absl::optional<int> icon_size = absl::nullopt); // Sets images on a `ToggleImageButton` |button| for STATE_NORMAL and // STATE_DISABLED with the default size from the given vector icon and colors. VIEWS_EXPORT void SetToggledImageFromVectorIconWithColorId( ToggleImageButton* button, const gfx::VectorIcon& icon, ui::ColorId icon_color_id, ui::ColorId icon_disabled_color_id); } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_FACTORY_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button_factory.h
C++
unknown
3,628
// 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/image_button_factory.h" #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "components/vector_icons/vector_icons.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/test/ink_drop_host_test_api.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/test/views_test_base.h" namespace views { using ImageButtonFactoryTest = ViewsTestBase; TEST_F(ImageButtonFactoryTest, CreateVectorImageButton) { auto button = CreateVectorImageButton(Button::PressedCallback()); EXPECT_EQ(ImageButton::ALIGN_CENTER, button->h_alignment_); EXPECT_EQ(ImageButton::ALIGN_MIDDLE, button->v_alignment_); } class ImageButtonFactoryWidgetTest : public ViewsTestBase { public: ImageButtonFactoryWidgetTest() = default; ImageButtonFactoryWidgetTest(const ImageButtonFactoryWidgetTest&) = delete; ImageButtonFactoryWidgetTest& operator=(const ImageButtonFactoryWidgetTest&) = delete; ~ImageButtonFactoryWidgetTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); // Create a widget so that buttons can get access to their ColorProvider // instance. 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(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } ImageButton* AddImageButton(std::unique_ptr<ImageButton> button) { button_ = widget_->SetContentsView(std::move(button)); return button_; } protected: Widget* widget() { return widget_.get(); } ImageButton* button() { return button_; } private: std::unique_ptr<Widget> widget_; raw_ptr<ImageButton> button_ = nullptr; // owned by |widget_|. }; TEST_F(ImageButtonFactoryWidgetTest, SetImageFromVectorIconWithColor) { AddImageButton(CreateVectorImageButton(Button::PressedCallback())); SetImageFromVectorIconWithColor(button(), vector_icons::kCloseRoundedIcon, SK_ColorRED, SK_ColorRED); EXPECT_FALSE(button()->GetImage(Button::STATE_NORMAL).isNull()); EXPECT_FALSE(button()->GetImage(Button::STATE_DISABLED).isNull()); EXPECT_EQ(SK_ColorRED, InkDrop::Get(button())->GetBaseColor()); } TEST_F(ImageButtonFactoryWidgetTest, CreateVectorImageButtonWithNativeTheme) { AddImageButton(CreateVectorImageButtonWithNativeTheme( Button::PressedCallback(), vector_icons::kCloseRoundedIcon)); EXPECT_EQ(button()->GetColorProvider()->GetColor(ui::kColorIcon), InkDrop::Get(button())->GetBaseColor()); } TEST_F(ImageButtonFactoryWidgetTest, CreateVectorImageButtonWithNativeThemeWithSize) { constexpr int kSize = 15; AddImageButton(CreateVectorImageButtonWithNativeTheme( Button::PressedCallback(), vector_icons::kEditIcon, kSize)); EXPECT_EQ(kSize, button()->GetImage(Button::STATE_NORMAL).width()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button_factory_unittest.cc
C++
unknown
3,448
// 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/image_button.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/layout.h" #include "ui/views/border.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/views_test_base.h" namespace { gfx::ImageSkia CreateTestImage(int width, int height) { SkBitmap bitmap; bitmap.allocN32Pixels(width, height); return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); } class Parent : public views::View { public: Parent() = default; Parent(const Parent&) = delete; Parent& operator=(const Parent&) = delete; void ChildPreferredSizeChanged(views::View* view) override { pref_size_changed_calls_++; } int pref_size_changed_calls() const { return pref_size_changed_calls_; } private: int pref_size_changed_calls_ = 0; }; } // namespace namespace views { using ImageButtonTest = ViewsTestBase; TEST_F(ImageButtonTest, FocusBehavior) { ImageButton button; EXPECT_EQ(PlatformStyle::kDefaultFocusBehavior, button.GetFocusBehavior()); } TEST_F(ImageButtonTest, Basics) { ImageButton button; // Our image to paint starts empty. EXPECT_TRUE(button.GetImageToPaint().isNull()); // Without an image, buttons are 16x14 by default. EXPECT_EQ(gfx::Size(16, 14), button.GetPreferredSize()); // The minimum image size should be applied even when there is no image. button.SetMinimumImageSize(gfx::Size(5, 15)); EXPECT_EQ(gfx::Size(5, 15), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(16, 15), button.GetPreferredSize()); // Set a normal image. gfx::ImageSkia normal_image = CreateTestImage(10, 20); button.SetImage(Button::STATE_NORMAL, &normal_image); // Image uses normal image for painting. EXPECT_FALSE(button.GetImageToPaint().isNull()); EXPECT_EQ(10, button.GetImageToPaint().width()); EXPECT_EQ(20, button.GetImageToPaint().height()); // Preferred size is the normal button size. EXPECT_EQ(gfx::Size(10, 20), button.GetPreferredSize()); // Set a pushed image. gfx::ImageSkia pushed_image = CreateTestImage(11, 21); button.SetImage(Button::STATE_PRESSED, &pushed_image); // By convention, preferred size doesn't change, even though pushed image // is bigger. EXPECT_EQ(gfx::Size(10, 20), button.GetPreferredSize()); // We're still painting the normal image. EXPECT_FALSE(button.GetImageToPaint().isNull()); EXPECT_EQ(10, button.GetImageToPaint().width()); EXPECT_EQ(20, button.GetImageToPaint().height()); // The minimum image size should make the preferred size bigger. button.SetMinimumImageSize(gfx::Size(15, 5)); EXPECT_EQ(gfx::Size(15, 5), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(15, 20), button.GetPreferredSize()); button.SetMinimumImageSize(gfx::Size(15, 25)); EXPECT_EQ(gfx::Size(15, 25), button.GetMinimumImageSize()); EXPECT_EQ(gfx::Size(15, 25), button.GetPreferredSize()); } TEST_F(ImageButtonTest, SetAndGetImage) { ImageButton button; // Images start as null. EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_HOVERED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); // Setting images works as expected. gfx::ImageSkia image1 = CreateTestImage(10, 11); gfx::ImageSkia image2 = CreateTestImage(20, 21); button.SetImage(Button::STATE_NORMAL, &image1); button.SetImage(Button::STATE_HOVERED, &image2); EXPECT_TRUE( button.GetImage(Button::STATE_NORMAL).BackedBySameObjectAs(image1)); EXPECT_TRUE( button.GetImage(Button::STATE_HOVERED).BackedBySameObjectAs(image2)); EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); // ImageButton supports NULL image pointers. button.SetImage(Button::STATE_NORMAL, nullptr); EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); } TEST_F(ImageButtonTest, ImagePositionWithBorder) { ImageButton button; gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); // The image should be painted at the top-left corner. EXPECT_EQ(gfx::Point(), button.ComputeImagePaintPosition(image)); button.SetBorder(views::CreateEmptyBorder(gfx::Insets::TLBR(10, 5, 0, 0))); EXPECT_EQ(gfx::Point(5, 10), button.ComputeImagePaintPosition(image)); button.SetBorder(NullBorder()); button.SetBounds(0, 0, 50, 50); EXPECT_EQ(gfx::Point(), button.ComputeImagePaintPosition(image)); button.SetImageHorizontalAlignment(ImageButton::ALIGN_CENTER); button.SetImageVerticalAlignment(ImageButton::ALIGN_MIDDLE); EXPECT_EQ(gfx::Point(15, 10), button.ComputeImagePaintPosition(image)); button.SetBorder(views::CreateEmptyBorder(gfx::Insets::TLBR(10, 10, 0, 0))); EXPECT_EQ(gfx::Point(20, 15), button.ComputeImagePaintPosition(image)); // The entire button's size should take the border into account. EXPECT_EQ(gfx::Size(30, 40), button.GetPreferredSize()); // The border should be added on top of the minimum image size. button.SetMinimumImageSize(gfx::Size(30, 5)); EXPECT_EQ(gfx::Size(40, 40), button.GetPreferredSize()); } TEST_F(ImageButtonTest, LeftAlignedMirrored) { ImageButton button; gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); button.SetBounds(0, 0, 50, 30); button.SetImageVerticalAlignment(ImageButton::ALIGN_BOTTOM); button.SetDrawImageMirrored(true); // Because the coordinates are flipped, we should expect this to draw as if // it were ALIGN_RIGHT. EXPECT_EQ(gfx::Point(30, 0), button.ComputeImagePaintPosition(image)); } TEST_F(ImageButtonTest, RightAlignedMirrored) { ImageButton button; gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); button.SetBounds(0, 0, 50, 30); button.SetImageHorizontalAlignment(ImageButton::ALIGN_RIGHT); button.SetImageVerticalAlignment(ImageButton::ALIGN_BOTTOM); button.SetDrawImageMirrored(true); // Because the coordinates are flipped, we should expect this to draw as if // it were ALIGN_LEFT. EXPECT_EQ(gfx::Point(0, 0), button.ComputeImagePaintPosition(image)); } TEST_F(ImageButtonTest, PreferredSizeInvalidation) { Parent parent; ImageButton button; gfx::ImageSkia first_image = CreateTestImage(20, 30); gfx::ImageSkia second_image = CreateTestImage(50, 50); button.SetImage(Button::STATE_NORMAL, &first_image); parent.AddChildView(&button); ASSERT_EQ(0, parent.pref_size_changed_calls()); button.SetImage(Button::STATE_NORMAL, &first_image); EXPECT_EQ(0, parent.pref_size_changed_calls()); button.SetImage(Button::STATE_HOVERED, &second_image); EXPECT_EQ(0, parent.pref_size_changed_calls()); // Changing normal state image size leads to a change in preferred size. button.SetImage(Button::STATE_NORMAL, &second_image); EXPECT_EQ(1, parent.pref_size_changed_calls()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/image_button_unittest.cc
C++
unknown
7,167
// 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/label_button.h" #include <stddef.h> #include <algorithm> #include <utility> #include "base/lazy_instance.h" #include "base/logging.h" #include "build/build_config.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/ui_base_features.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/layer.h" #include "ui/gfx/animation/throb_animation.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/native_theme/native_theme.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/painter.h" #include "ui/views/style/platform_style.h" #include "ui/views/view_class_properties.h" #include "ui/views/window/dialog_delegate.h" namespace views { namespace { constexpr Button::ButtonState kEnabledStates[] = { Button::STATE_NORMAL, Button::STATE_HOVERED, Button::STATE_PRESSED}; } // namespace LabelButton::LabelButton(PressedCallback callback, const std::u16string& text, int button_context) : Button(std::move(callback)), cached_normal_font_list_( style::GetFont(button_context, style::STYLE_PRIMARY)), cached_default_button_font_list_( style::GetFont(button_context, style::STYLE_DIALOG_BUTTON_DEFAULT)) { ink_drop_container_ = AddChildView(std::make_unique<InkDropContainerView>()); ink_drop_container_->SetVisible(false); image_ = AddChildView(std::make_unique<ImageView>()); image_->SetCanProcessEventsWithinSubtree(false); label_ = AddChildView( std::make_unique<internal::LabelButtonLabel>(text, button_context)); label_->SetAutoColorReadabilityEnabled(false); label_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); SetAnimationDuration(base::Milliseconds(170)); SetTextInternal(text); } LabelButton::~LabelButton() { // 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); } gfx::ImageSkia LabelButton::GetImage(ButtonState for_state) const { for_state = ImageStateForState(for_state); return button_state_image_models_[for_state].Rasterize(GetColorProvider()); } void LabelButton::SetImage(ButtonState for_state, const gfx::ImageSkia& image) { SetImageModel(for_state, ui::ImageModel::FromImageSkia(image)); } void LabelButton::SetImageModel(ButtonState for_state, const ui::ImageModel& image_model) { if (button_state_image_models_[for_state] == image_model) return; const auto old_image_state = ImageStateForState(GetVisualState()); button_state_image_models_[for_state] = image_model; if (for_state == old_image_state || for_state == ImageStateForState(GetVisualState())) UpdateImage(); } bool LabelButton::HasImage(ButtonState for_state) const { return !button_state_image_models_[for_state].IsEmpty(); } const std::u16string& LabelButton::GetText() const { return label_->GetText(); } void LabelButton::SetText(const std::u16string& text) { SetTextInternal(text); } void LabelButton::ShrinkDownThenClearText() { if (GetText().empty()) return; // First, we recalculate preferred size for the new mode (without the label). shrinking_down_label_ = true; PreferredSizeChanged(); // Second, we clear the label right away if the button is already small. ClearTextIfShrunkDown(); } void LabelButton::SetTextColor(ButtonState for_state, SkColor color) { button_state_colors_[for_state] = color; if (for_state == STATE_DISABLED) label_->SetDisabledColor(color); else if (for_state == GetState()) label_->SetEnabledColor(color); explicitly_set_colors_[for_state] = true; } void LabelButton::SetTextColorId(ButtonState for_state, ui::ColorId color_id) { button_state_colors_[for_state] = color_id; if (for_state == STATE_DISABLED) { label_->SetDisabledColorId(color_id); } else if (for_state == GetState()) { label_->SetEnabledColorId(color_id); } explicitly_set_colors_[for_state] = true; } float LabelButton::GetFocusRingCornerRadius() const { return focus_ring_corner_radius_; } void LabelButton::SetFocusRingCornerRadius(float radius) { if (focus_ring_corner_radius_ == radius) return; focus_ring_corner_radius_ = radius; InkDrop::Get(this)->SetSmallCornerRadius(focus_ring_corner_radius_); InkDrop::Get(this)->SetLargeCornerRadius(focus_ring_corner_radius_); views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(), focus_ring_corner_radius_); OnPropertyChanged(&focus_ring_corner_radius_, kPropertyEffectsPaint); } void LabelButton::SetEnabledTextColors(absl::optional<SkColor> color) { if (color.has_value()) { for (auto state : kEnabledStates) { SetTextColor(state, color.value()); } return; } for (auto state : kEnabledStates) { explicitly_set_colors_[state] = false; } ResetColorsFromNativeTheme(); } void LabelButton::SetEnabledTextColorIds(ui::ColorId color_id) { for (auto state : kEnabledStates) { SetTextColorId(state, color_id); } } SkColor LabelButton::GetCurrentTextColor() const { return label_->GetEnabledColor(); } void LabelButton::SetTextShadows(const gfx::ShadowValues& shadows) { label_->SetShadows(shadows); } void LabelButton::SetTextSubpixelRenderingEnabled(bool enabled) { label_->SetSubpixelRenderingEnabled(enabled); } void LabelButton::SetElideBehavior(gfx::ElideBehavior elide_behavior) { label_->SetElideBehavior(elide_behavior); } void LabelButton::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { DCHECK_NE(gfx::ALIGN_TO_HEAD, alignment); if (GetHorizontalAlignment() == alignment) return; horizontal_alignment_ = alignment; OnPropertyChanged(&min_size_, kPropertyEffectsLayout); } gfx::HorizontalAlignment LabelButton::GetHorizontalAlignment() const { return horizontal_alignment_; } gfx::Size LabelButton::GetMinSize() const { return min_size_; } void LabelButton::SetMinSize(const gfx::Size& min_size) { if (GetMinSize() == min_size) return; min_size_ = min_size; OnPropertyChanged(&min_size_, kPropertyEffectsPreferredSizeChanged); } gfx::Size LabelButton::GetMaxSize() const { return max_size_; } void LabelButton::SetMaxSize(const gfx::Size& max_size) { if (GetMaxSize() == max_size) return; max_size_ = max_size; OnPropertyChanged(&max_size_, kPropertyEffectsPreferredSizeChanged); } bool LabelButton::GetIsDefault() const { return is_default_; } void LabelButton::SetIsDefault(bool is_default) { // TODO(estade): move this to MdTextButton once |style_| is removed. if (GetIsDefault() == is_default) return; is_default_ = is_default; // The default button has an accelerator for VKEY_RETURN, which clicks it. // Note that if PlatformStyle::kReturnClicksFocusedControl is true and another // button is focused, that button's VKEY_RETURN handler will take precedence. // See Button::GetKeyClickActionForEvent(). ui::Accelerator accel(ui::VKEY_RETURN, ui::EF_NONE); if (is_default) AddAccelerator(accel); else RemoveAccelerator(accel); OnPropertyChanged(&is_default_, UpdateStyleToIndicateDefaultStatus()); } int LabelButton::GetImageLabelSpacing() const { return image_label_spacing_; } void LabelButton::SetImageLabelSpacing(int spacing) { if (GetImageLabelSpacing() == spacing) return; image_label_spacing_ = spacing; OnPropertyChanged(&image_label_spacing_, kPropertyEffectsPreferredSizeChanged); } bool LabelButton::GetImageCentered() const { return image_centered_; } void LabelButton::SetImageCentered(bool image_centered) { if (GetImageCentered() == image_centered) return; image_centered_ = image_centered; OnPropertyChanged(&image_centered_, kPropertyEffectsLayout); } std::unique_ptr<LabelButtonBorder> LabelButton::CreateDefaultBorder() const { auto border = std::make_unique<LabelButtonBorder>(); border->set_insets(views::LabelButtonAssetBorder::GetDefaultInsets()); return border; } void LabelButton::SetBorder(std::unique_ptr<Border> border) { explicitly_set_border_ = true; View::SetBorder(std::move(border)); } void LabelButton::OnBoundsChanged(const gfx::Rect& previous_bounds) { ClearTextIfShrunkDown(); Button::OnBoundsChanged(previous_bounds); } gfx::Size LabelButton::CalculatePreferredSize() const { gfx::Size size = GetUnclampedSizeWithoutLabel(); // Account for the label only when the button is not shrinking down to hide // the label entirely. if (!shrinking_down_label_) { if (max_size_.width() > 0) { if (label_->GetMultiLine()) label_->SetMaximumWidth(max_size_.width() - size.width()); else label_->SetMaximumWidthSingleLine(max_size_.width() - size.width()); } const gfx::Size preferred_label_size = label_->GetPreferredSize(); size.Enlarge(preferred_label_size.width(), 0); size.SetToMax( gfx::Size(0, preferred_label_size.height() + GetInsets().height())); } size.SetToMax(GetMinSize()); // Clamp size to max size (if valid). const gfx::Size max_size = GetMaxSize(); if (max_size.width() > 0) size.set_width(std::min(max_size.width(), size.width())); if (max_size.height() > 0) size.set_height(std::min(max_size.height(), size.height())); return size; } gfx::Size LabelButton::GetMinimumSize() const { if (label_->GetElideBehavior() == gfx::ElideBehavior::NO_ELIDE) return GetPreferredSize(); gfx::Size size = image_->GetPreferredSize(); const gfx::Insets insets(GetInsets()); size.Enlarge(insets.width(), insets.height()); size.SetToMax(GetMinSize()); const gfx::Size max_size = GetMaxSize(); if (max_size.width() > 0) size.set_width(std::min(max_size.width(), size.width())); if (max_size.height() > 0) size.set_height(std::min(max_size.height(), size.height())); return size; } int LabelButton::GetHeightForWidth(int width) const { const gfx::Size size_without_label = GetUnclampedSizeWithoutLabel(); // Get label height for the remaining width. const int label_height_with_insets = label_->GetHeightForWidth(width - size_without_label.width()) + GetInsets().height(); // Height is the larger of size without label and label height with insets. int height = std::max(size_without_label.height(), label_height_with_insets); height = std::max(height, GetMinSize().height()); // Clamp height to the maximum height (if valid). const gfx::Size max_size = GetMaxSize(); if (max_size.height() > 0) return std::min(max_size.height(), height); return height; } void LabelButton::Layout() { gfx::Rect image_area = GetLocalBounds(); ink_drop_container_->SetBoundsRect(image_area); gfx::Insets insets = GetInsets(); // If the button have a limited space to fit in, the image and the label // may overlap with the border, which often times contains a lot of empty // padding. image_area.Inset(gfx::Insets::TLBR(0, insets.left(), 0, insets.right())); // The space that the label can use. Labels truncate horizontally, so there // is no need to allow the label to take up the complete horizontal space. gfx::Rect label_area = image_area; gfx::Size image_size = image_->GetPreferredSize(); image_size.SetToMin(image_area.size()); const auto horizontal_alignment = GetHorizontalAlignment(); if (!image_size.IsEmpty()) { int image_space = image_size.width() + GetImageLabelSpacing(); if (horizontal_alignment == gfx::ALIGN_RIGHT) label_area.Inset(gfx::Insets::TLBR(0, 0, 0, image_space)); else label_area.Inset(gfx::Insets::TLBR(0, image_space, 0, 0)); } gfx::Size label_size( std::min(label_area.width(), label_->GetPreferredSize().width()), label_area.height()); gfx::Point image_origin = image_area.origin(); if (label_->GetMultiLine() && !image_centered_) { // This code assumes the text is vertically centered. DCHECK_EQ(gfx::ALIGN_MIDDLE, label_->GetVerticalAlignment()); int label_height = label_->GetHeightForWidth(label_size.width()); int first_line_y = label_area.y() + (label_area.height() - label_height) / 2; int image_origin_y = first_line_y + (label_->font_list().GetHeight() - image_size.height()) / 2; image_origin.Offset(0, std::max(0, image_origin_y)); } else { image_origin.Offset(0, (image_area.height() - image_size.height()) / 2); } if (horizontal_alignment == gfx::ALIGN_CENTER) { const int spacing = (image_size.width() > 0 && label_size.width() > 0) ? GetImageLabelSpacing() : 0; const int total_width = image_size.width() + label_size.width() + spacing; image_origin.Offset((image_area.width() - total_width) / 2, 0); } else if (horizontal_alignment == gfx::ALIGN_RIGHT) { image_origin.Offset(image_area.width() - image_size.width(), 0); } image_->SetBoundsRect(gfx::Rect(image_origin, image_size)); gfx::Rect label_bounds = label_area; if (label_area.width() == label_size.width()) { // Label takes up the whole area. } else if (horizontal_alignment == gfx::ALIGN_CENTER) { label_bounds.ClampToCenteredSize(label_size); } else { label_bounds.set_size(label_size); if (horizontal_alignment == gfx::ALIGN_RIGHT) label_bounds.Offset(label_area.width() - label_size.width(), 0); } label_->SetBoundsRect(label_bounds); Button::Layout(); } void LabelButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { Button::GetAccessibleNodeData(node_data); if (GetIsDefault()) { node_data->AddState(ax::mojom::State::kDefault); } } ui::NativeTheme::Part LabelButton::GetThemePart() const { return ui::NativeTheme::kPushButton; } gfx::Rect LabelButton::GetThemePaintRect() const { return GetLocalBounds(); } ui::NativeTheme::State LabelButton::GetThemeState( ui::NativeTheme::ExtraParams* params) const { GetExtraParams(params); switch (GetState()) { case STATE_NORMAL: return ui::NativeTheme::kNormal; case STATE_HOVERED: return ui::NativeTheme::kHovered; case STATE_PRESSED: return ui::NativeTheme::kPressed; case STATE_DISABLED: return ui::NativeTheme::kDisabled; case STATE_COUNT: NOTREACHED_NORETURN(); } return ui::NativeTheme::kNormal; } const gfx::Animation* LabelButton::GetThemeAnimation() const { return &hover_animation(); } ui::NativeTheme::State LabelButton::GetBackgroundThemeState( ui::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return ui::NativeTheme::kNormal; } ui::NativeTheme::State LabelButton::GetForegroundThemeState( ui::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return ui::NativeTheme::kHovered; } void LabelButton::UpdateImage() { if (GetWidget()) image_->SetImage(GetImage(GetVisualState())); } void LabelButton::AddLayerToRegion(ui::Layer* new_layer, views::LayerRegion region) { image()->SetPaintToLayer(); image()->layer()->SetFillsBoundsOpaquely(false); ink_drop_container()->SetVisible(true); ink_drop_container()->AddLayerToRegion(new_layer, region); } void LabelButton::RemoveLayerFromRegions(ui::Layer* old_layer) { ink_drop_container()->RemoveLayerFromRegions(old_layer); ink_drop_container()->SetVisible(false); image()->DestroyLayer(); } void LabelButton::GetExtraParams(ui::NativeTheme::ExtraParams* params) const { params->button.checked = false; params->button.indeterminate = false; params->button.is_default = GetIsDefault(); params->button.is_focused = HasFocus() && IsAccessibilityFocusable(); params->button.has_border = false; params->button.classic_state = 0; params->button.background_color = label_->GetBackgroundColor(); } PropertyEffects LabelButton::UpdateStyleToIndicateDefaultStatus() { // Check that a subclass hasn't replaced the Label font. These buttons may // never be given default status. DCHECK_EQ(cached_normal_font_list_.GetFontSize(), label()->font_list().GetFontSize()); // TODO(tapted): This should use style::GetFont(), but this part can just be // deleted when default buttons no longer go bold. Colors will need updating // still. label_->SetFontList(GetIsDefault() ? cached_default_button_font_list_ : cached_normal_font_list_); ResetLabelEnabledColor(); return kPropertyEffectsPreferredSizeChanged; } void LabelButton::ChildPreferredSizeChanged(View* child) { PreferredSizeChanged(); } void LabelButton::AddedToWidget() { if (PlatformStyle::kInactiveWidgetControlsAppearDisabled) { paint_as_active_subscription_ = GetWidget()->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &LabelButton::VisualStateChanged, base::Unretained(this))); // Set the initial state correctly. VisualStateChanged(); } } void LabelButton::RemovedFromWidget() { paint_as_active_subscription_ = {}; } void LabelButton::OnFocus() { Button::OnFocus(); // Typically the border renders differently when focused. SchedulePaint(); } void LabelButton::OnBlur() { Button::OnBlur(); // Typically the border renders differently when focused. SchedulePaint(); } void LabelButton::OnThemeChanged() { Button::OnThemeChanged(); ResetColorsFromNativeTheme(); UpdateImage(); if (!explicitly_set_border_) View::SetBorder(CreateDefaultBorder()); ResetLabelEnabledColor(); // The entire button has to be repainted here, since the native theme can // define the tint for the entire background/border/focus ring. SchedulePaint(); } void LabelButton::SetFontList(const gfx::FontList& font_list) { cached_normal_font_list_ = font_list; cached_default_button_font_list_ = font_list; label_->SetFontList(cached_normal_font_list_); } void LabelButton::StateChanged(ButtonState old_state) { Button::StateChanged(old_state); ResetLabelEnabledColor(); VisualStateChanged(); } void LabelButton::SetTextInternal(const std::u16string& text) { SetAccessibleName(text); label_->SetText(text); // Setting text cancels ShrinkDownThenClearText(). const auto effects = shrinking_down_label_ ? kPropertyEffectsPreferredSizeChanged : kPropertyEffectsNone; shrinking_down_label_ = false; // TODO(pkasting): Remove this and forward callback subscriptions to the // underlying label property when Label is converted to properties. OnPropertyChanged(label_, effects); } void LabelButton::ClearTextIfShrunkDown() { const gfx::Size preferred_size = GetPreferredSize(); if (shrinking_down_label_ && width() <= preferred_size.width() && height() <= preferred_size.height()) { // Once the button shrinks down to its preferred size (that disregards the // current text), we finish the operation by clearing the text. SetText(std::u16string()); } } gfx::Size LabelButton::GetUnclampedSizeWithoutLabel() const { const gfx::Size image_size = image_->GetPreferredSize(); gfx::Size size = image_size; const gfx::Insets insets(GetInsets()); size.Enlarge(insets.width(), insets.height()); // Accommodate for spacing between image and text if both are present. if (image_size.width() > 0 && !GetText().empty() && !shrinking_down_label_) size.Enlarge(GetImageLabelSpacing(), 0); // Make the size at least as large as the minimum size needed by the border. if (GetBorder()) size.SetToMax(GetBorder()->GetMinimumSize()); return size; } Button::ButtonState LabelButton::GetVisualState() const { const auto* widget = GetWidget(); if (!widget || !widget->CanActivate() || !PlatformStyle::kInactiveWidgetControlsAppearDisabled) return GetState(); // Paint as inactive if neither this widget nor its parent should paint as // active. if (!widget->ShouldPaintAsActive() && !(widget->parent() && widget->parent()->ShouldPaintAsActive())) return STATE_DISABLED; return GetState(); } void LabelButton::VisualStateChanged() { if (GetWidget()) { UpdateImage(); UpdateBackgroundColor(); } label_->SetEnabled(GetVisualState() != STATE_DISABLED); } void LabelButton::ResetColorsFromNativeTheme() { // Since this is a LabelButton, use the label colors. ui::ColorId color_ids[STATE_COUNT] = { ui::kColorLabelForeground, ui::kColorLabelForeground, ui::kColorLabelForeground, ui::kColorLabelForegroundDisabled}; label_->SetBackground(nullptr); label_->SetAutoColorReadabilityEnabled(false); for (size_t state = STATE_NORMAL; state < STATE_COUNT; ++state) { if (!explicitly_set_colors_[state]) { SetTextColorId(static_cast<ButtonState>(state), color_ids[state]); explicitly_set_colors_[state] = false; } } } void LabelButton::ResetLabelEnabledColor() { if (GetState() == STATE_DISABLED) { return; } const absl::variant<SkColor, ui::ColorId>& color = button_state_colors_[GetState()]; if (absl::holds_alternative<SkColor>(color) && label_->GetEnabledColor() != absl::get<SkColor>(color)) { label_->SetEnabledColor(absl::get<SkColor>(color)); } else if (absl::holds_alternative<ui::ColorId>(color)) { // Omitting the check that the new color id differs from the existing color // id, because the setter already does that check. label_->SetEnabledColorId(absl::get<ui::ColorId>(color)); } } Button::ButtonState LabelButton::ImageStateForState( ButtonState for_state) const { return button_state_image_models_[for_state].IsEmpty() ? STATE_NORMAL : for_state; } void LabelButton::FlipCanvasOnPaintForRTLUIChanged() { image_->SetFlipCanvasOnPaintForRTLUI(GetFlipCanvasOnPaintForRTLUI()); } BEGIN_METADATA(LabelButton, Button) ADD_PROPERTY_METADATA(std::u16string, Text) ADD_PROPERTY_METADATA(gfx::HorizontalAlignment, HorizontalAlignment) ADD_PROPERTY_METADATA(gfx::Size, MinSize) ADD_PROPERTY_METADATA(gfx::Size, MaxSize) ADD_PROPERTY_METADATA(bool, IsDefault) ADD_PROPERTY_METADATA(int, ImageLabelSpacing) ADD_PROPERTY_METADATA(bool, ImageCentered) ADD_PROPERTY_METADATA(float, FocusRingCornerRadius) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button.cc
C++
unknown
22,808
// 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_LABEL_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_H_ #include <array> #include <memory> #include "base/functional/bind.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button_label.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/native_theme_delegate.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" namespace views { class InkDropContainerView; class LabelButtonBorder; // LabelButton is a button with text and an icon. class VIEWS_EXPORT LabelButton : public Button, public NativeThemeDelegate { public: METADATA_HEADER(LabelButton); // Creates a LabelButton with pressed events sent to |callback| and label // |text|. |button_context| is a value from views::style::TextContext and // determines the appearance of |text|. explicit LabelButton(PressedCallback callback = PressedCallback(), const std::u16string& text = std::u16string(), int button_context = style::CONTEXT_BUTTON); LabelButton(const LabelButton&) = delete; LabelButton& operator=(const LabelButton&) = delete; ~LabelButton() override; // Gets or sets the image shown for the specified button state. // GetImage returns the image for STATE_NORMAL if the state's image is empty. virtual gfx::ImageSkia GetImage(ButtonState for_state) const; // TODO(http://crbug.com/1100034) prefer SetImageModel over SetImage(). void SetImage(ButtonState for_state, const gfx::ImageSkia& image); virtual void SetImageModel(ButtonState for_state, const ui::ImageModel& image_model); bool HasImage(ButtonState for_state) const; // Gets or sets the text shown on the button. const std::u16string& GetText() const; virtual void SetText(const std::u16string& text); // Makes the button report its preferred size without the label. This lets // AnimatingLayoutManager gradually shrink the button until the text is // invisible, at which point the text gets cleared. Think of this as // transitioning from the current text to SetText(""). // Note that the layout manager (or manual SetBounds calls) need to be // configured to eventually hit the the button's preferred size (or smaller) // or the text will never be cleared. void ShrinkDownThenClearText(); // Sets the text color shown for the specified button |for_state| to |color|. // TODO(crbug.com/1421316): Get rid of SkColor versions of these functions in // favor of the ColorId versions. void SetTextColor(ButtonState for_state, SkColor color); // Sets the text color as above but using ColorId. void SetTextColorId(ButtonState for_state, ui::ColorId color_id); // Sets the text colors shown for the non-disabled states to |color|. // TODO(crbug.com/1421316): Get rid of SkColor versions of these functions in // favor of the ColorId versions. virtual void SetEnabledTextColors(absl::optional<SkColor> color); // Sets the text colors shown for the non-disabled states to |color_id|. void SetEnabledTextColorIds(ui::ColorId color_id); // Gets the current state text color. SkColor GetCurrentTextColor() const; // Sets drop shadows underneath the text. void SetTextShadows(const gfx::ShadowValues& shadows); // Sets whether subpixel rendering is used on the label. void SetTextSubpixelRenderingEnabled(bool enabled); // Sets the elide behavior of this button. void SetElideBehavior(gfx::ElideBehavior elide_behavior); // Sets the horizontal alignment used for the button; reversed in RTL. The // optional image will lead the text, unless the button is right-aligned. void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); gfx::HorizontalAlignment GetHorizontalAlignment() const; gfx::Size GetMinSize() const; void SetMinSize(const gfx::Size& min_size); gfx::Size GetMaxSize() const; void SetMaxSize(const gfx::Size& max_size); // Gets or sets the option to handle the return key; false by default. bool GetIsDefault() const; void SetIsDefault(bool is_default); // Sets the spacing between the image and the text. int GetImageLabelSpacing() const; void SetImageLabelSpacing(int spacing); // Gets or sets the option to place the image aligned with the center of the // the label. The image is not centered for CheckBox and RadioButton only. bool GetImageCentered() const; void SetImageCentered(bool image_centered); // Sets the corner radius of the focus ring around the button. float GetFocusRingCornerRadius() const; void SetFocusRingCornerRadius(float radius); // Creates the default border for this button. This can be overridden by // subclasses. virtual std::unique_ptr<LabelButtonBorder> CreateDefaultBorder() const; // Button: void SetBorder(std::unique_ptr<Border> border) override; void OnBoundsChanged(const gfx::Rect& previous_bounds) override; gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; int GetHeightForWidth(int w) const override; void Layout() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void AddLayerToRegion(ui::Layer* new_layer, views::LayerRegion region) override; void RemoveLayerFromRegions(ui::Layer* old_layer) override; // NativeThemeDelegate: ui::NativeTheme::Part GetThemePart() const override; gfx::Rect GetThemePaintRect() const override; ui::NativeTheme::State GetThemeState( ui::NativeTheme::ExtraParams* params) const override; const gfx::Animation* GetThemeAnimation() const override; ui::NativeTheme::State GetBackgroundThemeState( ui::NativeTheme::ExtraParams* params) const override; ui::NativeTheme::State GetForegroundThemeState( ui::NativeTheme::ExtraParams* params) const override; // Sets the font list used by this button. void SetFontList(const gfx::FontList& font_list); protected: ImageView* image() const { return image_; } Label* label() const { return label_; } InkDropContainerView* ink_drop_container() const { return ink_drop_container_; } bool explicitly_set_normal_color() const { return explicitly_set_colors_[STATE_NORMAL]; } const std::array<bool, STATE_COUNT>& explicitly_set_colors() const { return explicitly_set_colors_; } void set_explicitly_set_colors(const std::array<bool, STATE_COUNT>& colors) { explicitly_set_colors_ = colors; } // Updates the image view to contain the appropriate button state image. void UpdateImage(); // Updates the background color, if the background color is state-sensitive. virtual void UpdateBackgroundColor() {} // Returns the current visual appearance of the button. This takes into // account both the button's underlying state, the state of the containing // widget, and the parent of the containing widget. ButtonState GetVisualState() const; // Fills |params| with information about the button. virtual void GetExtraParams(ui::NativeTheme::ExtraParams* params) const; // Changes the visual styling to match changes in the default state. Returns // the PropertyEffects triggered as a result. virtual PropertyEffects UpdateStyleToIndicateDefaultStatus(); // Button: void ChildPreferredSizeChanged(View* child) override; void AddedToWidget() override; void RemovedFromWidget() override; void OnFocus() override; void OnBlur() override; void OnThemeChanged() override; void StateChanged(ButtonState old_state) override; private: void SetTextInternal(const std::u16string& text); void ClearTextIfShrunkDown(); // Gets the preferred size (without respecting min_size_ or max_size_), but // does not account for the label. This is shared between GetHeightForWidth // and CalculatePreferredSize. GetHeightForWidth will subtract the width // returned from this method to get width available for the label while // CalculatePreferredSize will just add the preferred width from the label. // Both methods will then use the max of inset height + label height and this // height as total height, and clamp to min/max sizes as appropriate. gfx::Size GetUnclampedSizeWithoutLabel() const; // Updates the portions of the object that might change in response to a // change in the value returned by GetVisualState(). void VisualStateChanged(); // Resets colors from the NativeTheme, explicitly set colors are unchanged. void ResetColorsFromNativeTheme(); // Updates additional state related to focus or default status, rather than // merely the Button::state(). E.g. ensures the label text color is // correct for the current background. void ResetLabelEnabledColor(); // Returns the state whose image is shown for |for_state|, by falling back to // STATE_NORMAL when |for_state|'s image is empty. ButtonState ImageStateForState(ButtonState for_state) const; void FlipCanvasOnPaintForRTLUIChanged(); // The image and label shown in the button. raw_ptr<ImageView> image_; raw_ptr<internal::LabelButtonLabel> label_; // A separate view is necessary to hold the ink drop layer so that it can // be stacked below |image_| and on top of |label_|, without resorting to // drawing |label_| on a layer (which can mess with subpixel anti-aliasing). raw_ptr<InkDropContainerView> ink_drop_container_; // The cached font lists in the normal and default button style. The latter // may be bold. gfx::FontList cached_normal_font_list_; gfx::FontList cached_default_button_font_list_; // The image models and colors for each button state. ui::ImageModel button_state_image_models_[STATE_COUNT] = {}; absl::variant<SkColor, ui::ColorId> button_state_colors_[STATE_COUNT] = {}; // Used to track whether SetTextColor() has been invoked. std::array<bool, STATE_COUNT> explicitly_set_colors_ = {}; // |min_size_| and |max_size_| may be set to clamp the preferred size. gfx::Size min_size_; gfx::Size max_size_; // A flag indicating that this button should not include the label in its // desired size. Furthermore, once the bounds of the button adapt to this // desired size, the text in the label should get cleared. bool shrinking_down_label_ = false; // Flag indicating default handling of the return key via an accelerator. // Whether or not the button appears or behaves as the default button in its // current context; bool is_default_ = false; // True if current border was set by SetBorder. bool explicitly_set_border_ = false; // A flag indicating that this button's image should be aligned with the // center of the label when multiline is enabled. This shouldn't be the case // for a CheckBox or a RadioButton. bool image_centered_ = true; // Spacing between the image and the text. int image_label_spacing_ = LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_LABEL_HORIZONTAL); // Alignment of the button. This can be different from the alignment of the // text; for example, the label may be set to ALIGN_TO_HEAD (alignment matches // text direction) while |this| is laid out as ALIGN_LEFT (alignment matches // UI direction). gfx::HorizontalAlignment horizontal_alignment_ = gfx::ALIGN_LEFT; // Corner radius of the focus ring. float focus_ring_corner_radius_ = FocusRing::kDefaultCornerRadiusDp; base::CallbackListSubscription paint_as_active_subscription_; base::CallbackListSubscription flip_canvas_on_paint_subscription_ = AddFlipCanvasOnPaintForRTLUIChangedCallback( base::BindRepeating(&LabelButton::FlipCanvasOnPaintForRTLUIChanged, base::Unretained(this))); }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, LabelButton, Button) VIEW_BUILDER_PROPERTY(std::u16string, Text) VIEW_BUILDER_PROPERTY(gfx::HorizontalAlignment, HorizontalAlignment) VIEW_BUILDER_PROPERTY(gfx::Size, MinSize) VIEW_BUILDER_PROPERTY(gfx::Size, MaxSize) VIEW_BUILDER_PROPERTY(absl::optional<SkColor>, EnabledTextColors) VIEW_BUILDER_PROPERTY(bool, IsDefault) VIEW_BUILDER_PROPERTY(int, ImageLabelSpacing) VIEW_BUILDER_PROPERTY(bool, ImageCentered) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, LabelButton) #endif // UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button.h
C++
unknown
12,806
// 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/label_button_border.h" #include <utility> #include "cc/paint/paint_flags.h" #include "ui/gfx/animation/animation.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/sys_color_change_listener.h" #include "ui/native_theme/native_theme.h" #include "ui/views/border.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/native_theme_delegate.h" #include "ui/views/resources/grit/views_resources.h" namespace views { namespace { // The text-button hot and pushed image IDs; normal is unadorned by default. constexpr int kTextHoveredImages[] = IMAGE_GRID(IDR_TEXTBUTTON_HOVER); constexpr int kTextPressedImages[] = IMAGE_GRID(IDR_TEXTBUTTON_PRESSED); // A helper function to paint the appropriate broder images. void PaintHelper(LabelButtonAssetBorder* border, gfx::Canvas* canvas, ui::NativeTheme::State state, const gfx::Rect& rect, const ui::NativeTheme::ExtraParams& extra) { Painter* painter = border->GetPainter(extra.button.is_focused, Button::GetButtonStateFrom(state)); // Paint any corresponding unfocused painter if there is no focused painter. if (!painter && extra.button.is_focused) painter = border->GetPainter(false, Button::GetButtonStateFrom(state)); if (painter) Painter::PaintPainterAt(canvas, painter, rect); } } // namespace LabelButtonBorder::LabelButtonBorder() = default; LabelButtonBorder::~LabelButtonBorder() = default; bool LabelButtonBorder::PaintsButtonState(bool focused, Button::ButtonState state) { return false; } void LabelButtonBorder::Paint(const View& view, gfx::Canvas* canvas) {} gfx::Insets LabelButtonBorder::GetInsets() const { return insets_; } gfx::Size LabelButtonBorder::GetMinimumSize() const { return gfx::Size(); } LabelButtonAssetBorder::LabelButtonAssetBorder() { set_insets(GetDefaultInsets()); SetPainter(false, Button::STATE_HOVERED, Painter::CreateImageGridPainter(kTextHoveredImages)); SetPainter(false, Button::STATE_PRESSED, Painter::CreateImageGridPainter(kTextPressedImages)); } LabelButtonAssetBorder::~LabelButtonAssetBorder() = default; // static gfx::Insets LabelButtonAssetBorder::GetDefaultInsets() { return LayoutProvider::Get()->GetInsetsMetric( InsetsMetric::INSETS_LABEL_BUTTON); } bool LabelButtonAssetBorder::PaintsButtonState(bool focused, Button::ButtonState state) { // PaintHelper() above will paint the unfocused painter for a given state if // the button is focused, but there is no focused painter. return GetPainter(focused, state) || (focused && GetPainter(false, state)); } void LabelButtonAssetBorder::Paint(const View& view, gfx::Canvas* canvas) { const NativeThemeDelegate* native_theme_delegate = static_cast<const LabelButton*>(&view); gfx::Rect rect(native_theme_delegate->GetThemePaintRect()); ui::NativeTheme::ExtraParams extra; const gfx::Animation* animation = native_theme_delegate->GetThemeAnimation(); ui::NativeTheme::State state = native_theme_delegate->GetThemeState(&extra); if (animation && animation->is_animating()) { // Linearly interpolate background and foreground painters during animation. uint8_t fg_alpha = static_cast<uint8_t>(animation->CurrentValueBetween(0, 255)); const SkRect sk_rect = gfx::RectToSkRect(rect); cc::PaintCanvasAutoRestore auto_restore(canvas->sk_canvas(), false); canvas->sk_canvas()->saveLayer(sk_rect, cc::PaintFlags()); { // First, modulate the background by 1 - alpha. cc::PaintCanvasAutoRestore auto_restore_alpha(canvas->sk_canvas(), false); canvas->SaveLayerAlpha(255 - fg_alpha, rect); state = native_theme_delegate->GetBackgroundThemeState(&extra); PaintHelper(this, canvas, state, rect, extra); } // Then modulate the foreground by alpha, and blend using kPlus_Mode. cc::PaintFlags flags; flags.setAlphaf(fg_alpha / 255.0f); flags.setBlendMode(SkBlendMode::kPlus); canvas->sk_canvas()->saveLayer(sk_rect, flags); state = native_theme_delegate->GetForegroundThemeState(&extra); PaintHelper(this, canvas, state, rect, extra); } else { PaintHelper(this, canvas, state, rect, extra); } } gfx::Size LabelButtonAssetBorder::GetMinimumSize() const { gfx::Size minimum_size; for (const auto& painters_for_focus_state : painters_) { for (const auto& painter_for_button_state : painters_for_focus_state) { if (painter_for_button_state) minimum_size.SetToMax(painter_for_button_state->GetMinimumSize()); } } return minimum_size; } Painter* LabelButtonAssetBorder::GetPainter(bool focused, Button::ButtonState state) { return painters_[focused ? 1 : 0][state].get(); } void LabelButtonAssetBorder::SetPainter(bool focused, Button::ButtonState state, std::unique_ptr<Painter> painter) { painters_[focused ? 1 : 0][state] = std::move(painter); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_border.cc
C++
unknown
5,479
// 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_LABEL_BUTTON_BORDER_H_ #define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_BORDER_H_ #include <memory> #include "ui/gfx/geometry/insets.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/painter.h" namespace views { // An empty Border with customizable insets used by a LabelButton. class VIEWS_EXPORT LabelButtonBorder : public Border { public: LabelButtonBorder(); LabelButtonBorder(const LabelButtonBorder&) = delete; LabelButtonBorder& operator=(const LabelButtonBorder&) = delete; ~LabelButtonBorder() override; void set_insets(const gfx::Insets& insets) { insets_ = insets; } // Returns true if |this| is able to paint for the given |focused| and |state| // values. virtual bool PaintsButtonState(bool focused, Button::ButtonState state); // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Insets GetInsets() const override; gfx::Size GetMinimumSize() const override; private: gfx::Insets insets_; }; // A Border that paints a LabelButton's background frame using image assets. class VIEWS_EXPORT LabelButtonAssetBorder : public LabelButtonBorder { public: LabelButtonAssetBorder(); LabelButtonAssetBorder(const LabelButtonAssetBorder&) = delete; LabelButtonAssetBorder& operator=(const LabelButtonAssetBorder&) = delete; ~LabelButtonAssetBorder() override; // Returns the default insets. static gfx::Insets GetDefaultInsets(); // Overridden from LabelButtonBorder: bool PaintsButtonState(bool focused, Button::ButtonState state) override; // Overridden from Border: void Paint(const View& view, gfx::Canvas* canvas) override; gfx::Size GetMinimumSize() const override; // Get or set the painter used for the specified |focused| button |state|. // LabelButtonAssetBorder takes and retains ownership of |painter|. Painter* GetPainter(bool focused, Button::ButtonState state); void SetPainter(bool focused, Button::ButtonState state, std::unique_ptr<Painter> painter); private: // The painters used for each unfocused or focused button state. std::unique_ptr<Painter> painters_[2][Button::STATE_COUNT]; }; } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_BORDER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_border.h
C++
unknown
2,468
// 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/label_button_label.h" #include <string> #include "third_party/skia/include/core/SkColor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/layout/layout_provider.h" namespace views::internal { LabelButtonLabel::LabelButtonLabel(const std::u16string& text, int text_context) : Label(text, text_context, style::STYLE_PRIMARY) {} LabelButtonLabel::~LabelButtonLabel() = default; void LabelButtonLabel::SetDisabledColor(SkColor color) { requested_disabled_color_ = color; if (!GetEnabled()) Label::SetEnabledColor(color); } void LabelButtonLabel::SetDisabledColorId( absl::optional<ui::ColorId> color_id) { if (!color_id.has_value()) { return; } requested_disabled_color_ = color_id.value(); if (!GetEnabled()) { Label::SetEnabledColorId(color_id.value()); } } absl::optional<ui::ColorId> LabelButtonLabel::GetDisabledColorId() const { if (absl::holds_alternative<ui::ColorId>(requested_disabled_color_)) { return absl::get<ui::ColorId>(requested_disabled_color_); } return absl::nullopt; } void LabelButtonLabel::SetEnabledColor(SkColor color) { requested_enabled_color_ = color; if (GetEnabled()) Label::SetEnabledColor(color); } void LabelButtonLabel::SetEnabledColorId(absl::optional<ui::ColorId> color_id) { if (!color_id.has_value()) { return; } requested_enabled_color_ = color_id.value(); if (GetEnabled()) { Label::SetEnabledColorId(color_id.value()); } } absl::optional<ui::ColorId> LabelButtonLabel::GetEnabledColorId() const { if (absl::holds_alternative<ui::ColorId>(requested_enabled_color_)) { return absl::get<ui::ColorId>(requested_enabled_color_); } return absl::nullopt; } void LabelButtonLabel::OnThemeChanged() { SetColorForEnableState(); Label::OnThemeChanged(); } void LabelButtonLabel::OnEnabledChanged() { SetColorForEnableState(); } void LabelButtonLabel::SetColorForEnableState() { const absl::variant<absl::monostate, SkColor, ui::ColorId>& color = GetEnabled() ? requested_enabled_color_ : requested_disabled_color_; if (absl::holds_alternative<SkColor>(color)) { Label::SetEnabledColor(absl::get<SkColor>(color)); } else if (absl::holds_alternative<ui::ColorId>(color)) { Label::SetEnabledColorId(absl::get<ui::ColorId>(color)); } else { // Get default color Id. const ui::ColorId default_color_id = LayoutProvider::Get()->GetTypographyProvider().GetColorId( GetTextContext(), GetEnabled() ? style::STYLE_PRIMARY : style::STYLE_DISABLED); // Set default color Id. Label::SetEnabledColorId(default_color_id); } } BEGIN_METADATA(LabelButtonLabel, Label) ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, EnabledColorId) ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, DisabledColorId) END_METADATA } // namespace views::internal
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_label.cc
C++
unknown
3,033
// 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. #ifndef UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_LABEL_H_ #define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_LABEL_H_ #include <string> #include "base/functional/bind.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/color/color_id.h" #include "ui/views/controls/label.h" #include "ui/views/views_export.h" namespace views::internal { // A Label subclass that can be disabled. This is only used internally for // views::LabelButton. class VIEWS_EXPORT LabelButtonLabel : public Label { public: METADATA_HEADER(LabelButtonLabel); LabelButtonLabel(const std::u16string& text, int text_context); LabelButtonLabel(const LabelButtonLabel&) = delete; LabelButtonLabel& operator=(const LabelButtonLabel&) = delete; ~LabelButtonLabel() override; // Set an explicit disabled color. This will stop the Label responding to // changes in the native theme for disabled colors. void SetDisabledColor(SkColor color); // Sets/Gets the explicit disable color as above, but using color_id. void SetDisabledColorId(absl::optional<ui::ColorId> color_id); absl::optional<ui::ColorId> GetDisabledColorId() const; // Label: void SetEnabledColor(SkColor color) override; // Sets/Gets the explicit enabled color with color_id. void SetEnabledColorId(absl::optional<ui::ColorId> color_id); absl::optional<ui::ColorId> GetEnabledColorId() const; protected: // Label: void OnThemeChanged() override; private: void OnEnabledChanged(); void SetColorForEnableState(); absl::variant<absl::monostate, SkColor, ui::ColorId> requested_enabled_color_; absl::variant<absl::monostate, SkColor, ui::ColorId> requested_disabled_color_; base::CallbackListSubscription enabled_changed_subscription_ = AddEnabledChangedCallback( base::BindRepeating(&LabelButtonLabel::OnEnabledChanged, base::Unretained(this))); }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, LabelButtonLabel, Label) VIEW_BUILDER_PROPERTY(absl::optional<ui::ColorId>, EnabledColorId) VIEW_BUILDER_PROPERTY(absl::optional<ui::ColorId>, DisabledColorId) END_VIEW_BUILDER } // namespace views::internal DEFINE_VIEW_BUILDER(VIEWS_EXPORT, internal::LabelButtonLabel) #endif // UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_LABEL_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_label.h
C++
unknown
2,512
// 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/label_button_label.h" #include <map> #include <memory> #include "base/memory/raw_ptr.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/views/test/views_test_base.h" namespace views { namespace { // LabelButtonLabel subclass that reports its text color whenever a paint is // scheduled. class TestLabel : public internal::LabelButtonLabel { public: explicit TestLabel(SkColor* last_color, absl::optional<ui::ColorId>* last_color_id) : LabelButtonLabel(std::u16string(), views::style::CONTEXT_BUTTON), last_color_(last_color), last_color_id_(last_color_id) {} TestLabel(const TestLabel&) = delete; TestLabel& operator=(const TestLabel&) = delete; // LabelButtonLabel: void OnDidSchedulePaint(const gfx::Rect& r) override { LabelButtonLabel::OnDidSchedulePaint(r); *last_color_ = GetEnabledColor(); *last_color_id_ = Label::GetEnabledColorId(); } private: raw_ptr<SkColor> last_color_; raw_ptr<absl::optional<ui::ColorId>> last_color_id_; }; } // namespace class LabelButtonLabelTest : public ViewsTestBase { public: LabelButtonLabelTest() = default; LabelButtonLabelTest(const LabelButtonLabelTest&) = delete; LabelButtonLabelTest& operator=(const LabelButtonLabelTest&) = delete; void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateTestWidget(); widget_->GetNativeTheme()->set_use_dark_colors(false); label_ = widget_->SetContentsView( std::make_unique<TestLabel>(&last_color_, &last_color_id_)); label_->SetAutoColorReadabilityEnabled(false); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } void SetUseDarkColors(bool use_dark_colors) { ui::NativeTheme* native_theme = widget_->GetNativeTheme(); native_theme->set_use_dark_colors(use_dark_colors); native_theme->NotifyOnNativeThemeUpdated(); } protected: SkColor last_color_ = gfx::kPlaceholderColor; absl::optional<ui::ColorId> last_color_id_; std::unique_ptr<views::Widget> widget_; raw_ptr<TestLabel> label_; }; // Test that LabelButtonLabel reacts properly to themed and overridden colors. TEST_F(LabelButtonLabelTest, Colors) { // First one comes from the default theme. This check ensures the SK_ColorRED // placeholder initializers were replaced. SkColor default_theme_enabled_color = label_->GetColorProvider()->GetColor(ui::kColorLabelForeground); EXPECT_EQ(default_theme_enabled_color, last_color_); label_->SetEnabled(false); SkColor default_theme_disabled_color = label_->GetColorProvider()->GetColor(ui::kColorLabelForegroundDisabled); EXPECT_EQ(default_theme_disabled_color, last_color_); SetUseDarkColors(true); SkColor dark_theme_disabled_color = label_->GetColorProvider()->GetColor(ui::kColorLabelForegroundDisabled); EXPECT_NE(default_theme_disabled_color, dark_theme_disabled_color); EXPECT_EQ(dark_theme_disabled_color, last_color_); label_->SetEnabled(true); SkColor dark_theme_enabled_color = label_->GetColorProvider()->GetColor(ui::kColorLabelForeground); EXPECT_NE(default_theme_enabled_color, dark_theme_enabled_color); EXPECT_EQ(dark_theme_enabled_color, last_color_); // Override the theme for the disabled color. label_->SetDisabledColor(SK_ColorRED); EXPECT_NE(SK_ColorRED, dark_theme_disabled_color); // Still enabled, so not RED yet. EXPECT_EQ(dark_theme_enabled_color, last_color_); label_->SetEnabled(false); EXPECT_EQ(SK_ColorRED, last_color_); label_->SetDisabledColor(SK_ColorMAGENTA); EXPECT_EQ(SK_ColorMAGENTA, last_color_); // Disabled still overridden after a theme change. SetUseDarkColors(false); EXPECT_EQ(SK_ColorMAGENTA, last_color_); // The enabled color still gets its value from the theme. label_->SetEnabled(true); EXPECT_EQ(default_theme_enabled_color, last_color_); label_->SetEnabledColor(SK_ColorYELLOW); label_->SetDisabledColor(SK_ColorCYAN); EXPECT_EQ(SK_ColorYELLOW, last_color_); label_->SetEnabled(false); EXPECT_EQ(SK_ColorCYAN, last_color_); } // Test that LabelButtonLabel reacts properly to themed and overridden color // ids. TEST_F(LabelButtonLabelTest, ColorIds) { // Default color id was set. EXPECT_TRUE(last_color_id_.has_value()); // Override the theme for the enabled color. label_->SetEnabledColorId(ui::kColorAccent); EXPECT_EQ(last_color_id_.value(), ui::kColorAccent); EXPECT_EQ(last_color_, label_->GetColorProvider()->GetColor(ui::kColorAccent)); label_->SetEnabled(false); label_->SetDisabledColorId(ui::kColorBadgeBackground); EXPECT_EQ(last_color_id_.value(), ui::kColorBadgeBackground); EXPECT_EQ(last_color_, label_->GetColorProvider()->GetColor(ui::kColorBadgeBackground)); // Still overridden after a theme change. SetUseDarkColors(false); EXPECT_EQ(last_color_id_.value(), ui::kColorBadgeBackground); EXPECT_EQ(last_color_, label_->GetColorProvider()->GetColor(ui::kColorBadgeBackground)); label_->SetEnabled(true); EXPECT_EQ(last_color_id_.value(), ui::kColorAccent); EXPECT_EQ(last_color_, label_->GetColorProvider()->GetColor(ui::kColorAccent)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_label_unittest.cc
C++
unknown
5,514
// 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/label_button.h" #include <algorithm> #include <string> #include <utility> #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/ui_base_switches.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/events/test/event_generator.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/text_utils.h" #include "ui/native_theme/native_theme.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/test/ink_drop_host_test_api.h" #include "ui/views/animation/test/test_ink_drop.h" #include "ui/views/border.h" #include "ui/views/buildflags.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/test/widget_test.h" #include "ui/views/view_test_api.h" #include "ui/views/widget/widget_utils.h" using base::ASCIIToUTF16; namespace { gfx::ImageSkia CreateTestImage(int width, int height) { SkBitmap bitmap; bitmap.allocN32Pixels(width, height); return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); } } // namespace namespace views { // Testing button that exposes protected methods. class TestLabelButton : public LabelButton { public: explicit TestLabelButton(const std::u16string& text = std::u16string(), int button_context = style::CONTEXT_BUTTON) : LabelButton(Button::PressedCallback(), text, button_context) {} TestLabelButton(const TestLabelButton&) = delete; TestLabelButton& operator=(const TestLabelButton&) = delete; void SetMultiLine(bool multi_line) { label()->SetMultiLine(multi_line); } using LabelButton::GetVisualState; using LabelButton::image; using LabelButton::label; using LabelButton::OnThemeChanged; }; class LabelButtonTest : public test::WidgetTest { public: LabelButtonTest() = default; LabelButtonTest(const LabelButtonTest&) = delete; LabelButtonTest& operator=(const LabelButtonTest&) = delete; // testing::Test: void SetUp() override { WidgetTest::SetUp(); // Make a Widget to host the button. This ensures appropriate borders are // used (which could be derived from the Widget's NativeTheme). test_widget_ = CreateTopLevelPlatformWidget(); // The test code below is not prepared to handle dark mode. test_widget_->GetNativeTheme()->set_use_dark_colors(false); // Ensure the Widget is active, since LabelButton appearance in inactive // Windows is platform-dependent. test_widget_->Show(); // Place the button into a separate container view which itself does no // layouts. This will isolate the button from the client view which does // a fill layout by default. auto* container = test_widget_->client_view()->AddChildView(std::make_unique<View>()); button_ = container->AddChildView(std::make_unique<TestLabelButton>()); // Establish the expected text colors for testing changes due to state. themed_normal_text_color_ = button_->GetColorProvider()->GetColor(ui::kColorLabelForeground); // For styled buttons only, platforms other than Desktop Linux either ignore // ColorProvider and use a hardcoded black or (on Mac) have a ColorProvider // that reliably returns black. styled_normal_text_color_ = SK_ColorBLACK; #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \ BUILDFLAG(ENABLE_DESKTOP_AURA) // The Linux theme provides a non-black highlight text color, but it's not // used for styled buttons. styled_highlight_text_color_ = styled_normal_text_color_ = button_->GetColorProvider()->GetColor(ui::kColorButtonForeground); #else styled_highlight_text_color_ = styled_normal_text_color_; #endif } void TearDown() override { test_widget_->CloseNow(); WidgetTest::TearDown(); } void UseDarkColors() { ui::NativeTheme* native_theme = test_widget_->GetNativeTheme(); native_theme->set_use_dark_colors(true); native_theme->NotifyOnNativeThemeUpdated(); } protected: raw_ptr<TestLabelButton> button_ = nullptr; SkColor themed_normal_text_color_ = 0; SkColor styled_normal_text_color_ = 0; SkColor styled_highlight_text_color_ = 0; private: raw_ptr<Widget> test_widget_ = nullptr; }; TEST_F(LabelButtonTest, FocusBehavior) { EXPECT_EQ(PlatformStyle::kDefaultFocusBehavior, button_->GetFocusBehavior()); } TEST_F(LabelButtonTest, Init) { const std::u16string text(u"abc"); button_->SetText(text); EXPECT_TRUE(button_->GetImage(Button::STATE_NORMAL).isNull()); EXPECT_TRUE(button_->GetImage(Button::STATE_HOVERED).isNull()); EXPECT_TRUE(button_->GetImage(Button::STATE_PRESSED).isNull()); EXPECT_TRUE(button_->GetImage(Button::STATE_DISABLED).isNull()); EXPECT_EQ(text, button_->GetText()); ui::AXNodeData accessible_node_data; button_->GetAccessibleNodeData(&accessible_node_data); EXPECT_EQ(ax::mojom::Role::kButton, accessible_node_data.role); EXPECT_EQ(text, accessible_node_data.GetString16Attribute( ax::mojom::StringAttribute::kName)); EXPECT_FALSE(button_->GetIsDefault()); EXPECT_EQ(Button::STATE_NORMAL, button_->GetState()); EXPECT_EQ(button_->image()->parent(), button_); EXPECT_EQ(button_->label()->parent(), button_); } TEST_F(LabelButtonTest, Label) { EXPECT_TRUE(button_->GetText().empty()); const gfx::FontList font_list = button_->label()->font_list(); const std::u16string short_text(u"abcdefghijklm"); const std::u16string long_text(u"abcdefghijklmnopqrstuvwxyz"); const int short_text_width = gfx::GetStringWidth(short_text, font_list); const int long_text_width = gfx::GetStringWidth(long_text, font_list); EXPECT_LT(button_->GetPreferredSize().width(), short_text_width); button_->SetText(short_text); EXPECT_GT(button_->GetPreferredSize().height(), font_list.GetHeight()); EXPECT_GT(button_->GetPreferredSize().width(), short_text_width); EXPECT_LT(button_->GetPreferredSize().width(), long_text_width); button_->SetText(long_text); EXPECT_GT(button_->GetPreferredSize().width(), long_text_width); button_->SetText(short_text); EXPECT_GT(button_->GetPreferredSize().width(), short_text_width); EXPECT_LT(button_->GetPreferredSize().width(), long_text_width); // Clamp the size to a maximum value. button_->SetText(long_text); button_->SetMaxSize(gfx::Size(short_text_width, 1)); const gfx::Size preferred_size = button_->GetPreferredSize(); EXPECT_LE(preferred_size.width(), short_text_width); EXPECT_EQ(1, preferred_size.height()); // Clamp the size to a minimum value. button_->SetText(short_text); button_->SetMaxSize(gfx::Size()); button_->SetMinSize(gfx::Size(long_text_width, font_list.GetHeight() * 2)); EXPECT_EQ(button_->GetPreferredSize(), gfx::Size(long_text_width, font_list.GetHeight() * 2)); } // Tests LabelButton's usage of SetMaximumWidthSingleLine. TEST_F(LabelButtonTest, LabelPreferredSizeWithMaxWidth) { const std::string text_cases[] = { {"The"}, {"The quick"}, {"The quick brown"}, {"The quick brown fox"}, {"The quick brown fox jumps"}, {"The quick brown fox jumps over"}, {"The quick brown fox jumps over the"}, {"The quick brown fox jumps over the lazy"}, {"The quick brown fox jumps over the lazy dog"}, }; const int width_cases[] = { 10, 30, 50, 70, 90, 110, 130, 170, 200, 500, }; for (bool is_multiline : {false, true}) { button_->SetMultiLine(is_multiline); for (bool set_image : {false, true}) { if (set_image) button_->SetImage(Button::STATE_NORMAL, CreateTestImage(16, 16)); bool preferred_size_is_sometimes_narrower_than_max = false; bool preferred_height_shrinks_as_max_width_grows = false; for (const auto& text_case : text_cases) { for (int width_case : width_cases) { const gfx::Size old_preferred_size = button_->GetPreferredSize(); button_->SetText(ASCIIToUTF16(text_case)); button_->SetMaxSize(gfx::Size(width_case, 30)); const gfx::Size preferred_size = button_->GetPreferredSize(); EXPECT_LE(preferred_size.width(), width_case); if (preferred_size.width() < width_case) preferred_size_is_sometimes_narrower_than_max = true; if (preferred_size.height() < old_preferred_size.height()) preferred_height_shrinks_as_max_width_grows = true; } } EXPECT_TRUE(preferred_size_is_sometimes_narrower_than_max); if (is_multiline) EXPECT_TRUE(preferred_height_shrinks_as_max_width_grows); } } } TEST_F(LabelButtonTest, LabelShrinkDown) { ASSERT_TRUE(button_->GetText().empty()); const gfx::FontList font_list = button_->label()->font_list(); const std::u16string text(u"abcdefghijklm"); const int text_width = gfx::GetStringWidth(text, font_list); ASSERT_LT(button_->GetPreferredSize().width(), text_width); button_->SetText(text); EXPECT_GT(button_->GetPreferredSize().width(), text_width); button_->SetSize(button_->GetPreferredSize()); // When shrinking, the button should report again the size with no label // (while keeping the label). button_->ShrinkDownThenClearText(); EXPECT_EQ(button_->GetText(), text); EXPECT_LT(button_->GetPreferredSize().width(), text_width); // After the layout manager resizes the button to it's desired size, it's text // should be empty again. button_->SetSize(button_->GetPreferredSize()); EXPECT_TRUE(button_->GetText().empty()); } TEST_F(LabelButtonTest, LabelShrinksDownOnManualSetBounds) { ASSERT_TRUE(button_->GetText().empty()); ASSERT_GT(button_->GetPreferredSize().width(), 1); const std::u16string text(u"abcdefghijklm"); button_->SetText(text); EXPECT_EQ(button_->GetText(), text); button_->SetSize(button_->GetPreferredSize()); button_->SetBoundsRect(gfx::Rect(button_->GetPreferredSize())); button_->ShrinkDownThenClearText(); // Manually setting a smaller size should also clear text. button_->SetBoundsRect(gfx::Rect(1, 1)); EXPECT_TRUE(button_->GetText().empty()); } TEST_F(LabelButtonTest, LabelShrinksDownCanceledBySettingText) { ASSERT_TRUE(button_->GetText().empty()); const gfx::FontList font_list = button_->label()->font_list(); const std::u16string text(u"abcdefghijklm"); const int text_width = gfx::GetStringWidth(text, font_list); ASSERT_LT(button_->GetPreferredSize().width(), text_width); button_->SetText(text); EXPECT_GT(button_->GetPreferredSize().width(), text_width); button_->SetBoundsRect(gfx::Rect(button_->GetPreferredSize())); // When shrinking, the button should report again the size with no label // (while keeping the label). button_->ShrinkDownThenClearText(); EXPECT_EQ(button_->GetText(), text); gfx::Size shrinking_size = button_->GetPreferredSize(); EXPECT_LT(shrinking_size.width(), text_width); // When we SetText() again, the shrinking gets canceled. button_->SetText(text); EXPECT_GT(button_->GetPreferredSize().width(), text_width); // Even if the layout manager resizes the button to it's size desired for // shrinking, it's text does not get cleared and it still prefers having space // for its label. button_->SetSize(shrinking_size); EXPECT_FALSE(button_->GetText().empty()); EXPECT_GT(button_->GetPreferredSize().width(), text_width); } TEST_F( LabelButtonTest, LabelShrinksDownImmediatelyIfAlreadySmallerThanPreferredSizeWithoutLabel) { button_->SetBoundsRect(gfx::Rect(1, 1)); button_->SetText(u"abcdefghijklm"); // Shrinking the text down when it's already shrunk down (its size is smaller // than preferred without label) should clear the text immediately. EXPECT_FALSE(button_->GetText().empty()); button_->ShrinkDownThenClearText(); EXPECT_TRUE(button_->GetText().empty()); } // Test behavior of View::GetAccessibleNodeData() for buttons when setting a // label. TEST_F(LabelButtonTest, AccessibleState) { ui::AXNodeData accessible_node_data; button_->GetAccessibleNodeData(&accessible_node_data); EXPECT_EQ(ax::mojom::Role::kButton, accessible_node_data.role); EXPECT_EQ(std::u16string(), accessible_node_data.GetString16Attribute( ax::mojom::StringAttribute::kName)); // Without a label (e.g. image-only), the accessible name should automatically // be set from the tooltip. const std::u16string tooltip_text = u"abc"; button_->SetTooltipText(tooltip_text); button_->GetAccessibleNodeData(&accessible_node_data); EXPECT_EQ(tooltip_text, accessible_node_data.GetString16Attribute( ax::mojom::StringAttribute::kName)); EXPECT_EQ(std::u16string(), button_->GetText()); // Setting a label overrides the tooltip text. const std::u16string label_text = u"def"; button_->SetText(label_text); button_->GetAccessibleNodeData(&accessible_node_data); EXPECT_EQ(label_text, accessible_node_data.GetString16Attribute( ax::mojom::StringAttribute::kName)); EXPECT_EQ(label_text, button_->GetText()); EXPECT_EQ(tooltip_text, button_->GetTooltipText(gfx::Point())); } // Test View::GetAccessibleNodeData() for default buttons. TEST_F(LabelButtonTest, AccessibleDefaultState) { { // If SetIsDefault() is not called, the ax default state should not be set. ui::AXNodeData ax_data; button_->GetViewAccessibility().GetAccessibleNodeData(&ax_data); EXPECT_FALSE(ax_data.HasState(ax::mojom::State::kDefault)); } { button_->SetIsDefault(true); ui::AXNodeData ax_data; button_->GetViewAccessibility().GetAccessibleNodeData(&ax_data); EXPECT_TRUE(ax_data.HasState(ax::mojom::State::kDefault)); } { button_->SetIsDefault(false); ui::AXNodeData ax_data; button_->GetViewAccessibility().GetAccessibleNodeData(&ax_data); EXPECT_FALSE(ax_data.HasState(ax::mojom::State::kDefault)); } } TEST_F(LabelButtonTest, Image) { const int small_size = 50, large_size = 100; const gfx::ImageSkia small_image = CreateTestImage(small_size, small_size); const gfx::ImageSkia large_image = CreateTestImage(large_size, large_size); EXPECT_LT(button_->GetPreferredSize().width(), small_size); EXPECT_LT(button_->GetPreferredSize().height(), small_size); button_->SetImage(Button::STATE_NORMAL, small_image); EXPECT_GT(button_->GetPreferredSize().width(), small_size); EXPECT_GT(button_->GetPreferredSize().height(), small_size); EXPECT_LT(button_->GetPreferredSize().width(), large_size); EXPECT_LT(button_->GetPreferredSize().height(), large_size); button_->SetImage(Button::STATE_NORMAL, large_image); EXPECT_GT(button_->GetPreferredSize().width(), large_size); EXPECT_GT(button_->GetPreferredSize().height(), large_size); button_->SetImage(Button::STATE_NORMAL, small_image); EXPECT_GT(button_->GetPreferredSize().width(), small_size); EXPECT_GT(button_->GetPreferredSize().height(), small_size); EXPECT_LT(button_->GetPreferredSize().width(), large_size); EXPECT_LT(button_->GetPreferredSize().height(), large_size); // Clamp the size to a maximum value. button_->SetImage(Button::STATE_NORMAL, large_image); button_->SetMaxSize(gfx::Size(large_size, 1)); EXPECT_EQ(button_->GetPreferredSize(), gfx::Size(large_size, 1)); // Clamp the size to a minimum value. button_->SetImage(Button::STATE_NORMAL, small_image); button_->SetMaxSize(gfx::Size()); button_->SetMinSize(gfx::Size(large_size, large_size)); EXPECT_EQ(button_->GetPreferredSize(), gfx::Size(large_size, large_size)); } TEST_F(LabelButtonTest, ImageAlignmentWithMultilineLabel) { const std::u16string text( u"Some long text that would result in multiline label"); button_->SetText(text); const int max_label_width = 40; button_->label()->SetMultiLine(true); button_->label()->SetMaximumWidth(max_label_width); const int image_size = 16; const gfx::ImageSkia image = CreateTestImage(image_size, image_size); button_->SetImage(Button::STATE_NORMAL, image); button_->SetBoundsRect(gfx::Rect(button_->GetPreferredSize())); views::test::RunScheduledLayout(button_); int y_origin_centered = button_->image()->origin().y(); button_->SetBoundsRect(gfx::Rect(button_->GetPreferredSize())); button_->SetImageCentered(false); views::test::RunScheduledLayout(button_); int y_origin_not_centered = button_->image()->origin().y(); EXPECT_LT(y_origin_not_centered, y_origin_centered); } TEST_F(LabelButtonTest, LabelAndImage) { const gfx::FontList font_list = button_->label()->font_list(); const std::u16string text(u"abcdefghijklm"); const int text_width = gfx::GetStringWidth(text, font_list); const int image_size = 50; const gfx::ImageSkia image = CreateTestImage(image_size, image_size); ASSERT_LT(font_list.GetHeight(), image_size); EXPECT_LT(button_->GetPreferredSize().width(), text_width); EXPECT_LT(button_->GetPreferredSize().width(), image_size); EXPECT_LT(button_->GetPreferredSize().height(), image_size); button_->SetText(text); EXPECT_GT(button_->GetPreferredSize().width(), text_width); EXPECT_GT(button_->GetPreferredSize().height(), font_list.GetHeight()); EXPECT_LT(button_->GetPreferredSize().width(), text_width + image_size); EXPECT_LT(button_->GetPreferredSize().height(), image_size); button_->SetImage(Button::STATE_NORMAL, image); EXPECT_GT(button_->GetPreferredSize().width(), text_width + image_size); EXPECT_GT(button_->GetPreferredSize().height(), image_size); // Layout and ensure the image is left of the label except for ALIGN_RIGHT. // (A proper parent view or layout manager would Layout on its invalidations). // Also make sure CENTER alignment moves the label compared to LEFT alignment. gfx::Size button_size = button_->GetPreferredSize(); button_size.Enlarge(50, 0); button_->SetSize(button_size); views::test::RunScheduledLayout(button_); EXPECT_LT(button_->image()->bounds().right(), button_->label()->bounds().x()); int left_align_label_midpoint = button_->label()->bounds().CenterPoint().x(); button_->SetHorizontalAlignment(gfx::ALIGN_CENTER); views::test::RunScheduledLayout(button_); EXPECT_LT(button_->image()->bounds().right(), button_->label()->bounds().x()); int center_align_label_midpoint = button_->label()->bounds().CenterPoint().x(); EXPECT_LT(left_align_label_midpoint, center_align_label_midpoint); button_->SetHorizontalAlignment(gfx::ALIGN_RIGHT); views::test::RunScheduledLayout(button_); EXPECT_LT(button_->label()->bounds().right(), button_->image()->bounds().x()); button_->SetText(std::u16string()); EXPECT_LT(button_->GetPreferredSize().width(), text_width + image_size); EXPECT_GT(button_->GetPreferredSize().width(), image_size); EXPECT_GT(button_->GetPreferredSize().height(), image_size); button_->SetImage(Button::STATE_NORMAL, gfx::ImageSkia()); EXPECT_LT(button_->GetPreferredSize().width(), image_size); EXPECT_LT(button_->GetPreferredSize().height(), image_size); // Clamp the size to a minimum value. button_->SetText(text); button_->SetImage(Button::STATE_NORMAL, image); button_->SetMinSize(gfx::Size((text_width + image_size) * 2, image_size * 2)); EXPECT_EQ(button_->GetPreferredSize().width(), (text_width + image_size) * 2); EXPECT_EQ(button_->GetPreferredSize().height(), image_size * 2); // Clamp the size to a maximum value. button_->SetMinSize(gfx::Size()); button_->SetMaxSize(gfx::Size(1, 1)); EXPECT_EQ(button_->GetPreferredSize(), gfx::Size(1, 1)); } TEST_F(LabelButtonTest, LabelWrapAndImageAlignment) { LayoutProvider* provider = LayoutProvider::Get(); const gfx::FontList font_list = button_->label()->font_list(); const std::u16string text(u"abcdefghijklm abcdefghijklm"); const int text_wrap_width = gfx::GetStringWidth(text, font_list) / 2; const int image_spacing = provider->GetDistanceMetric(DISTANCE_RELATED_LABEL_HORIZONTAL); button_->SetText(text); button_->label()->SetMultiLine(true); const int image_size = font_list.GetHeight(); const gfx::ImageSkia image = CreateTestImage(image_size, image_size); ASSERT_EQ(font_list.GetHeight(), image.width()); button_->SetImage(Button::STATE_NORMAL, image); button_->SetImageCentered(false); button_->SetMaxSize( gfx::Size(image.width() + image_spacing + text_wrap_width, 0)); gfx::Insets button_insets = button_->GetInsets(); gfx::Size preferred_size = button_->GetPreferredSize(); preferred_size.set_height(button_->GetHeightForWidth(preferred_size.width())); button_->SetSize(preferred_size); views::test::RunScheduledLayout(button_); EXPECT_EQ(preferred_size.width(), image.width() + image_spacing + text_wrap_width); EXPECT_EQ(preferred_size.height(), font_list.GetHeight() * 2 + button_insets.height()); // The image should be centered on the first line of the multi-line label EXPECT_EQ(button_->image()->y(), (font_list.GetHeight() - button_->image()->height()) / 2 + button_insets.top()); } // This test was added because GetHeightForWidth and GetPreferredSize were // inconsistent. GetPreferredSize would account for image size + insets whereas // GetHeightForWidth wouldn't. As of writing they share a large chunk of // logic, but this remains in place so they don't diverge as easily. TEST_F(LabelButtonTest, GetHeightForWidthConsistentWithGetPreferredSize) { const std::u16string text(u"abcdefghijklm"); constexpr int kTinyImageSize = 2; constexpr int kLargeImageSize = 50; const int font_height = button_->label()->font_list().GetHeight(); // Parts of this test (accounting for label height) doesn't make sense if the // font is smaller than the tiny test image and insets. ASSERT_GT(font_height, button_->GetInsets().height() + kTinyImageSize); // Parts of this test (accounting for image insets) doesn't make sense if the // font is larger than the large test image. ASSERT_LT(font_height, kLargeImageSize); button_->SetText(text); for (int image_size : {kTinyImageSize, kLargeImageSize}) { SCOPED_TRACE(testing::Message() << "Image Size: " << image_size); // Set image and reset monotonic min size for every test iteration. const gfx::ImageSkia image = CreateTestImage(image_size, image_size); button_->SetImage(Button::STATE_NORMAL, image); const gfx::Size preferred_button_size = button_->GetPreferredSize(); // The preferred button height should be the larger of image / label // heights + inset height. EXPECT_EQ(std::max(image_size, font_height) + button_->GetInsets().height(), preferred_button_size.height()); // Make sure this preferred height is consistent with GetHeightForWidth(). EXPECT_EQ(preferred_button_size.height(), button_->GetHeightForWidth(preferred_button_size.width())); } } // Ensure that the text used for button labels correctly adjusts in response // to provided style::TextContext values. TEST_F(LabelButtonTest, TextSizeFromContext) { constexpr style::TextContext kDefaultContext = style::CONTEXT_BUTTON; // Although CONTEXT_DIALOG_TITLE isn't used for buttons, picking a style with // a small delta risks finding a font with a different point-size but with the // same maximum glyph height. constexpr style::TextContext kAlternateContext = style::CONTEXT_DIALOG_TITLE; // First sanity that the TextConstants used in the test give different sizes. const auto get_delta = [](auto context) { return TypographyProvider() .GetFont(context, style::STYLE_PRIMARY) .GetFontSize() - gfx::FontList().GetFontSize(); }; TypographyProvider typography_provider; int default_delta = get_delta(kDefaultContext); int alternate_delta = get_delta(kAlternateContext); EXPECT_LT(default_delta, alternate_delta); const std::u16string text(u"abcdefghijklm"); button_->SetText(text); EXPECT_EQ(default_delta, button_->label()->font_list().GetFontSize() - gfx::FontList().GetFontSize()); TestLabelButton* alternate_button = new TestLabelButton(text, kAlternateContext); button_->parent()->AddChildView(alternate_button); EXPECT_EQ(alternate_delta, alternate_button->label()->font_list().GetFontSize() - gfx::FontList().GetFontSize()); // The button size increases when the font size is increased. EXPECT_LT(button_->GetPreferredSize().width(), alternate_button->GetPreferredSize().width()); EXPECT_LT(button_->GetPreferredSize().height(), alternate_button->GetPreferredSize().height()); } TEST_F(LabelButtonTest, ChangeTextSize) { const std::u16string text(u"abc"); const std::u16string longer_text(u"abcdefghijklm"); button_->SetText(text); button_->SizeToPreferredSize(); gfx::Rect bounds(button_->bounds()); const int original_width = button_->GetPreferredSize().width(); EXPECT_EQ(original_width, bounds.width()); // Reserve more space in the button. bounds.set_width(bounds.width() * 10); button_->SetBoundsRect(bounds); // Label view in the button is sized to short text. const int original_label_width = button_->label()->bounds().width(); // The button preferred size and the label size increase when the text size // is increased. button_->SetText(longer_text); EXPECT_TRUE(ViewTestApi(button_).needs_layout()); views::test::RunScheduledLayout(button_); EXPECT_GT(button_->label()->bounds().width(), original_label_width * 2); EXPECT_GT(button_->GetPreferredSize().width(), original_width * 2); // The button and the label view return to its original size when the original // text is restored. button_->SetText(text); EXPECT_TRUE(ViewTestApi(button_).needs_layout()); views::test::RunScheduledLayout(button_); EXPECT_EQ(original_label_width, button_->label()->bounds().width()); EXPECT_EQ(original_width, button_->GetPreferredSize().width()); } TEST_F(LabelButtonTest, ChangeLabelImageSpacing) { button_->SetText(u"abc"); button_->SetImage(Button::STATE_NORMAL, CreateTestImage(50, 50)); const int kOriginalSpacing = 5; button_->SetImageLabelSpacing(kOriginalSpacing); const int original_width = button_->GetPreferredSize().width(); // Increasing the spacing between the text and label should increase the size. button_->SetImageLabelSpacing(2 * kOriginalSpacing); EXPECT_GT(button_->GetPreferredSize().width(), original_width); // The button shrinks if the original spacing is restored. button_->SetImageLabelSpacing(kOriginalSpacing); EXPECT_EQ(original_width, button_->GetPreferredSize().width()); } // Ensure the label gets the correct style when pressed or becoming default. TEST_F(LabelButtonTest, HighlightedButtonStyle) { // The ColorProvider might not provide SK_ColorBLACK, but it should be the // same for normal and pressed states. EXPECT_EQ(themed_normal_text_color_, button_->label()->GetEnabledColor()); button_->SetState(Button::STATE_PRESSED); EXPECT_EQ(themed_normal_text_color_, button_->label()->GetEnabledColor()); } // Ensure the label resets the enabled color after LabelButton::OnThemeChanged() // is invoked. TEST_F(LabelButtonTest, OnThemeChanged) { ASSERT_NE(button_->GetNativeTheme()->GetPlatformHighContrastColorScheme(), ui::NativeTheme::PlatformHighContrastColorScheme::kDark); ASSERT_NE(button_->label()->GetBackgroundColor(), SK_ColorBLACK); EXPECT_EQ(themed_normal_text_color_, button_->label()->GetEnabledColor()); button_->label()->SetBackgroundColor(SK_ColorBLACK); button_->label()->SetAutoColorReadabilityEnabled(true); EXPECT_NE(themed_normal_text_color_, button_->label()->GetEnabledColor()); button_->OnThemeChanged(); EXPECT_EQ(themed_normal_text_color_, button_->label()->GetEnabledColor()); } TEST_F(LabelButtonTest, SetEnabledTextColorsResetsToThemeColors) { constexpr SkColor kReplacementColor = SK_ColorCYAN; // This test doesn't make sense if the used colors are equal. EXPECT_NE(themed_normal_text_color_, kReplacementColor); // Initially the test should have the normal colors. EXPECT_EQ(themed_normal_text_color_, button_->label()->GetEnabledColor()); // Setting the enabled text colors should replace the label's enabled color. button_->SetEnabledTextColors(kReplacementColor); EXPECT_EQ(kReplacementColor, button_->label()->GetEnabledColor()); // Toggle dark mode. This should not replace the enabled text color as it's // been manually overridden above. UseDarkColors(); EXPECT_EQ(kReplacementColor, button_->label()->GetEnabledColor()); // Removing the enabled text color restore colors from the new theme, not // the original colors used before the theme changed. button_->SetEnabledTextColors(absl::nullopt); EXPECT_NE(themed_normal_text_color_, button_->label()->GetEnabledColor()); } TEST_F(LabelButtonTest, SetEnabledTextColorIds) { ASSERT_NE(ui::kColorLabelForeground, ui::kColorAccent); // Initially the test should have the normal colors. EXPECT_EQ(button_->label()->GetEnabledColorId(), ui::kColorLabelForeground); // Setting the enabled text colors should replace the label's enabled color. button_->SetEnabledTextColorIds(ui::kColorAccent); EXPECT_EQ(button_->label()->GetEnabledColorId(), ui::kColorAccent); // Toggle dark mode. This should not replace the enabled text color as it's // been manually overridden above. UseDarkColors(); EXPECT_EQ(button_->label()->GetEnabledColorId(), ui::kColorAccent); EXPECT_EQ(button_->label()->GetEnabledColor(), button_->GetColorProvider()->GetColor(ui::kColorAccent)); } TEST_F(LabelButtonTest, ImageOrLabelGetClipped) { const std::u16string text(u"abc"); button_->SetText(text); const gfx::FontList font_list = button_->label()->font_list(); const int image_size = font_list.GetHeight(); button_->SetImage(Button::STATE_NORMAL, CreateTestImage(image_size, image_size)); button_->SetBoundsRect(gfx::Rect(button_->GetPreferredSize())); // The border size + the content height is more than button's preferred size. button_->SetBorder(CreateEmptyBorder( gfx::Insets::TLBR(image_size / 2, 0, image_size / 2, 0))); views::test::RunScheduledLayout(button_); // Ensure that content (image and label) doesn't get clipped by the border. EXPECT_GE(button_->image()->height(), image_size); EXPECT_GE(button_->label()->height(), image_size); } TEST_F(LabelButtonTest, UpdateImageAfterSettingImageModel) { auto is_showing_image = [&](const gfx::ImageSkia& image) { return button_->image()->GetImage().BackedBySameObjectAs(image); }; auto normal_image = CreateTestImage(16, 16); button_->SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(normal_image)); EXPECT_TRUE(is_showing_image(normal_image)); // When the button has no specific disabled image, changing the normal image // while the button is disabled should update the currently-visible image. normal_image = CreateTestImage(16, 16); button_->SetState(Button::STATE_DISABLED); button_->SetImageModel(Button::STATE_NORMAL, ui::ImageModel::FromImageSkia(normal_image)); EXPECT_TRUE(is_showing_image(normal_image)); // Any specific disabled image should take precedence over the normal image. auto disabled_image = CreateTestImage(16, 16); button_->SetImageModel(Button::STATE_DISABLED, ui::ImageModel::FromImageSkia(disabled_image)); EXPECT_TRUE(is_showing_image(disabled_image)); // Removing the disabled image should result in falling back to the normal // image again. button_->SetImageModel(Button::STATE_DISABLED, ui::ImageModel()); EXPECT_TRUE(is_showing_image(normal_image)); } // Test fixture for a LabelButton that has an ink drop configured. class InkDropLabelButtonTest : public ViewsTestBase { public: InkDropLabelButtonTest() = default; InkDropLabelButtonTest(const InkDropLabelButtonTest&) = delete; InkDropLabelButtonTest& operator=(const InkDropLabelButtonTest&) = delete; // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); // Create a widget so that the Button can query the hover state // correctly. widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 20, 20); widget_->Init(std::move(params)); widget_->Show(); button_ = widget_->SetContentsView(std::make_unique<LabelButton>( Button::PressedCallback(), std::u16string())); test_ink_drop_ = new test::TestInkDrop(); test::InkDropHostTestApi(InkDrop::Get(button_)) .SetInkDrop(base::WrapUnique(test_ink_drop_.get())); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } protected: // Required to host the test target. std::unique_ptr<Widget> widget_; // The test target. raw_ptr<LabelButton> button_ = nullptr; // Weak ptr, |button_| owns the instance. raw_ptr<test::TestInkDrop> test_ink_drop_ = nullptr; }; TEST_F(InkDropLabelButtonTest, HoverStateAfterMouseEnterAndExitEvents) { ui::test::EventGenerator event_generator(GetRootWindow(widget_.get())); const gfx::Point out_of_bounds_point( button_->GetBoundsInScreen().bottom_right() + gfx::Vector2d(1, 1)); const gfx::Point in_bounds_point(button_->GetBoundsInScreen().CenterPoint()); event_generator.MoveMouseTo(out_of_bounds_point); EXPECT_FALSE(test_ink_drop_->is_hovered()); event_generator.MoveMouseTo(in_bounds_point); EXPECT_TRUE(test_ink_drop_->is_hovered()); event_generator.MoveMouseTo(out_of_bounds_point); EXPECT_FALSE(test_ink_drop_->is_hovered()); } // Verifies the target event handler View is the |LabelButton| and not any of // the child Views. TEST_F(InkDropLabelButtonTest, TargetEventHandler) { View* target_view = widget_->GetRootView()->GetEventHandlerForPoint( button_->bounds().CenterPoint()); EXPECT_EQ(button_, target_view); } class LabelButtonVisualStateTest : public test::WidgetTest { public: LabelButtonVisualStateTest() = default; LabelButtonVisualStateTest(const LabelButtonVisualStateTest&) = delete; LabelButtonVisualStateTest& operator=(const LabelButtonVisualStateTest&) = delete; // testing::Test: void SetUp() override { WidgetTest::SetUp(); test_widget_ = CreateTopLevelPlatformWidget(); dummy_widget_ = CreateTopLevelPlatformWidget(); button_ = MakeButtonAsContent(test_widget_); style_of_inactive_widget_ = PlatformStyle::kInactiveWidgetControlsAppearDisabled ? Button::STATE_DISABLED : Button::STATE_NORMAL; } void TearDown() override { test_widget_->CloseNow(); dummy_widget_->CloseNow(); WidgetTest::TearDown(); } protected: std::unique_ptr<Widget> CreateActivatableChildWidget(Widget* parent) { auto child = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.parent = parent->GetNativeView(); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.activatable = Widget::InitParams::Activatable::kYes; child->Init(std::move(params)); child->SetContentsView(std::make_unique<View>()); return child; } TestLabelButton* MakeButtonAsContent(Widget* widget) { return widget->GetContentsView()->AddChildView( std::make_unique<TestLabelButton>()); } raw_ptr<TestLabelButton> button_ = nullptr; raw_ptr<Widget> test_widget_ = nullptr; raw_ptr<Widget> dummy_widget_ = nullptr; Button::ButtonState style_of_inactive_widget_; }; TEST_F(LabelButtonVisualStateTest, IndependentWidget) { test_widget_->ShowInactive(); EXPECT_EQ(button_->GetVisualState(), style_of_inactive_widget_); test_widget_->Activate(); EXPECT_EQ(button_->GetVisualState(), Button::STATE_NORMAL); auto paint_as_active_lock = test_widget_->LockPaintAsActive(); dummy_widget_->Show(); EXPECT_EQ(button_->GetVisualState(), Button::STATE_NORMAL); } TEST_F(LabelButtonVisualStateTest, ChildWidget) { std::unique_ptr<Widget> child_widget = CreateActivatableChildWidget(test_widget_); TestLabelButton* child_button = MakeButtonAsContent(child_widget.get()); test_widget_->Show(); EXPECT_EQ(button_->GetVisualState(), Button::STATE_NORMAL); EXPECT_EQ(child_button->GetVisualState(), Button::STATE_NORMAL); dummy_widget_->Show(); EXPECT_EQ(button_->GetVisualState(), style_of_inactive_widget_); EXPECT_EQ(child_button->GetVisualState(), style_of_inactive_widget_); child_widget->Show(); #if BUILDFLAG(IS_MAC) // Child widget is in a key window and it will lock its parent. // See crrev.com/c/2048144. EXPECT_EQ(button_->GetVisualState(), Button::STATE_NORMAL); #else EXPECT_EQ(button_->GetVisualState(), style_of_inactive_widget_); #endif EXPECT_EQ(child_button->GetVisualState(), Button::STATE_NORMAL); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/label_button_unittest.cc
C++
unknown
37,671
// 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/button/md_text_button.h" #include <algorithm> #include <utility> #include <vector> #include "base/functional/bind.h" #include "base/i18n/case_conversion.h" #include "base/memory/ptr_util.h" #include "build/build_config.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/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/native_theme/native_theme.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.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_painted_layer_delegates.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/painter.h" #include "ui/views/style/platform_style.h" #include "ui/views/style/typography.h" namespace views { MdTextButton::MdTextButton(PressedCallback callback, const std::u16string& text, int button_context) : LabelButton(std::move(callback), text, button_context) { InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON); SetHasInkDropActionOnClick(true); SetShowInkDropWhenHotTracked(true); InkDrop::Get(this)->SetBaseColorCallback(base::BindRepeating( [](MdTextButton* host) { return host->GetHoverColor(host->GetStyle()); }, this)); if (features::IsChromeRefresh2023()) { constexpr int kImageSpacing = 8; SetImageLabelSpacing(kImageSpacing); // Highlight button colors already have opacity applied. // Set the opacity to 1 so the two values do not compound. InkDrop::Get(this)->SetHighlightOpacity(1); } else { SetCornerRadius(LayoutProvider::Get()->GetCornerRadiusMetric( ShapeContextTokens::kButtonRadius)); } SetHorizontalAlignment(gfx::ALIGN_CENTER); const int minimum_width = LayoutProvider::Get()->GetDistanceMetric( DISTANCE_DIALOG_BUTTON_MINIMUM_WIDTH); SetMinSize(gfx::Size(minimum_width, 0)); SetInstallFocusRingOnFocus(true); label()->SetAutoColorReadabilityEnabled(false); SetRequestFocusOnPress(false); SetAnimateOnStateChange(true); // Paint to a layer so that the canvas is snapped to pixel boundaries (useful // for fractional DSF). SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); // Call this to calculate the border given text. UpdatePadding(); } MdTextButton::~MdTextButton() = default; void MdTextButton::SetProminent(bool is_prominent) { SetStyle(is_prominent ? Style::kProminent : Style::kDefault); UpdateColors(); } bool MdTextButton::GetProminent() const { return style_ == Style::kProminent; } void MdTextButton::SetStyle(views::MdTextButton::Style button_style) { if (style_ == button_style) { return; } style_ = button_style; SetProperty(kDrawFocusRingBackgroundOutline, button_style == Style::kProminent); UpdateColors(); } views::MdTextButton::Style MdTextButton::GetStyle() const { return style_; } SkColor MdTextButton::GetHoverColor(Style button_style) { if (!features::IsChromeRefresh2023()) { return color_utils::DeriveDefaultIconColor(label()->GetEnabledColor()); } switch (button_style) { case Style::kProminent: return GetColorProvider()->GetColor(ui::kColorSysStateHoverOnProminent); case Style::kDefault: case Style::kText: case Style::kTonal: default: return GetColorProvider()->GetColor(ui::kColorSysStateHoverOnSubtle); } } void MdTextButton::SetBgColorOverride(const absl::optional<SkColor>& color) { if (color == bg_color_override_) return; bg_color_override_ = color; UpdateColors(); OnPropertyChanged(&bg_color_override_, kPropertyEffectsNone); } absl::optional<SkColor> MdTextButton::GetBgColorOverride() const { return bg_color_override_; } void MdTextButton::SetCornerRadius(absl::optional<float> radius) { if (corner_radius_ == radius) return; corner_radius_ = radius; LabelButton::SetFocusRingCornerRadius(GetCornerRadiusValue()); // UpdateColors also updates the background border radius. UpdateColors(); OnPropertyChanged(&corner_radius_, kPropertyEffectsNone); } absl::optional<float> MdTextButton::GetCornerRadius() const { return corner_radius_; } float MdTextButton::GetCornerRadiusValue() const { return corner_radius_.value_or(0); } void MdTextButton::OnThemeChanged() { LabelButton::OnThemeChanged(); UpdateColors(); } void MdTextButton::StateChanged(ButtonState old_state) { LabelButton::StateChanged(old_state); UpdateColors(); } void MdTextButton::SetImageModel(ButtonState for_state, const ui::ImageModel& image_model) { LabelButton::SetImageModel(for_state, image_model); UpdatePadding(); } void MdTextButton::OnFocus() { LabelButton::OnFocus(); UpdateColors(); } void MdTextButton::OnBlur() { LabelButton::OnBlur(); UpdateColors(); } void MdTextButton::OnBoundsChanged(const gfx::Rect& previous_bounds) { LabelButton::OnBoundsChanged(previous_bounds); // A fully rounded corner radius is calculated based on the size of the // button. To avoid overriding a custom corner radius, make sure the default // radius is only called once by checking if the value already exists. if (!corner_radius_) { SetCornerRadius(LayoutProvider::Get()->GetCornerRadiusMetric( ShapeContextTokens::kButtonRadius, size())); } } void MdTextButton::SetEnabledTextColors(absl::optional<SkColor> color) { LabelButton::SetEnabledTextColors(std::move(color)); UpdateColors(); } void MdTextButton::SetCustomPadding( const absl::optional<gfx::Insets>& padding) { custom_padding_ = padding; UpdatePadding(); } absl::optional<gfx::Insets> MdTextButton::GetCustomPadding() const { return custom_padding_.value_or(CalculateDefaultPadding()); } void MdTextButton::SetText(const std::u16string& text) { LabelButton::SetText(text); UpdatePadding(); } PropertyEffects MdTextButton::UpdateStyleToIndicateDefaultStatus() { SetProminent(style_ == Style::kProminent || GetIsDefault()); return kPropertyEffectsNone; } void MdTextButton::UpdatePadding() { // Don't use font-based padding when there's no text visible. if (GetText().empty()) { SetBorder(NullBorder()); return; } SetBorder( CreateEmptyBorder(custom_padding_.value_or(CalculateDefaultPadding()))); } gfx::Insets MdTextButton::CalculateDefaultPadding() const { int target_height = LayoutProvider::GetControlHeightForFont( label()->GetTextContext(), style::STYLE_PRIMARY, label()->font_list()); int label_height = label()->GetPreferredSize().height(); DCHECK_GE(target_height, label_height); int top_padding = (target_height - label_height) / 2; int bottom_padding = (target_height - label_height + 1) / 2; DCHECK_EQ(target_height, label_height + top_padding + bottom_padding); // TODO(estade): can we get rid of the platform style border hoopla if // we apply the MD treatment to all buttons, even GTK buttons? int right_padding = LayoutProvider::Get()->GetDistanceMetric( DISTANCE_BUTTON_HORIZONTAL_PADDING); int left_padding = right_padding; if (HasImage(GetVisualState()) && features::IsChromeRefresh2023()) { constexpr int kLeftPadding = 12; left_padding = kLeftPadding; } return gfx::Insets::TLBR(top_padding, left_padding, bottom_padding, right_padding); } void MdTextButton::UpdateTextColor() { if (explicitly_set_normal_color()) return; style::TextStyle text_style = style::STYLE_PRIMARY; if (style_ == Style::kProminent) { text_style = style::STYLE_DIALOG_BUTTON_DEFAULT; } else if (style_ == Style::kTonal) { text_style = style::STYLE_DIALOG_BUTTON_TONAL; } const ui::ColorProvider* color_provider = GetColorProvider(); SkColor enabled_text_color = color_provider->GetColor( style::GetColorId(label()->GetTextContext(), text_style)); const auto colors = explicitly_set_colors(); LabelButton::SetEnabledTextColors(enabled_text_color); // Disabled buttons need the disabled color explicitly set. // This ensures that label()->GetEnabledColor() returns the correct color as // the basis for calculating the stroke color. enabled_text_color isn't used // since a descendant could have overridden the label enabled color. if (GetState() == STATE_DISABLED) { LabelButton::SetTextColor( STATE_DISABLED, color_provider->GetColor(style::GetColorId( label()->GetTextContext(), style::STYLE_DISABLED))); } set_explicitly_set_colors(colors); } void MdTextButton::UpdateBackgroundColor() { bool is_disabled = GetVisualState() == STATE_DISABLED; const ui::ColorProvider* color_provider = GetColorProvider(); SkColor bg_color = color_provider->GetColor(ui::kColorButtonBackground); if (bg_color_override_) { bg_color = *bg_color_override_; } else if (style_ == Style::kProminent) { bg_color = color_provider->GetColor( HasFocus() ? ui::kColorButtonBackgroundProminentFocused : ui::kColorButtonBackgroundProminent); if (is_disabled) { bg_color = color_provider->GetColor(ui::kColorButtonBackgroundProminentDisabled); } } else if (style_ == Style::kTonal) { bg_color = color_provider->GetColor( HasFocus() ? ui::kColorButtonBackgroundTonalFocused : ui::kColorButtonBackgroundTonal); if (is_disabled) { bg_color = color_provider->GetColor(ui::kColorButtonBackgroundTonalDisabled); } } if (GetState() == STATE_PRESSED) { bg_color = GetNativeTheme()->GetSystemButtonPressedColor(bg_color); } SkColor stroke_color = color_provider->GetColor( is_disabled ? ui::kColorButtonBorderDisabled : ui::kColorButtonBorder); if (style_ == Style::kProminent || style_ == Style::kText || style_ == Style::kTonal) { stroke_color = SK_ColorTRANSPARENT; } SetBackground( CreateBackgroundFromPainter(Painter::CreateRoundRectWith1PxBorderPainter( bg_color, stroke_color, GetCornerRadiusValue()))); } void MdTextButton::UpdateColors() { if (GetWidget()) { UpdateTextColor(); UpdateBackgroundColor(); SchedulePaint(); } } BEGIN_METADATA(MdTextButton, LabelButton) ADD_PROPERTY_METADATA(bool, Prominent) ADD_PROPERTY_METADATA(absl::optional<float>, CornerRadius) ADD_PROPERTY_METADATA(absl::optional<SkColor>, BgColorOverride) ADD_PROPERTY_METADATA(absl::optional<gfx::Insets>, CustomPadding) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/md_text_button.cc
C++
unknown
10,970
// 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. #ifndef UI_VIEWS_CONTROLS_BUTTON_MD_TEXT_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_MD_TEXT_BUTTON_H_ #include <memory> #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/style/typography.h" namespace views { // A button class that implements the Material Design text button spec. class VIEWS_EXPORT MdTextButton : public LabelButton { public: // MdTextButton has various button styles that can change the button's // background and text color. // kDefault: White background with blue text and a solid outline. // kProminent: Blue background with white text. // kTonal: Cyan background with black text. // kText: White background with blue text but no outline. enum class Style { kDefault = 0, kProminent = 1, kTonal = 2, kText = 3, }; METADATA_HEADER(MdTextButton); explicit MdTextButton(PressedCallback callback = PressedCallback(), const std::u16string& text = std::u16string(), int button_context = style::CONTEXT_BUTTON_MD); MdTextButton(const MdTextButton&) = delete; MdTextButton& operator=(const MdTextButton&) = delete; ~MdTextButton() override; // TODO(crbug.com/1406008): Remove the use of Prominent state and use button // style state instead. void SetProminent(bool is_prominent); bool GetProminent() const; void SetStyle(views::MdTextButton::Style button_style); Style GetStyle() const; // Returns the hover color depending on the button style. SkColor GetHoverColor(Style button_style); // See |bg_color_override_|. void SetBgColorOverride(const absl::optional<SkColor>& color); absl::optional<SkColor> GetBgColorOverride() const; // Override the default corner radius of the round rect used for the // background and ink drop effects. void SetCornerRadius(absl::optional<float> radius); absl::optional<float> GetCornerRadius() const; float GetCornerRadiusValue() const; // See |custom_padding_|. void SetCustomPadding(const absl::optional<gfx::Insets>& padding); absl::optional<gfx::Insets> GetCustomPadding() const; // LabelButton: void OnThemeChanged() override; void SetEnabledTextColors(absl::optional<SkColor> color) override; void SetText(const std::u16string& text) override; PropertyEffects UpdateStyleToIndicateDefaultStatus() override; void StateChanged(ButtonState old_state) override; void SetImageModel(ButtonState for_state, const ui::ImageModel& image_model) override; protected: // View: void OnFocus() override; void OnBlur() override; void OnBoundsChanged(const gfx::Rect& previous_bounds) override; private: void UpdatePadding(); gfx::Insets CalculateDefaultPadding() const; void UpdateTextColor(); void UpdateBackgroundColor() override; void UpdateColors(); Style style_ = Style::kDefault; // When set, this provides the background color. absl::optional<SkColor> bg_color_override_; // Used to set the corner radius of the button. absl::optional<float> corner_radius_; // Used to override default padding. absl::optional<gfx::Insets> custom_padding_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, MdTextButton, LabelButton) VIEW_BUILDER_PROPERTY(bool, Prominent) VIEW_BUILDER_PROPERTY(absl::optional<float>, CornerRadius) VIEW_BUILDER_PROPERTY(absl::optional<SkColor>, BgColorOverride) VIEW_BUILDER_PROPERTY(absl::optional<gfx::Insets>, CustomPadding) VIEW_BUILDER_PROPERTY(MdTextButton::Style, Style) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, MdTextButton) #endif // UI_VIEWS_CONTROLS_BUTTON_MD_TEXT_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/md_text_button.h
C++
unknown
3,854
// 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/button/md_text_button.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/views/background.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/views_drawing_test_utils.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/widget_test.h" namespace views { using MdTextButtonTest = ViewsTestBase; TEST_F(MdTextButtonTest, CustomPadding) { const std::u16string text = u"abc"; auto button = std::make_unique<MdTextButton>(Button::PressedCallback(), text); const auto custom_padding = gfx::Insets::VH(10, 20); ASSERT_NE(button->GetInsets(), custom_padding); button->SetCustomPadding(custom_padding); EXPECT_EQ(button->GetInsets(), custom_padding); } TEST_F(MdTextButtonTest, BackgroundColorChangesWithWidgetActivation) { // Test whether the button's background color changes when its containing // widget's activation changes. if (!PlatformStyle::kInactiveWidgetControlsAppearDisabled) GTEST_SKIP() << "Button colors do not change with widget activation here."; std::unique_ptr<Widget> widget = CreateTestWidget(); auto* button = widget->SetContentsView( std::make_unique<MdTextButton>(Button::PressedCallback(), u"button")); button->SetProminent(true); button->SetBounds(0, 0, 70, 20); widget->LayoutRootViewIfNecessary(); const ui::ColorProvider* color_provider = button->GetColorProvider(); test::WidgetTest::SimulateNativeActivate(widget.get()); EXPECT_TRUE(widget->IsActive()); SkBitmap active_bitmap = views::test::PaintViewToBitmap(button); auto background_color = [button](const SkBitmap& bitmap) { // The very edge of the bitmap contains the button's border, which we aren't // interested in here. Instead, grab a pixel that is inset by the button's // corner radius from the top-left point to avoid the border. // // It would make a bit more sense to inset by the border thickness or // something, but MdTextButton doesn't expose (or even know) that value // without some major abstraction violation. int corner_radius = button->GetCornerRadiusValue(); return bitmap.getColor(corner_radius, corner_radius); }; EXPECT_EQ(background_color(active_bitmap), color_provider->GetColor(ui::kColorButtonBackgroundProminent)); // It would be neat to also check the text color here, but the label's text // ends up drawn on top of the background with antialiasing, which means there // aren't any pixels that are actually *exactly* // kColorButtonForegroundProminent. Bummer. // Activate another widget to cause the original widget to deactivate. std::unique_ptr<Widget> other_widget = CreateTestWidget(); test::WidgetTest::SimulateNativeActivate(other_widget.get()); EXPECT_FALSE(widget->IsActive()); SkBitmap inactive_bitmap = views::test::PaintViewToBitmap(button); EXPECT_EQ( background_color(inactive_bitmap), color_provider->GetColor(ui::kColorButtonBackgroundProminentDisabled)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/md_text_button_unittest.cc
C++
unknown
3,294
// 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/menu_button.h" #include <memory> #include <utility> #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/event.h" #include "ui/views/controls/button/button_controller_delegate.h" #include "ui/views/controls/button/menu_button_controller.h" #include "ui/views/view_class_properties.h" namespace views { MenuButton::MenuButton(PressedCallback callback, const std::u16string& text, int button_context) : LabelButton(PressedCallback(), text, button_context) { SetHorizontalAlignment(gfx::ALIGN_LEFT); std::unique_ptr<MenuButtonController> menu_button_controller = std::make_unique<MenuButtonController>( this, std::move(callback), std::make_unique<Button::DefaultButtonControllerDelegate>(this)); menu_button_controller_ = menu_button_controller.get(); SetButtonController(std::move(menu_button_controller)); SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); } MenuButton::~MenuButton() = default; bool MenuButton::Activate(const ui::Event* event) { return button_controller()->Activate(event); } void MenuButton::SetCallback(PressedCallback callback) { menu_button_controller_->SetCallback(std::move(callback)); } void MenuButton::NotifyClick(const ui::Event& event) { // Run pressed callback via MenuButtonController, instead of directly. button_controller()->Activate(&event); } BEGIN_METADATA(MenuButton, LabelButton) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/menu_button.cc
C++
unknown
1,655
// 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_MENU_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_H_ #include <string> #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/metadata/view_factory.h" namespace views { class MenuButtonController; //////////////////////////////////////////////////////////////////////////////// // // MenuButton // // A button that shows a menu when the left mouse button is pushed // //////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT MenuButton : public LabelButton { public: METADATA_HEADER(MenuButton); explicit MenuButton(PressedCallback callback = PressedCallback(), const std::u16string& text = std::u16string(), int button_context = style::CONTEXT_BUTTON); MenuButton(const MenuButton&) = delete; MenuButton& operator=(const MenuButton&) = delete; ~MenuButton() override; MenuButtonController* button_controller() const { return menu_button_controller_; } bool Activate(const ui::Event* event); // Button: void SetCallback(PressedCallback callback) override; protected: // Button: void NotifyClick(const ui::Event& event) final; private: raw_ptr<MenuButtonController> menu_button_controller_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, MenuButton, LabelButton) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, MenuButton) #endif // UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/menu_button.h
C++
unknown
1,710
// 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/button/menu_button_controller.h" #include <utility> #include "base/functional/bind.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/interaction/element_identifier.h" #include "ui/events/event_constants.h" #include "ui/events/types/event_type.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/button_controller_delegate.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/interaction/element_tracker_views.h" #include "ui/views/mouse_constants.h" #include "ui/views/style/platform_style.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" using base::TimeTicks; namespace views { namespace { ui::EventType NotifyActionToMouseEventType( ButtonController::NotifyAction notify_action) { switch (notify_action) { case ButtonController::NotifyAction::kOnPress: return ui::ET_MOUSE_PRESSED; case ButtonController::NotifyAction::kOnRelease: return ui::ET_MOUSE_RELEASED; } } } // namespace //////////////////////////////////////////////////////////////////////////////// // // MenuButtonController::PressedLock // //////////////////////////////////////////////////////////////////////////////// MenuButtonController::PressedLock::PressedLock( MenuButtonController* menu_button_controller) : PressedLock(menu_button_controller, false, nullptr) {} MenuButtonController::PressedLock::PressedLock( MenuButtonController* menu_button_controller, bool is_sibling_menu_show, const ui::LocatedEvent* event) : menu_button_controller_( menu_button_controller->weak_factory_.GetWeakPtr()) { menu_button_controller_->IncrementPressedLocked(is_sibling_menu_show, event); } std::unique_ptr<MenuButtonController::PressedLock> MenuButtonController::TakeLock() { return TakeLock(false, nullptr); } std::unique_ptr<MenuButtonController::PressedLock> MenuButtonController::TakeLock(bool is_sibling_menu_show, const ui::LocatedEvent* event) { return std::make_unique<MenuButtonController::PressedLock>( this, is_sibling_menu_show, event); } MenuButtonController::PressedLock::~PressedLock() { if (menu_button_controller_) menu_button_controller_->DecrementPressedLocked(); } //////////////////////////////////////////////////////////////////////////////// // // MenuButtonController // //////////////////////////////////////////////////////////////////////////////// MenuButtonController::MenuButtonController( Button* button, Button::PressedCallback callback, std::unique_ptr<ButtonControllerDelegate> delegate) : ButtonController(button, std::move(delegate)), callback_(std::move(callback)) { // Triggers on button press by default, unless drag-and-drop is enabled, see // MenuButtonController::IsTriggerableEventType. set_notify_action(ButtonController::NotifyAction::kOnPress); } MenuButtonController::~MenuButtonController() = default; bool MenuButtonController::OnMousePressed(const ui::MouseEvent& event) { // Sets true if the amount of time since the last |menu_closed_time_| is // large enough for the current event to be considered an intentionally // different event. is_intentional_menu_trigger_ = (TimeTicks::Now() - menu_closed_time_) >= kMinimumTimeBetweenButtonClicks; if (button()->GetRequestFocusOnPress()) button()->RequestFocus(); if (button()->GetState() != Button::STATE_DISABLED && button()->HitTestPoint(event.location()) && IsTriggerableEvent(event)) { return Activate(&event); } // If this is an unintentional trigger do not display the inkdrop. if (!is_intentional_menu_trigger_) InkDrop::Get(button())->AnimateToState(InkDropState::HIDDEN, &event); return true; } void MenuButtonController::OnMouseReleased(const ui::MouseEvent& event) { if (button()->GetState() != Button::STATE_DISABLED && delegate()->IsTriggerableEvent(event) && button()->HitTestPoint(event.location()) && !delegate()->InDrag()) { Activate(&event); } else { if (button()->GetHideInkDropWhenShowingContextMenu()) InkDrop::Get(button())->AnimateToState(InkDropState::HIDDEN, &event); ButtonController::OnMouseReleased(event); } } void MenuButtonController::OnMouseMoved(const ui::MouseEvent& event) { if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. ButtonController::OnMouseMoved(event); } void MenuButtonController::OnMouseEntered(const ui::MouseEvent& event) { if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. ButtonController::OnMouseEntered(event); } void MenuButtonController::OnMouseExited(const ui::MouseEvent& event) { if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. ButtonController::OnMouseExited(event); } bool MenuButtonController::OnKeyPressed(const ui::KeyEvent& event) { // Alt-space on windows should show the window menu. if (event.key_code() == ui::VKEY_SPACE && event.IsAltDown()) return false; // If Return doesn't normally click buttons, don't do it here either. if (event.key_code() == ui::VKEY_RETURN && !PlatformStyle::kReturnClicksFocusedControl) { return false; } switch (event.key_code()) { case ui::VKEY_SPACE: case ui::VKEY_RETURN: case ui::VKEY_UP: case ui::VKEY_DOWN: { // WARNING: we may have been deleted by the time Activate returns. Activate(&event); // This is to prevent the keyboard event from being dispatched twice. If // the keyboard event is not handled, we pass it to the default handler // which dispatches the event back to us causing the menu to get displayed // again. Return true to prevent this. return true; } default: break; } return false; } bool MenuButtonController::OnKeyReleased(const ui::KeyEvent& event) { // A MenuButton always activates the menu on key press. return false; } void MenuButtonController::UpdateAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kPopUpButton; node_data->SetHasPopup(ax::mojom::HasPopup::kMenu); if (button()->GetEnabled()) { node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kOpen); } } bool MenuButtonController::IsTriggerableEvent(const ui::Event& event) { return ButtonController::IsTriggerableEvent(event) && IsTriggerableEventType(event) && is_intentional_menu_trigger_; } void MenuButtonController::OnGestureEvent(ui::GestureEvent* event) { if (button()->GetState() != Button::STATE_DISABLED) { auto ref = weak_factory_.GetWeakPtr(); if (delegate()->IsTriggerableEvent(*event) && !Activate(event)) { // When Activate() returns false, it means the click was handled by a // button listener and has handled the gesture event. So, there is no need // to further process the gesture event here. However, if the listener // didn't run menu code, we should make sure to reset our state. if (ref && button()->GetState() == Button::STATE_HOVERED) button()->SetState(Button::STATE_NORMAL); return; } if (event->type() == ui::ET_GESTURE_TAP_DOWN) { event->SetHandled(); if (pressed_lock_count_ == 0) button()->SetState(Button::STATE_HOVERED); } else if (button()->GetState() == Button::STATE_HOVERED && (event->type() == ui::ET_GESTURE_TAP_CANCEL || event->type() == ui::ET_GESTURE_END) && pressed_lock_count_ == 0) { button()->SetState(Button::STATE_NORMAL); } } ButtonController::OnGestureEvent(event); } bool MenuButtonController::Activate(const ui::Event* event) { if (callback_) { // We're about to show the menu from a mouse press. By showing from the // mouse press event we block RootView in mouse dispatching. This also // appears to cause RootView to get a mouse pressed BEFORE the mouse // release is seen, which means RootView sends us another mouse press no // matter where the user pressed. To force RootView to recalculate the // mouse target during the mouse press we explicitly set the mouse handler // to NULL. static_cast<internal::RootView*>(button()->GetWidget()->GetRootView()) ->SetMouseAndGestureHandler(nullptr); DCHECK(increment_pressed_lock_called_ == nullptr); // Observe if IncrementPressedLocked() was called so we can trigger the // correct ink drop animations. bool increment_pressed_lock_called = false; increment_pressed_lock_called_ = &increment_pressed_lock_called; // Since regular Button logic isn't used, we need to instead notify that the // menu button was activated here. const ui::ElementIdentifier id = button()->GetProperty(views::kElementIdentifierKey); if (id) { views::ElementTrackerViews::GetInstance()->NotifyViewActivated(id, button()); } // Allow for the button callback to delete this. auto ref = weak_factory_.GetWeakPtr(); // TODO(pbos): Make sure we always propagate an event. This requires changes // to ShowAppMenu which now provides none. ui::KeyEvent fake_event(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_IS_SYNTHESIZED); if (!event) event = &fake_event; // We don't set our state here. It's handled in the MenuController code or // by the callback. callback_.Run(*event); if (!ref) { // The menu was deleted while showing. Don't attempt any processing. return false; } increment_pressed_lock_called_ = nullptr; if (!increment_pressed_lock_called && pressed_lock_count_ == 0) { InkDrop::Get(button())->AnimateToState( InkDropState::ACTION_TRIGGERED, ui::LocatedEvent::FromIfValid(event)); } // We must return false here so that the RootView does not get stuck // sending all mouse pressed events to us instead of the appropriate // target. return false; } InkDrop::Get(button())->AnimateToState(InkDropState::HIDDEN, ui::LocatedEvent::FromIfValid(event)); return true; } bool MenuButtonController::IsTriggerableEventType(const ui::Event& event) { if (event.IsMouseEvent()) { const auto* mouse_event = event.AsMouseEvent(); // Check that the event has the correct flags the button specified can // trigger button actions. For example, menus should only active on left // mouse button, to prevent a menu from being activated when a right-click // would also activate a context menu. if (!(mouse_event->button_flags() & button()->GetTriggerableEventFlags())) return false; // Activate on release if dragging, otherwise activate based on // notify_action. ui::EventType active_on = delegate()->GetDragOperations(mouse_event->location()) == ui::DragDropTypes::DRAG_NONE ? NotifyActionToMouseEventType(notify_action()) : ui::ET_MOUSE_RELEASED; return event.type() == active_on; } return event.type() == ui::ET_GESTURE_TAP; } void MenuButtonController::IncrementPressedLocked( bool snap_ink_drop_to_activated, const ui::LocatedEvent* event) { ++pressed_lock_count_; if (increment_pressed_lock_called_) *increment_pressed_lock_called_ = true; if (!state_changed_subscription_) { state_changed_subscription_ = button()->AddStateChangedCallback(base::BindRepeating( &MenuButtonController::OnButtonStateChangedWhilePressedLocked, base::Unretained(this))); } should_disable_after_press_ = button()->GetState() == Button::STATE_DISABLED; if (button()->GetState() != Button::STATE_PRESSED) { if (snap_ink_drop_to_activated) delegate()->GetInkDrop()->SnapToActivated(); else InkDrop::Get(button())->AnimateToState(InkDropState::ACTIVATED, event); } button()->SetState(Button::STATE_PRESSED); delegate()->GetInkDrop()->SetHovered(false); } void MenuButtonController::DecrementPressedLocked() { --pressed_lock_count_; DCHECK_GE(pressed_lock_count_, 0); // If this was the last lock, manually reset state to the desired state. if (pressed_lock_count_ == 0) { menu_closed_time_ = TimeTicks::Now(); state_changed_subscription_ = {}; LabelButton::ButtonState desired_state = Button::STATE_NORMAL; if (should_disable_after_press_) { desired_state = Button::STATE_DISABLED; should_disable_after_press_ = false; } else if (button()->GetWidget() && !button()->GetWidget()->dragged_view() && delegate()->ShouldEnterHoveredState()) { desired_state = Button::STATE_HOVERED; delegate()->GetInkDrop()->SetHovered(true); } button()->SetState(desired_state); // The widget may be null during shutdown. If so, it doesn't make sense to // try to add an ink drop effect. if (button()->GetWidget() && button()->GetState() != Button::STATE_PRESSED) InkDrop::Get(button())->AnimateToState(InkDropState::DEACTIVATED, nullptr /* event */); } } void MenuButtonController::OnButtonStateChangedWhilePressedLocked() { // The button's state was changed while it was supposed to be locked in a // pressed state. This shouldn't happen, but conceivably could if a caller // tries to switch from enabled to disabled or vice versa while the button is // pressed. if (button()->GetState() == Button::STATE_NORMAL) should_disable_after_press_ = false; else if (button()->GetState() == Button::STATE_DISABLED) should_disable_after_press_ = true; } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/menu_button_controller.cc
C++
unknown
14,068
// 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_BUTTON_MENU_BUTTON_CONTROLLER_H_ #define UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_CONTROLLER_H_ #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "ui/views/controls/button/button_controller.h" namespace views { class ButtonControllerDelegate; class MenuButton; // A controller that contains the logic for showing a menu when the left mouse // is pushed. class VIEWS_EXPORT MenuButtonController : public ButtonController { public: // A scoped lock for keeping the MenuButton in STATE_PRESSED e.g., while a // menu is running. These are cumulative. class VIEWS_EXPORT PressedLock { public: explicit PressedLock(MenuButtonController* menu_button_controller); // |event| is the event that caused the button to be pressed. May be null. PressedLock(MenuButtonController* menu_button_controller, bool is_sibling_menu_show, const ui::LocatedEvent* event); PressedLock(const PressedLock&) = delete; PressedLock& operator=(const PressedLock&) = delete; ~PressedLock(); private: base::WeakPtr<MenuButtonController> menu_button_controller_; }; MenuButtonController(Button* button, Button::PressedCallback callback, std::unique_ptr<ButtonControllerDelegate> delegate); MenuButtonController(const MenuButtonController&) = delete; MenuButtonController& operator=(const MenuButtonController&) = delete; ~MenuButtonController() override; // view::ButtonController bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseMoved(const ui::MouseEvent& event) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnKeyReleased(const ui::KeyEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; void UpdateAccessibleNodeData(ui::AXNodeData* node_data) override; bool IsTriggerableEvent(const ui::Event& event) override; // Calls TakeLock with is_sibling_menu_show as false and a nullptr to the // event. std::unique_ptr<PressedLock> TakeLock(); // Convenience method to increment the lock count on a button to keep the // button in a PRESSED state when a menu is showing. std::unique_ptr<PressedLock> TakeLock(bool is_sibling_menu_show, const ui::LocatedEvent* event); // Activate the button (called when the button is pressed). |event| is the // event triggering the activation, if any. bool Activate(const ui::Event* event); // Returns true if the event is of the proper type to potentially trigger an // action. Since MenuButtons have properties other than event type (like // last menu open time) to determine if an event is valid to activate the // menu, this is distinct from IsTriggerableEvent(). bool IsTriggerableEventType(const ui::Event& event); void SetCallback(Button::PressedCallback callback) { callback_ = std::move(callback); } private: // Increment/decrement the number of "pressed" locks this button has, and // set the state accordingly. The ink drop is snapped to the final ACTIVATED // state if |snap_ink_drop_to_activated| is true, otherwise the ink drop // will be animated to the ACTIVATED node_data. The ink drop is animated at // the location of |event| if non-null, otherwise at the default location. void IncrementPressedLocked(bool snap_ink_drop_to_activated, const ui::LocatedEvent* event); void DecrementPressedLocked(); // Called if the button state changes while pressed lock is engaged. void OnButtonStateChangedWhilePressedLocked(); // Our callback. Button::PressedCallback callback_; // We use a time object in order to keep track of when the menu was closed. // The time is used for simulating menu behavior for the menu button; 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 menu_closed_time_; // Tracks if the current triggering event should open a menu. bool is_intentional_menu_trigger_ = true; // The current number of "pressed" locks this button has. int pressed_lock_count_ = 0; // Used to let Activate() know if IncrementPressedLocked() was called. raw_ptr<bool> increment_pressed_lock_called_ = nullptr; // True if the button was in a disabled state when a menu was run, and // should return to it once the press is complete. This can happen if, e.g., // we programmatically show a menu on a disabled button. bool should_disable_after_press_ = false; // Subscribes to state changes on the button while pressed lock is engaged. base::CallbackListSubscription state_changed_subscription_; base::WeakPtrFactory<MenuButtonController> weak_factory_{this}; }; } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/menu_button_controller.h
C++
unknown
5,453
// 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/button/menu_button.h" #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/test/event_generator.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/animation/test/ink_drop_host_test_api.h" #include "ui/views/animation/test/test_ink_drop.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/menu_button_controller.h" #include "ui/views/drag_controller.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget_utils.h" #if defined(USE_AURA) #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/client/drag_drop_client_observer.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h" #include "ui/events/event.h" #include "ui/events/event_handler.h" #endif namespace views { using ::base::ASCIIToUTF16; using ::ui::mojom::DragOperation; class TestMenuButton : public MenuButton { public: TestMenuButton() : TestMenuButton(base::BindRepeating(&TestMenuButton::ButtonPressed, base::Unretained(this))) {} explicit TestMenuButton(PressedCallback callback) : MenuButton(std::move(callback), std::u16string(u"button")) {} TestMenuButton(const TestMenuButton&) = delete; TestMenuButton& operator=(const TestMenuButton&) = delete; ~TestMenuButton() override = default; bool clicked() const { return clicked_; } Button::ButtonState last_state() const { return last_state_; } ui::EventType last_event_type() const { return last_event_type_; } void Reset() { clicked_ = false; last_state_ = Button::STATE_NORMAL; last_event_type_ = ui::ET_UNKNOWN; } private: void ButtonPressed(const ui::Event& event) { clicked_ = true; last_state_ = GetState(); last_event_type_ = event.type(); } bool clicked_ = false; Button::ButtonState last_state_ = Button::STATE_NORMAL; ui::EventType last_event_type_ = ui::ET_UNKNOWN; }; class MenuButtonTest : public ViewsTestBase { public: MenuButtonTest() = default; MenuButtonTest(const MenuButtonTest&) = delete; MenuButtonTest& operator=(const MenuButtonTest&) = delete; ~MenuButtonTest() override = default; void TearDown() override { generator_.reset(); if (widget_ && !widget_->IsClosed()) widget_->Close(); ViewsTestBase::TearDown(); } protected: Widget* widget() { return widget_; } TestMenuButton* button() { return button_; } ui::test::EventGenerator* generator() { return generator_.get(); } test::TestInkDrop* ink_drop() { return ink_drop_; } gfx::Point GetOutOfButtonLocation() const { return gfx::Point(button_->x() - 1, button_->y() - 1); } void CreateWidget() { DCHECK(!widget_); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); widget_->Init(std::move(params)); } void ConfigureMenuButton(std::unique_ptr<TestMenuButton> button) { CreateWidget(); generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_)); // Set initial mouse location in a consistent way so that the menu button we // are about to create initializes its hover state in a consistent manner. generator_->set_current_screen_location(gfx::Point(10, 10)); button_ = widget_->SetContentsView(std::move(button)); button_->SetBoundsRect(gfx::Rect(0, 0, 200, 20)); auto ink_drop = std::make_unique<test::TestInkDrop>(); ink_drop_ = ink_drop.get(); test::InkDropHostTestApi(InkDrop::Get(button_)) .SetInkDrop(std::move(ink_drop)); widget_->Show(); } private: raw_ptr<Widget> widget_ = nullptr; // Owned by self. raw_ptr<TestMenuButton> button_ = nullptr; // Owned by |widget_|. std::unique_ptr<ui::test::EventGenerator> generator_; raw_ptr<test::TestInkDrop> ink_drop_ = nullptr; // Owned by |button_|. }; // A Button that will acquire a PressedLock in the pressed callback and // optionally release it as well. class PressStateButton : public TestMenuButton { public: explicit PressStateButton(bool release_lock) : TestMenuButton(base::BindRepeating(&PressStateButton::ButtonPressed, base::Unretained(this))), release_lock_(release_lock) {} PressStateButton(const PressStateButton&) = delete; PressStateButton& operator=(const PressStateButton&) = delete; ~PressStateButton() override = default; void ReleasePressedLock() { pressed_lock_.reset(); } private: void ButtonPressed() { pressed_lock_ = button_controller()->TakeLock(); if (release_lock_) ReleasePressedLock(); } bool release_lock_; std::unique_ptr<MenuButtonController::PressedLock> pressed_lock_; }; // Basic implementation of a DragController, to test input behaviour for // MenuButtons that can be dragged. class TestDragController : public DragController { public: TestDragController() = default; TestDragController(const TestDragController&) = delete; TestDragController& operator=(const TestDragController&) = delete; ~TestDragController() override = default; void WriteDragDataForView(View* sender, const gfx::Point& press_pt, ui::OSExchangeData* data) override {} int GetDragOperationsForView(View* sender, const gfx::Point& p) override { return ui::DragDropTypes::DRAG_MOVE; } bool CanStartDragForView(View* sender, const gfx::Point& press_pt, const gfx::Point& p) override { return true; } }; #if defined(USE_AURA) // Basic implementation of a DragDropClient, tracking the state of the drag // operation. While dragging addition mouse events are consumed, preventing the // target view from receiving them. class TestDragDropClient : public aura::client::DragDropClient, public ui::EventHandler { public: TestDragDropClient(); TestDragDropClient(const TestDragDropClient&) = delete; TestDragDropClient& operator=(const TestDragDropClient&) = delete; ~TestDragDropClient() override; // 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 { } // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; private: // True while receiving ui::LocatedEvents for drag operations. bool drag_in_progress_ = false; // Target window where drag operations are occurring. raw_ptr<aura::Window> target_ = nullptr; }; TestDragDropClient::TestDragDropClient() = default; TestDragDropClient::~TestDragDropClient() = default; 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) { if (IsDragDropInProgress()) return DragOperation::kNone; drag_in_progress_ = true; target_ = root_window; return ui::PreferredDragOperation(allowed_operations); } void TestDragDropClient::DragCancel() { drag_in_progress_ = false; } bool TestDragDropClient::IsDragDropInProgress() { return drag_in_progress_; } void TestDragDropClient::OnMouseEvent(ui::MouseEvent* event) { if (!IsDragDropInProgress()) return; switch (event->type()) { case ui::ET_MOUSE_DRAGGED: event->StopPropagation(); break; case ui::ET_MOUSE_RELEASED: drag_in_progress_ = false; event->StopPropagation(); break; default: break; } } #endif // defined(USE_AURA) // Tests if the callback is called correctly when a mouse click happens on a // MenuButton. TEST_F(MenuButtonTest, ActivateDropDownOnMouseClick) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); generator()->ClickLeftButton(); EXPECT_TRUE(button()->clicked()); EXPECT_EQ(Button::STATE_HOVERED, button()->last_state()); } TEST_F(MenuButtonTest, ActivateOnKeyPress) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); EXPECT_FALSE(button()->clicked()); button()->OnKeyPressed(ui::KeyEvent( ui::ET_KEY_PRESSED, ui::KeyboardCode::VKEY_SPACE, ui::DomCode::SPACE, 0)); EXPECT_TRUE(button()->clicked()); button()->Reset(); EXPECT_FALSE(button()->clicked()); button()->OnKeyPressed(ui::KeyEvent(ui::ET_KEY_PRESSED, ui::KeyboardCode::VKEY_RETURN, ui::DomCode::ENTER, 0)); EXPECT_EQ(PlatformStyle::kReturnClicksFocusedControl, button()->clicked()); } // Tests that the ink drop center point is set from the mouse click point. TEST_F(MenuButtonTest, InkDropCenterSetFromClick) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); const gfx::Point click_point = button()->GetBoundsInScreen().CenterPoint(); generator()->MoveMouseTo(click_point); generator()->ClickLeftButton(); EXPECT_TRUE(button()->clicked()); gfx::Point inkdrop_center_point = InkDrop::Get(button())->GetInkDropCenterBasedOnLastEvent(); View::ConvertPointToScreen(button(), &inkdrop_center_point); EXPECT_EQ(click_point, inkdrop_center_point); } // Tests that the ink drop center point is set from the PressedLock constructor. // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_InkDropCenterSetFromClickWithPressedLock \ DISABLED_InkDropCenterSetFromClickWithPressedLock #else #define MAYBE_InkDropCenterSetFromClickWithPressedLock \ InkDropCenterSetFromClickWithPressedLock #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_InkDropCenterSetFromClickWithPressedLock) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); gfx::Point click_point(11, 7); ui::MouseEvent click_event(ui::EventType::ET_MOUSE_PRESSED, click_point, click_point, base::TimeTicks(), 0, 0); MenuButtonController::PressedLock pressed_lock(button()->button_controller(), false, &click_event); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); EXPECT_EQ(click_point, InkDrop::Get(button())->GetInkDropCenterBasedOnLastEvent()); } // Test that the MenuButton stays pressed while there are any PressedLocks. // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_ButtonStateForMenuButtonsWithPressedLocks \ DISABLED_ButtonStateForMenuButtonsWithPressedLocks #else #define MAYBE_ButtonStateForMenuButtonsWithPressedLocks \ ButtonStateForMenuButtonsWithPressedLocks #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_ButtonStateForMenuButtonsWithPressedLocks) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); const gfx::Rect button_bounds = button()->GetBoundsInScreen(); // Move the mouse over the button; the button should be in a hovered state. generator()->MoveMouseTo(button_bounds.CenterPoint()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); // Introduce a PressedLock, which should make the button pressed. auto pressed_lock1 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); // Even if we move the mouse outside of the button, it should remain pressed. generator()->MoveMouseTo(button_bounds.bottom_right() + gfx::Vector2d(1, 1)); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); // Creating a new lock should obviously keep the button pressed. auto pressed_lock2 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); // The button should remain pressed while any locks are active. pressed_lock1.reset(); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); // Resetting the final lock should return the button's state to normal... pressed_lock2.reset(); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); // ...And it should respond to mouse movement again. generator()->MoveMouseTo(button_bounds.CenterPoint()); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); // Test that the button returns to the appropriate state after the press; if // the mouse ends over the button, the button should be hovered. pressed_lock1 = button()->button_controller()->TakeLock(); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); pressed_lock1.reset(); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); // If the button is disabled before the pressed lock, it should be disabled // after the pressed lock. button()->SetState(Button::STATE_DISABLED); pressed_lock1 = button()->button_controller()->TakeLock(); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); pressed_lock1.reset(); EXPECT_EQ(Button::STATE_DISABLED, button()->GetState()); generator()->MoveMouseTo(button_bounds.bottom_right() + gfx::Vector2d(1, 1)); // Edge case: the button is disabled, a pressed lock is added, and then the // button is re-enabled. It should be enabled after the lock is removed. pressed_lock1 = button()->button_controller()->TakeLock(); EXPECT_EQ(Button::STATE_PRESSED, button()->GetState()); button()->SetState(Button::STATE_NORMAL); pressed_lock1.reset(); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); } // Test that the MenuButton does not become pressed if it can be dragged, until // a release occurs. // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_DraggableMenuButtonActivatesOnRelease \ DISABLED_DraggableMenuButtonActivatesOnRelease #else #define MAYBE_DraggableMenuButtonActivatesOnRelease \ DraggableMenuButtonActivatesOnRelease #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_DraggableMenuButtonActivatesOnRelease) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); TestDragController drag_controller; button()->set_drag_controller(&drag_controller); generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); generator()->PressLeftButton(); EXPECT_FALSE(button()->clicked()); generator()->ReleaseLeftButton(); EXPECT_TRUE(button()->clicked()); EXPECT_EQ(Button::STATE_HOVERED, button()->last_state()); } // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_InkDropStateForMenuButtonActivationsWithoutCallback \ DISABLED_InkDropStateForMenuButtonActivationsWithoutCallback #else #define MAYBE_InkDropStateForMenuButtonActivationsWithoutCallback \ InkDropStateForMenuButtonActivationsWithoutCallback #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_InkDropStateForMenuButtonActivationsWithoutCallback) { ConfigureMenuButton( std::make_unique<TestMenuButton>(Button::PressedCallback())); ink_drop()->AnimateToState(InkDropState::ACTION_PENDING); button()->Activate(nullptr); EXPECT_EQ(InkDropState::HIDDEN, ink_drop()->GetTargetInkDropState()); } // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_InkDropStateForMenuButtonActivationsWithCallbackThatDoesntAcquireALock \ DISABLED_InkDropStateForMenuButtonActivationsWithCallbackThatDoesntAcquireALock #else #define MAYBE_InkDropStateForMenuButtonActivationsWithCallbackThatDoesntAcquireALock \ InkDropStateForMenuButtonActivationsWithCallbackThatDoesntAcquireALock #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F( MenuButtonTest, MAYBE_InkDropStateForMenuButtonActivationsWithCallbackThatDoesntAcquireALock) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); button()->Activate(nullptr); EXPECT_EQ(InkDropState::ACTION_TRIGGERED, ink_drop()->GetTargetInkDropState()); } TEST_F( MenuButtonTest, InkDropStateForMenuButtonActivationsWithCallbackThatDoesntReleaseAllLocks) { ConfigureMenuButton(std::make_unique<PressStateButton>(false)); button()->Activate(nullptr); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); } TEST_F(MenuButtonTest, InkDropStateForMenuButtonActivationsWithCallbackThatReleasesAllLocks) { ConfigureMenuButton(std::make_unique<PressStateButton>(true)); button()->Activate(nullptr); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop()->GetTargetInkDropState()); } // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_InkDropStateForMenuButtonsWithPressedLocks \ DISABLED_InkDropStateForMenuButtonsWithPressedLocks #else #define MAYBE_InkDropStateForMenuButtonsWithPressedLocks \ InkDropStateForMenuButtonsWithPressedLocks #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_InkDropStateForMenuButtonsWithPressedLocks) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); auto pressed_lock1 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); auto pressed_lock2 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); pressed_lock1.reset(); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); pressed_lock2.reset(); EXPECT_EQ(InkDropState::DEACTIVATED, ink_drop()->GetTargetInkDropState()); } // Verifies only one ink drop animation is triggered when multiple PressedLocks // are attached to a MenuButton. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_OneInkDropAnimationForReentrantPressedLocks \ DISABLED_OneInkDropAnimationForReentrantPressedLocks #else #define MAYBE_OneInkDropAnimationForReentrantPressedLocks \ OneInkDropAnimationForReentrantPressedLocks #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_OneInkDropAnimationForReentrantPressedLocks) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); auto pressed_lock1 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); ink_drop()->AnimateToState(InkDropState::ACTION_PENDING); auto pressed_lock2 = std::make_unique<MenuButtonController::PressedLock>( button()->button_controller()); EXPECT_EQ(InkDropState::ACTION_PENDING, ink_drop()->GetTargetInkDropState()); } // Verifies the InkDropState is left as ACTIVATED if a PressedLock is active // before another Activation occurs. // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_InkDropStateForMenuButtonWithPressedLockBeforeActivation \ DISABLED_InkDropStateForMenuButtonWithPressedLockBeforeActivation #else #define MAYBE_InkDropStateForMenuButtonWithPressedLockBeforeActivation \ InkDropStateForMenuButtonWithPressedLockBeforeActivation #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_InkDropStateForMenuButtonWithPressedLockBeforeActivation) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); MenuButtonController::PressedLock lock(button()->button_controller()); button()->Activate(nullptr); EXPECT_EQ(InkDropState::ACTIVATED, ink_drop()->GetTargetInkDropState()); } #if defined(USE_AURA) // Tests that the MenuButton does not become pressed if it can be dragged, and a // DragDropClient is processing the events. // TODO(crbug.com/1433710): Test flaky on MSAN ChromeOS builders. #if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER) #define MAYBE_DraggableMenuButtonDoesNotActivateOnDrag \ DISABLED_DraggableMenuButtonDoesNotActivateOnDrag #else #define MAYBE_DraggableMenuButtonDoesNotActivateOnDrag \ DraggableMenuButtonDoesNotActivateOnDrag #endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER) TEST_F(MenuButtonTest, MAYBE_DraggableMenuButtonDoesNotActivateOnDrag) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); TestDragController drag_controller; button()->set_drag_controller(&drag_controller); TestDragDropClient drag_client; SetDragDropClient(GetContext(), &drag_client); button()->AddPreTargetHandler(&drag_client, ui::EventTarget::Priority::kSystem); generator()->DragMouseBy(10, 0); EXPECT_FALSE(button()->clicked()); EXPECT_EQ(Button::STATE_NORMAL, button()->last_state()); button()->RemovePreTargetHandler(&drag_client); } #endif // USE_AURA // No touch on desktop Mac. Tracked in http://crbug.com/445520. #if !BUILDFLAG(IS_MAC) || defined(USE_AURA) // Tests if the callback is notified correctly when a gesture tap happens on a // MenuButton that has a callback. TEST_F(MenuButtonTest, ActivateDropDownOnGestureTap) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); // Move the mouse outside the menu button so that it doesn't impact the // button state. generator()->MoveMouseTo(400, 400); EXPECT_FALSE(button()->IsMouseHovered()); generator()->GestureTapAt(gfx::Point(10, 10)); // Check that MenuButton has notified the callback, while it was in pressed // state. EXPECT_TRUE(button()->clicked()); EXPECT_EQ(Button::STATE_HOVERED, button()->last_state()); // The button should go back to its normal state since the gesture ended. EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); } // Tests that the button enters a hovered state upon a tap down, before becoming // pressed at activation. TEST_F(MenuButtonTest, TouchFeedbackDuringTap) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); generator()->PressTouch(); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); generator()->ReleaseTouch(); EXPECT_EQ(Button::STATE_HOVERED, button()->last_state()); } // Tests that a move event that exits the button returns it to the normal state, // and that the button did not activate the callback. TEST_F(MenuButtonTest, TouchFeedbackDuringTapCancel) { ConfigureMenuButton(std::make_unique<TestMenuButton>()); generator()->PressTouch(); EXPECT_EQ(Button::STATE_HOVERED, button()->GetState()); generator()->MoveTouch(gfx::Point(10, 30)); generator()->ReleaseTouch(); EXPECT_EQ(Button::STATE_NORMAL, button()->GetState()); EXPECT_FALSE(button()->clicked()); } #endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA) TEST_F(MenuButtonTest, InkDropHoverWhenShowingMenu) { ConfigureMenuButton(std::make_unique<PressStateButton>(false)); generator()->MoveMouseTo(GetOutOfButtonLocation()); EXPECT_FALSE(ink_drop()->is_hovered()); generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(ink_drop()->is_hovered()); generator()->PressLeftButton(); EXPECT_FALSE(ink_drop()->is_hovered()); } TEST_F(MenuButtonTest, InkDropIsHoveredAfterDismissingMenuWhenMouseOverButton) { auto press_state_button = std::make_unique<PressStateButton>(false); auto* test_button = press_state_button.get(); ConfigureMenuButton(std::move(press_state_button)); generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); generator()->PressLeftButton(); EXPECT_FALSE(ink_drop()->is_hovered()); test_button->ReleasePressedLock(); EXPECT_TRUE(ink_drop()->is_hovered()); } TEST_F(MenuButtonTest, InkDropIsntHoveredAfterDismissingMenuWhenMouseOutsideButton) { auto press_state_button = std::make_unique<PressStateButton>(false); auto* test_button = press_state_button.get(); ConfigureMenuButton(std::move(press_state_button)); generator()->MoveMouseTo(button()->GetBoundsInScreen().CenterPoint()); generator()->PressLeftButton(); generator()->MoveMouseTo(GetOutOfButtonLocation()); test_button->ReleasePressedLock(); EXPECT_FALSE(ink_drop()->is_hovered()); } // This test ensures there isn't a UAF in MenuButton::OnGestureEvent() if the // button callback deletes the MenuButton. TEST_F(MenuButtonTest, DestroyButtonInGesture) { std::unique_ptr<TestMenuButton> test_menu_button = std::make_unique<TestMenuButton>(base::BindRepeating( [](std::unique_ptr<TestMenuButton>* button) { button->reset(); }, &test_menu_button)); ConfigureMenuButton(std::move(test_menu_button)); ui::GestureEvent gesture_event(0, 0, 0, base::TimeTicks::Now(), ui::GestureEventDetails(ui::ET_GESTURE_TAP)); button()->OnGestureEvent(&gesture_event); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/button/menu_button_unittest.cc
C++
unknown
26,166