code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate_win.h"
#include <oleacc.h>
#include <memory>
#include <set>
#include <vector>
#include "base/memory/singleton.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_text_utils.h"
#include "ui/accessibility/platform/ax_fragment_root_win.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/layout.h"
#include "ui/base/win/atl_module.h"
#include "ui/display/win/screen_win.h"
#include "ui/views/accessibility/views_utilities_aura.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/win/hwnd_util.h"
namespace views {
// static
std::unique_ptr<ViewAccessibility> ViewAccessibility::Create(View* view) {
auto result = std::make_unique<ViewAXPlatformNodeDelegateWin>(view);
result->Init();
return result;
}
ViewAXPlatformNodeDelegateWin::ViewAXPlatformNodeDelegateWin(View* view)
: ViewAXPlatformNodeDelegate(view) {}
ViewAXPlatformNodeDelegateWin::~ViewAXPlatformNodeDelegateWin() = default;
gfx::NativeViewAccessible ViewAXPlatformNodeDelegateWin::GetParent() const {
// If the View has a parent View, return that View's IAccessible.
if (view()->parent())
return ViewAXPlatformNodeDelegate::GetParent();
// Otherwise we must be the RootView, get the corresponding Widget
// and Window.
Widget* widget = view()->GetWidget();
if (!widget)
return nullptr;
aura::Window* window = widget->GetNativeWindow();
if (!window)
return nullptr;
// Look for an ancestor window with a Widget, and if found, return
// the NativeViewAccessible for its RootView.
aura::Window* ancestor_window = GetWindowParentIncludingTransient(window);
while (ancestor_window) {
Widget* ancestor_widget = Widget::GetWidgetForNativeView(ancestor_window);
if (ancestor_widget && ancestor_widget->GetRootView())
return ancestor_widget->GetRootView()->GetNativeViewAccessible();
ancestor_window = GetWindowParentIncludingTransient(ancestor_window);
}
// If that fails, return the NativeViewAccessible for our owning HWND.
HWND hwnd = HWNDForView(view());
if (!hwnd)
return nullptr;
IAccessible* parent;
if (SUCCEEDED(
::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&parent)))) {
return parent;
}
return nullptr;
}
gfx::AcceleratedWidget
ViewAXPlatformNodeDelegateWin::GetTargetForNativeAccessibilityEvent() {
return HWNDForView(view());
}
gfx::Rect ViewAXPlatformNodeDelegateWin::GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const {
switch (coordinate_system) {
case ui::AXCoordinateSystem::kScreenPhysicalPixels:
return display::win::ScreenWin::DIPToScreenRect(
HWNDForView(view()), view()->GetBoundsInScreen());
case ui::AXCoordinateSystem::kScreenDIPs:
// We could optionally add clipping here if ever needed.
return view()->GetBoundsInScreen();
case ui::AXCoordinateSystem::kRootFrame:
case ui::AXCoordinateSystem::kFrame:
NOTIMPLEMENTED();
return gfx::Rect();
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_win.cc | C++ | unknown | 3,721 |
// 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_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_WIN_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_WIN_H_
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
namespace views {
class View;
class ViewAXPlatformNodeDelegateWin : public ViewAXPlatformNodeDelegate {
public:
explicit ViewAXPlatformNodeDelegateWin(View* view);
ViewAXPlatformNodeDelegateWin(const ViewAXPlatformNodeDelegateWin&) = delete;
ViewAXPlatformNodeDelegateWin& operator=(
const ViewAXPlatformNodeDelegateWin&) = delete;
~ViewAXPlatformNodeDelegateWin() override;
// |ViewAXPlatformNodeDelegate| overrides:
gfx::NativeViewAccessible GetParent() const override;
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
gfx::Rect GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const override;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_win.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/accessibility/view_ax_platform_node_delegate_win.h"
#include <oleacc.h>
#include <wrl/client.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_variant.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/accessibility/ax_constants.mojom.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/views/accessibility/test_list_grid_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/unique_widget_ptr.h"
using base::win::ScopedBstr;
using base::win::ScopedVariant;
using Microsoft::WRL::ComPtr;
namespace views {
namespace test {
#define EXPECT_UIA_BOOL_EQ(node, property_id, expected) \
{ \
ScopedVariant expectedVariant(expected); \
ASSERT_EQ(VT_BOOL, expectedVariant.type()); \
ScopedVariant actual; \
ASSERT_HRESULT_SUCCEEDED( \
node->GetPropertyValue(property_id, actual.Receive())); \
EXPECT_EQ(expectedVariant.ptr()->boolVal, actual.ptr()->boolVal); \
}
namespace {
// Whether |left| represents the same COM object as |right|.
template <typename T, typename U>
bool IsSameObject(T* left, U* right) {
if (!left && !right)
return true;
if (!left || !right)
return false;
ComPtr<IUnknown> left_unknown;
left->QueryInterface(IID_PPV_ARGS(&left_unknown));
ComPtr<IUnknown> right_unknown;
right->QueryInterface(IID_PPV_ARGS(&right_unknown));
return left_unknown == right_unknown;
}
} // namespace
class ViewAXPlatformNodeDelegateWinTest : public ViewsTestBase {
public:
ViewAXPlatformNodeDelegateWinTest() = default;
~ViewAXPlatformNodeDelegateWinTest() override = default;
protected:
void GetIAccessible2InterfaceForView(View* view, IAccessible2_2** result) {
ComPtr<IAccessible> view_accessible(view->GetNativeViewAccessible());
ComPtr<IServiceProvider> service_provider;
ASSERT_EQ(S_OK, view_accessible.As(&service_provider));
ASSERT_EQ(S_OK, service_provider->QueryService(IID_IAccessible2_2, result));
}
ComPtr<IRawElementProviderSimple> GetIRawElementProviderSimple(View* view) {
ComPtr<IRawElementProviderSimple> result;
EXPECT_HRESULT_SUCCEEDED(view->GetNativeViewAccessible()->QueryInterface(
__uuidof(IRawElementProviderSimple), &result));
return result;
}
ComPtr<IAccessible2> ToIAccessible2(ComPtr<IAccessible> accessible) {
CHECK(accessible);
ComPtr<IServiceProvider> service_provider;
accessible.As(&service_provider);
ComPtr<IAccessible2> result;
CHECK(SUCCEEDED(service_provider->QueryService(IID_IAccessible2,
IID_PPV_ARGS(&result))));
return result;
}
};
TEST_F(ViewAXPlatformNodeDelegateWinTest, TextfieldAccessibility) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
Textfield* textfield = new Textfield;
textfield->SetAccessibleName(u"Name");
textfield->SetText(u"Value");
content->AddChildView(textfield);
ComPtr<IAccessible> content_accessible(content->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
EXPECT_EQ(1, child_count);
ComPtr<IDispatch> textfield_dispatch;
ComPtr<IAccessible> textfield_accessible;
ScopedVariant child_index(1);
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &textfield_dispatch));
ASSERT_EQ(S_OK, textfield_dispatch.As(&textfield_accessible));
ASSERT_EQ(S_OK, textfield_accessible->get_accChildCount(&child_count));
EXPECT_EQ(0, child_count)
<< "Text fields should be leaf nodes on this platform, otherwise no "
"descendants will be recognized by assistive software.";
ScopedBstr name;
ScopedVariant childid_self(CHILDID_SELF);
ASSERT_EQ(S_OK,
textfield_accessible->get_accName(childid_self, name.Receive()));
EXPECT_STREQ(L"Name", name.Get());
ScopedBstr value;
ASSERT_EQ(S_OK,
textfield_accessible->get_accValue(childid_self, value.Receive()));
EXPECT_STREQ(L"Value", value.Get());
ScopedBstr new_value(L"New value");
ASSERT_EQ(S_OK,
textfield_accessible->put_accValue(childid_self, new_value.Get()));
EXPECT_EQ(u"New value", textfield->GetText());
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, TextfieldAssociatedLabel) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
Label* label = new Label(u"Label");
content->AddChildView(label);
Textfield* textfield = new Textfield;
textfield->SetAccessibleName(label);
content->AddChildView(textfield);
ComPtr<IAccessible> content_accessible(content->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
ASSERT_EQ(2L, child_count);
ComPtr<IDispatch> textfield_dispatch;
ComPtr<IAccessible> textfield_accessible;
ScopedVariant child_index(2);
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &textfield_dispatch));
ASSERT_EQ(S_OK, textfield_dispatch.As(&textfield_accessible));
ScopedBstr name;
ScopedVariant childid_self(CHILDID_SELF);
ASSERT_EQ(S_OK,
textfield_accessible->get_accName(childid_self, name.Receive()));
ASSERT_STREQ(L"Label", name.Get());
ComPtr<IAccessible2_2> textfield_ia2;
EXPECT_EQ(S_OK, textfield_accessible.As(&textfield_ia2));
ScopedBstr type(IA2_RELATION_LABELLED_BY);
IUnknown** targets;
LONG n_targets;
EXPECT_EQ(S_OK, textfield_ia2->get_relationTargetsOfType(
type.Get(), 0, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ComPtr<IUnknown> label_unknown(targets[0]);
ComPtr<IAccessible> label_accessible;
ASSERT_EQ(S_OK, label_unknown.As(&label_accessible));
ScopedVariant role;
EXPECT_EQ(S_OK, label_accessible->get_accRole(childid_self, role.Receive()));
EXPECT_EQ(ROLE_SYSTEM_STATICTEXT, V_I4(role.ptr()));
}
// A subclass of ViewAXPlatformNodeDelegateWinTest that we run twice,
// first where we create an transient child widget (child = false), the second
// time where we create a child widget (child = true).
class ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag
: public ViewAXPlatformNodeDelegateWinTest,
public testing::WithParamInterface<bool> {
public:
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag() = default;
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag(
const ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag&) = delete;
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag& operator=(
const ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag&) = delete;
~ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag() override = default;
};
INSTANTIATE_TEST_SUITE_P(All,
ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag,
testing::Bool());
TEST_P(ViewAXPlatformNodeDelegateWinTestWithBoolChildFlag, AuraChildWidgets) {
// Create the parent widget.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.bounds = gfx::Rect(0, 0, 400, 200);
widget->Init(std::move(init_params));
widget->Show();
// Initially it has 1 child.
ComPtr<IAccessible> root_view_accessible(
widget->GetRootView()->GetNativeViewAccessible());
LONG child_count = 0;
ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count));
ASSERT_EQ(1L, child_count);
// Create the child widget, one of two ways (see below).
UniqueWidgetPtr child_widget = std::make_unique<Widget>();
Widget::InitParams child_init_params =
CreateParams(Widget::InitParams::TYPE_BUBBLE);
child_init_params.parent = widget->GetNativeView();
child_init_params.bounds = gfx::Rect(30, 40, 100, 50);
// NOTE: this test is run two times, GetParam() returns a different
// value each time. The first time we test with child = false,
// making this an owned widget (a transient child). The second time
// we test with child = true, making it a child widget->
child_init_params.child = GetParam();
child_widget->Init(std::move(child_init_params));
child_widget->Show();
// Now the IAccessible for the parent widget should have 2 children.
ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count));
ASSERT_EQ(2L, child_count);
// Ensure the bounds of the parent widget are as expected.
ScopedVariant childid_self(CHILDID_SELF);
LONG x, y, width, height;
ASSERT_EQ(S_OK, root_view_accessible->accLocation(&x, &y, &width, &height,
childid_self));
EXPECT_EQ(0, x);
EXPECT_EQ(0, y);
EXPECT_EQ(400, width);
EXPECT_EQ(200, height);
// Get the IAccessible for the second child of the parent widget,
// which should be the one for our child widget->
ComPtr<IDispatch> child_widget_dispatch;
ComPtr<IAccessible> child_widget_accessible;
ScopedVariant child_index_2(2);
ASSERT_EQ(S_OK, root_view_accessible->get_accChild(child_index_2,
&child_widget_dispatch));
ASSERT_EQ(S_OK, child_widget_dispatch.As(&child_widget_accessible));
// Check the bounds of the IAccessible for the child widget->
// This is a sanity check to make sure we have the right object
// and not some other view.
ASSERT_EQ(S_OK, child_widget_accessible->accLocation(&x, &y, &width, &height,
childid_self));
EXPECT_EQ(30, x);
EXPECT_EQ(40, y);
EXPECT_EQ(100, width);
EXPECT_EQ(50, height);
// Now make sure that querying the parent of the child gets us back to
// the original parent.
ComPtr<IDispatch> child_widget_parent_dispatch;
ComPtr<IAccessible> child_widget_parent_accessible;
ASSERT_EQ(S_OK, child_widget_accessible->get_accParent(
&child_widget_parent_dispatch));
ASSERT_EQ(S_OK,
child_widget_parent_dispatch.As(&child_widget_parent_accessible));
EXPECT_EQ(root_view_accessible.Get(), child_widget_parent_accessible.Get());
}
// Flaky on Windows: https://crbug.com/461837.
TEST_F(ViewAXPlatformNodeDelegateWinTest, DISABLED_RetrieveAllAlerts) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
View* infobar = new View;
content->AddChildView(infobar);
View* infobar2 = new View;
content->AddChildView(infobar2);
View* root_view = content->parent();
ASSERT_EQ(nullptr, root_view->parent());
ComPtr<IAccessible2_2> root_view_accessible;
GetIAccessible2InterfaceForView(root_view, &root_view_accessible);
ComPtr<IAccessible2_2> infobar_accessible;
GetIAccessible2InterfaceForView(infobar, &infobar_accessible);
ComPtr<IAccessible2_2> infobar2_accessible;
GetIAccessible2InterfaceForView(infobar2, &infobar2_accessible);
// Initially, there are no alerts
ScopedBstr alerts_bstr(L"alerts");
IUnknown** targets;
LONG n_targets;
ASSERT_EQ(S_FALSE, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(0, n_targets);
// Fire alert events on the infobars.
infobar->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
infobar2->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
// Now calling get_relationTargetsOfType should retrieve the alerts.
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(2, n_targets);
ASSERT_TRUE(IsSameObject(infobar_accessible.Get(), targets[0]));
ASSERT_TRUE(IsSameObject(infobar2_accessible.Get(), targets[1]));
CoTaskMemFree(targets);
// If we set max_targets to 1, we should only get the first one.
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 1, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ASSERT_TRUE(IsSameObject(infobar_accessible.Get(), targets[0]));
CoTaskMemFree(targets);
// If we delete the first view, we should only get the second one now.
delete infobar;
ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType(
alerts_bstr.Get(), 0, &targets, &n_targets));
ASSERT_EQ(1, n_targets);
ASSERT_TRUE(IsSameObject(infobar2_accessible.Get(), targets[0]));
CoTaskMemFree(targets);
}
// Test trying to retrieve child widgets during window close does not crash.
// TODO(crbug.com/1218885): Remove this after WIDGET_OWNS_NATIVE_WIDGET is gone.
TEST_F(ViewAXPlatformNodeDelegateWinTest, GetAllOwnedWidgetsCrash) {
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
widget.CloseNow();
LONG child_count = 0;
ComPtr<IAccessible> content_accessible(
widget.GetRootView()->GetNativeViewAccessible());
EXPECT_EQ(S_OK, content_accessible->get_accChildCount(&child_count));
EXPECT_EQ(1L, child_count);
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, WindowHasRoleApplication) {
// We expect that our internal window object does not expose
// ROLE_SYSTEM_WINDOW, but ROLE_SYSTEM_PANE instead.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(init_params));
ComPtr<IAccessible> accessible(
widget->GetRootView()->GetNativeViewAccessible());
ScopedVariant childid_self(CHILDID_SELF);
ScopedVariant role;
EXPECT_EQ(S_OK, accessible->get_accRole(childid_self, role.Receive()));
EXPECT_EQ(VT_I4, role.type());
EXPECT_EQ(ROLE_SYSTEM_PANE, V_I4(role.ptr()));
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, Overrides) {
// We expect that our internal window object does not expose
// ROLE_SYSTEM_WINDOW, but ROLE_SYSTEM_PANE instead.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* contents_view = widget->SetContentsView(std::make_unique<View>());
View* alert_view = new ScrollView;
alert_view->GetViewAccessibility().OverrideRole(ax::mojom::Role::kAlert);
alert_view->GetViewAccessibility().OverrideName(u"Name");
alert_view->GetViewAccessibility().OverrideDescription("Description");
alert_view->GetViewAccessibility().OverrideIsLeaf(true);
contents_view->AddChildView(alert_view);
// Descendant should be ignored because the parent uses OverrideIsLeaf().
View* ignored_descendant = new View;
alert_view->AddChildView(ignored_descendant);
ComPtr<IAccessible> content_accessible(
contents_view->GetNativeViewAccessible());
ScopedVariant child_index(1);
// Role.
ScopedVariant role;
EXPECT_EQ(S_OK, content_accessible->get_accRole(child_index, role.Receive()));
EXPECT_EQ(VT_I4, role.type());
EXPECT_EQ(ROLE_SYSTEM_ALERT, V_I4(role.ptr()));
// Name.
ScopedBstr name;
ASSERT_EQ(S_OK, content_accessible->get_accName(child_index, name.Receive()));
ASSERT_STREQ(L"Name", name.Get());
// Description.
ScopedBstr description;
ASSERT_EQ(S_OK, content_accessible->get_accDescription(
child_index, description.Receive()));
ASSERT_STREQ(L"Description", description.Get());
// Get the child accessible.
ComPtr<IDispatch> alert_dispatch;
ComPtr<IAccessible> alert_accessible;
ASSERT_EQ(S_OK,
content_accessible->get_accChild(child_index, &alert_dispatch));
ASSERT_EQ(S_OK, alert_dispatch.As(&alert_accessible));
// Child accessible is a leaf.
LONG child_count = 0;
ASSERT_EQ(S_OK, alert_accessible->get_accChildCount(&child_count));
ASSERT_EQ(0, child_count);
ComPtr<IDispatch> child_dispatch;
ASSERT_EQ(E_INVALIDARG,
alert_accessible->get_accChild(child_index, &child_dispatch));
ASSERT_EQ(child_dispatch.Get(), nullptr);
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, GridRowColumnCount) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
TestListGridView* grid = new TestListGridView();
content->AddChildView(grid);
Microsoft::WRL::ComPtr<IGridProvider> grid_provider;
EXPECT_HRESULT_SUCCEEDED(
grid->GetViewAccessibility().GetNativeObject()->QueryInterface(
__uuidof(IGridProvider), &grid_provider));
// If set, aria row/column count takes precedence over table row/column count.
// Expect E_UNEXPECTED if the result is kUnknownAriaColumnOrRowCount (-1) or
// if neither is set.
int row_count;
int column_count;
// aria row/column count = not set
// table row/column count = not set
grid->UnsetAriaTableSize();
grid->UnsetTableSize();
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(0, row_count);
EXPECT_EQ(0, column_count);
// To do still: When nothing is set, currently
// AXPlatformNodeDelegateBase::GetTable{Row/Col}Count() returns 0 Should it
// return absl::nullopt if the attribute is not set? Like
// GetTableAria{Row/Col}Count()
// EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
// aria row/column count = 2
// table row/column count = not set
grid->SetAriaTableSize(2, 2);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(2, row_count);
EXPECT_EQ(2, column_count);
// aria row/column count = kUnknownAriaColumnOrRowCount
// table row/column count = not set
grid->SetAriaTableSize(ax::mojom::kUnknownAriaColumnOrRowCount,
ax::mojom::kUnknownAriaColumnOrRowCount);
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_ColumnCount(&column_count));
// aria row/column count = 3
// table row/column count = 4
grid->SetAriaTableSize(3, 3);
grid->SetTableSize(4, 4);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(3, row_count);
EXPECT_EQ(3, column_count);
// aria row/column count = not set
// table row/column count = 4
grid->UnsetAriaTableSize();
grid->SetTableSize(4, 4);
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_RowCount(&row_count));
EXPECT_HRESULT_SUCCEEDED(grid_provider->get_ColumnCount(&column_count));
EXPECT_EQ(4, row_count);
EXPECT_EQ(4, column_count);
// aria row/column count = not set
// table row/column count = kUnknownAriaColumnOrRowCount
grid->SetTableSize(ax::mojom::kUnknownAriaColumnOrRowCount,
ax::mojom::kUnknownAriaColumnOrRowCount);
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_RowCount(&row_count));
EXPECT_EQ(E_UNEXPECTED, grid_provider->get_ColumnCount(&column_count));
}
TEST_F(ViewAXPlatformNodeDelegateWinTest, IsUIAControlIsTrueEvenWhenReadonly) {
// This test ensures that the value returned by
// AXPlatformNodeWin::IsUIAControl returns true even if the element is
// read-only. The previous implementation was incorrect and used to return
// false for read-only views, causing all sorts of issues with ATs.
//
// Since we can't test IsUIAControl directly, we go through the
// UIA_IsControlElementPropertyId, which is computed using IsUIAControl.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
Textfield* text_field = new Textfield();
text_field->SetReadOnly(true);
content->AddChildView(text_field);
ComPtr<IRawElementProviderSimple> textfield_provider =
GetIRawElementProviderSimple(text_field);
EXPECT_UIA_BOOL_EQ(textfield_provider, UIA_IsControlElementPropertyId, true);
}
//
// TableView tests.
//
namespace {
class TestTableModel : public ui::TableModel {
public:
TestTableModel() = default;
TestTableModel(const TestTableModel&) = delete;
TestTableModel& operator=(const TestTableModel&) = delete;
// ui::TableModel:
size_t RowCount() override { return 3; }
std::u16string GetText(size_t row, int column_id) override {
const char* const cells[5][3] = {
{"Australia", "24,584,620", "1,323,421,072,479"},
{"Spain", "46,647,428", "1,314,314,164,402"},
{"Nigeria", "190.873,244", "375,745,486,521"},
};
return base::ASCIIToUTF16(cells[row % 5][column_id]);
}
void SetObserver(ui::TableModelObserver* observer) override {}
};
} // namespace
class ViewAXPlatformNodeDelegateWinTableTest
: public ViewAXPlatformNodeDelegateWinTest {
void SetUp() override {
ViewAXPlatformNodeDelegateWinTest::SetUp();
std::vector<ui::TableColumn> columns;
columns.push_back(TestTableColumn(0, "Country"));
columns.push_back(TestTableColumn(1, "Population"));
columns.push_back(TestTableColumn(2, "GDP"));
model_ = std::make_unique<TestTableModel>();
auto table =
std::make_unique<TableView>(model_.get(), columns, TEXT_ONLY, true);
table_ = table.get();
widget_ = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
init_params.bounds = gfx::Rect(0, 0, 400, 400);
widget_->Init(std::move(init_params));
View* content = widget_->SetContentsView(std::make_unique<View>());
content->AddChildView(
TableView::CreateScrollViewWithTable(std::move(table)));
widget_->Show();
}
void TearDown() override {
if (!widget_->IsClosed())
widget_->Close();
ViewAXPlatformNodeDelegateWinTest::TearDown();
}
ui::TableColumn TestTableColumn(int id, const std::string& title) {
ui::TableColumn column;
column.id = id;
column.title = base::ASCIIToUTF16(title.c_str());
column.sortable = true;
return column;
}
protected:
std::unique_ptr<TestTableModel> model_;
UniqueWidgetPtr widget_;
raw_ptr<TableView> table_ = nullptr; // Owned by parent.
};
TEST_F(ViewAXPlatformNodeDelegateWinTableTest, TableCellAttributes) {
ComPtr<IAccessible2_2> table_accessible;
GetIAccessible2InterfaceForView(table_, &table_accessible);
auto get_attributes = [&](int row_child, int cell_child) -> std::wstring {
ComPtr<IDispatch> row_dispatch;
CHECK_EQ(S_OK, table_accessible->get_accChild(ScopedVariant(row_child),
&row_dispatch));
ComPtr<IAccessible> row;
CHECK_EQ(S_OK, row_dispatch.As(&row));
ComPtr<IAccessible2> ia2_row = ToIAccessible2(row);
ComPtr<IDispatch> cell_dispatch;
CHECK_EQ(S_OK,
row->get_accChild(ScopedVariant(cell_child), &cell_dispatch));
ComPtr<IAccessible> cell;
CHECK_EQ(S_OK, cell_dispatch.As(&cell));
ComPtr<IAccessible2> ia2_cell = ToIAccessible2(cell);
ScopedBstr attributes_bstr;
CHECK_EQ(S_OK, ia2_cell->get_attributes(attributes_bstr.Receive()));
std::wstring attributes(attributes_bstr.Get());
return attributes;
};
// These strings should NOT contain rowindex or colindex, since those
// imply an ARIA override.
EXPECT_EQ(get_attributes(1, 1),
L"explicit-name:true;sort:none;class:AXVirtualView;");
EXPECT_EQ(get_attributes(1, 2),
L"explicit-name:true;sort:none;class:AXVirtualView;");
EXPECT_EQ(get_attributes(2, 1),
L"hidden:true;explicit-name:true;class:AXVirtualView;");
EXPECT_EQ(get_attributes(2, 2),
L"hidden:true;explicit-name:true;class:AXVirtualView;");
}
} // namespace test
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc | C++ | unknown | 25,146 |
// 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/accessibility/views_ax_tree_manager.h"
#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/notreached.h"
#include "base/task/sequenced_task_runner.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_tree_source_checker.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/widget_ax_tree_id_map.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
ViewsAXTreeManager::ViewsAXTreeManager(Widget* widget)
: ui::AXTreeManager(std::make_unique<ui::AXTree>()),
widget_(widget),
tree_source_(cache_.GetOrCreate(widget),
ui::AXTreeID::CreateNewAXTreeID(),
&cache_),
tree_serializer_(&tree_source_) {
DCHECK(widget);
views::WidgetAXTreeIDMap::GetInstance().AddWidget(tree_source_.tree_id(),
widget);
views_event_observer_.Observe(AXEventManager::Get());
widget_observer_.Observe(widget);
// Load complete can't be fired synchronously here. The act of firing the
// event will call |View::GetViewAccessibility|, which (if fired
// synchronously) will create *another* |ViewsAXTreeManager| for the same
// widget, since the wrapper that created this |ViewsAXTreeManager| hasn't
// been added to the cache yet.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&ViewsAXTreeManager::FireLoadComplete,
weak_factory_.GetWeakPtr()));
}
ViewsAXTreeManager::~ViewsAXTreeManager() {
views_event_observer_.Reset();
widget_observer_.Reset();
}
void ViewsAXTreeManager::SetGeneratedEventCallbackForTesting(
const GeneratedEventCallbackForTesting& callback) {
generated_event_callback_for_testing_ = callback;
}
void ViewsAXTreeManager::UnsetGeneratedEventCallbackForTesting() {
generated_event_callback_for_testing_.Reset();
}
ui::AXNode* ViewsAXTreeManager::GetNode(
const ui::AXNodeID node_id) const {
if (!widget_ || !widget_->GetRootView() || !ax_tree_)
return nullptr;
return ax_tree_->GetFromId(node_id);
}
ui::AXTreeID ViewsAXTreeManager::GetParentTreeID() const {
// TODO(nektar): Implement stiching of AXTrees, e.g. a dialog to the main
// window.
return ui::AXTreeIDUnknown();
}
ui::AXNode* ViewsAXTreeManager::GetParentNodeFromParentTree() const {
// TODO(nektar): Implement stiching of AXTrees, e.g. a dialog to the main
// window.
return nullptr;
}
void ViewsAXTreeManager::OnViewEvent(View* view, ax::mojom::Event event) {
DCHECK(view);
AXAuraObjWrapper* wrapper = cache_.GetOrCreate(view);
if (!wrapper)
return;
modified_nodes_.insert(wrapper->GetUniqueId());
if (waiting_to_serialize_)
return;
waiting_to_serialize_ = true;
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&ViewsAXTreeManager::SerializeTreeUpdates,
weak_factory_.GetWeakPtr()));
}
void ViewsAXTreeManager::OnWidgetDestroyed(Widget* widget) {
// If a widget becomes disconnected from its root view, we shouldn't keep it
// in the map or attempt any operations on it.
if (widget->is_top_level() || !widget->GetRootView())
views::WidgetAXTreeIDMap::GetInstance().RemoveWidget(widget);
widget_ = nullptr;
}
void ViewsAXTreeManager::PerformAction(const ui::AXActionData& data) {
if (!widget_ || !widget_->GetRootView())
return;
tree_source_.HandleAccessibleAction(data);
}
void ViewsAXTreeManager::SerializeTreeUpdates() {
if (!widget_ || !widget_->GetRootView())
return;
// Better to set this flag to false early in case this method, or any method
// it calls, causes an event to get fired.
waiting_to_serialize_ = false;
// Make sure the focused node is serialized.
AXAuraObjWrapper* focused_wrapper = cache_.GetFocus();
if (focused_wrapper)
modified_nodes_.insert(focused_wrapper->GetUniqueId());
std::vector<ui::AXTreeUpdate> updates;
for (const ui::AXNodeID node_id : modified_nodes_) {
AXAuraObjWrapper* wrapper = cache_.Get(node_id);
if (!wrapper)
continue;
ui::AXTreeUpdate update;
// TODO(pbos): Consider rewriting this as a CHECK now that this is fatally
// aborting.
if (!tree_serializer_.SerializeChanges(wrapper, &update)) {
std::string error;
ui::AXTreeSourceChecker<AXAuraObjWrapper*> checker(&tree_source_);
checker.CheckAndGetErrorString(&error);
NOTREACHED_NORETURN() << error << '\n' << update.ToString();
}
updates.push_back(update);
}
UnserializeTreeUpdates(updates);
}
void ViewsAXTreeManager::UnserializeTreeUpdates(
const std::vector<ui::AXTreeUpdate>& updates) {
if (!widget_ || !widget_->GetRootView() || !ax_tree_)
return;
for (const ui::AXTreeUpdate& update : updates) {
CHECK(ax_tree_->Unserialize(update)) << ax_tree_->error();
}
// Unserializing the updates into our AXTree should have prompted our
// AXEventGenerator to generate events based on the updates.
for (const ui::AXEventGenerator::TargetedEvent& targeted_event :
event_generator_) {
if (ui::AXNode* node = ax_tree_->GetFromId(targeted_event.node_id))
FireGeneratedEvent(targeted_event.event_params.event, node);
}
event_generator_.ClearEvents();
}
void ViewsAXTreeManager::FireLoadComplete() {
DCHECK(widget_.get());
View* root_view = widget_->GetRootView();
if (root_view)
root_view->NotifyAccessibilityEvent(ax::mojom::Event::kLoadComplete, true);
}
void ViewsAXTreeManager::FireGeneratedEvent(ui::AXEventGenerator::Event event,
const ui::AXNode* node) {
if (!generated_event_callback_for_testing_.is_null())
generated_event_callback_for_testing_.Run(widget_.get(), event, node->id());
// TODO(nektar): Implement this other than "for testing".
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/views_ax_tree_manager.cc | C++ | unknown | 6,292 |
// 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_ACCESSIBILITY_VIEWS_AX_TREE_MANAGER_H_
#define UI_VIEWS_ACCESSIBILITY_VIEWS_AX_TREE_MANAGER_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observation.h"
#include "ui/accessibility/ax_action_handler.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/ax_tree_manager.h"
#include "ui/accessibility/ax_tree_serializer.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/ax_event_observer.h"
#include "ui/views/accessibility/ax_tree_source_views.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace ui {
struct AXActionData;
} // namespace ui
namespace views {
class AXAuraObjWrapper;
class View;
// Manages an accessibility tree that mirrors the Views tree for a particular
// widget.
//
// TODO(nektar): Enable navigating to parent and child accessibility trees for
// parent and child widgets, thereby allowing stiching the various accessibility
// trees into a unified platform tree.
//
// The Views tree is serialized into an AXTreeSource and immediately
// deserialized into an AXTree, both in the same process.
class VIEWS_EXPORT ViewsAXTreeManager : public ui::AXTreeManager,
public ui::AXActionHandler,
public AXEventObserver,
public views::WidgetObserver {
public:
using GeneratedEventCallbackForTesting = base::RepeatingCallback<
void(Widget*, ui::AXEventGenerator::Event, ui::AXNodeID)>;
// Creates an instance of this class that manages an AXTree mirroring the
// Views tree rooted at a given Widget.
//
// The provided |widget| doesn't own this class.
explicit ViewsAXTreeManager(Widget* widget);
~ViewsAXTreeManager() override;
ViewsAXTreeManager(const ViewsAXTreeManager& manager) = delete;
ViewsAXTreeManager& operator=(const ViewsAXTreeManager& manager) = delete;
// For testing only, register a function to be called when a generated event
// is fired from this ViewsAXTreeManager.
void SetGeneratedEventCallbackForTesting(
const GeneratedEventCallbackForTesting& callback);
// For testing only, unregister the function that was previously registered to
// be called when a generated event is fired from this ViewsAXTreeManager.
void UnsetGeneratedEventCallbackForTesting();
// AXTreeManager implementation.
ui::AXNode* GetNode(const ui::AXNodeID node_id) const override;
ui::AXTreeID GetParentTreeID() const override;
ui::AXNode* GetParentNodeFromParentTree() const override;
// AXActionHandlerBase implementation.
void PerformAction(const ui::AXActionData& data) override;
// AXEventObserver implementation.
void OnViewEvent(views::View* view, ax::mojom::Event event) override;
// WidgetObserver implementation.
void OnWidgetDestroyed(Widget* widget) override;
private:
using ViewsAXTreeSerializer = ui::AXTreeSerializer<AXAuraObjWrapper*>;
void SerializeTreeUpdates();
void UnserializeTreeUpdates(const std::vector<ui::AXTreeUpdate>& updates);
void FireLoadComplete();
// Determines the platform node which corresponds to the given |node| and
// fires the given |event| on it.
//
// TODO(nektar): Implement this other than for testing.
void FireGeneratedEvent(ui::AXEventGenerator::Event event,
const ui::AXNode* node) override;
// The Widget for which this class manages an AXTree.
//
// Weak, a Widget doesn't own this class.
raw_ptr<Widget> widget_;
// Set to true if we are still waiting for a task to serialize all previously
// modified nodes.
bool waiting_to_serialize_ = false;
// The set of nodes in the source tree that might have been modified after an
// event has been fired on them.
std::set<ui::AXNodeID> modified_nodes_;
// The cache that maps objects in the Views tree to AXAuraObjWrapper objects
// that are used to serialize the Views tree.
AXAuraObjCache cache_;
// The tree source that enables us to serialize the Views tree.
AXTreeSourceViews tree_source_;
// The serializer that serializes the Views tree into one or more
// AXTreeUpdate.
ViewsAXTreeSerializer tree_serializer_;
// For testing only: A function to call when a generated event is fired.
GeneratedEventCallbackForTesting generated_event_callback_for_testing_;
// To prevent any use-after-free, members below this line should be declared
// last.
base::ScopedObservation<AXEventManager, AXEventObserver>
views_event_observer_{this};
base::ScopedObservation<Widget, views::WidgetObserver> widget_observer_{this};
base::WeakPtrFactory<ViewsAXTreeManager> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEWS_AX_TREE_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/views_ax_tree_manager.h | C++ | unknown | 5,399 |
// 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/accessibility/views_ax_tree_manager.h"
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_event_generator.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/label.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"
namespace views::test {
namespace {
class TestButton : public Button {
public:
TestButton() : Button(Button::PressedCallback()) {}
TestButton(const TestButton&) = delete;
TestButton& operator=(const TestButton&) = delete;
~TestButton() override = default;
};
class ViewsAXTreeManagerTest : public ViewsTestBase,
public ::testing::WithParamInterface<bool> {
public:
ViewsAXTreeManagerTest() = default;
ViewsAXTreeManagerTest(const ViewsAXTreeManagerTest&) = delete;
ViewsAXTreeManagerTest& operator=(const ViewsAXTreeManagerTest&) = delete;
protected:
void SetUp() override;
void TearDown() override;
void CloseWidget();
ui::AXNode* FindNode(const ax::mojom::Role role,
const std::string& name_or_value) const;
void WaitFor(const ui::AXEventGenerator::Event event);
Widget* widget() const { return widget_.get(); }
Button* button() const { return button_; }
Label* label() const { return label_; }
ViewsAXTreeManager* manager() const {
return features::IsAccessibilityTreeForViewsEnabled()
? absl::get<raw_ptr<ViewsAXTreeManager>>(manager_).get()
: absl::get<std::unique_ptr<ViewsAXTreeManager>>(manager_).get();
}
private:
using TestOwnedManager = std::unique_ptr<ViewsAXTreeManager>;
using WidgetOwnedManager = raw_ptr<ViewsAXTreeManager>;
ui::AXNode* FindNodeInSubtree(ui::AXNode* root,
const ax::mojom::Role role,
const std::string& name_or_value) const;
void OnGeneratedEvent(Widget* widget,
ui::AXEventGenerator::Event event,
ui::AXNodeID node_id);
UniqueWidgetPtr widget_;
raw_ptr<Button> button_ = nullptr;
raw_ptr<Label> label_ = nullptr;
absl::variant<TestOwnedManager, WidgetOwnedManager> manager_;
ui::AXEventGenerator::Event event_to_wait_for_;
std::unique_ptr<base::RunLoop> loop_runner_;
base::test::ScopedFeatureList scoped_feature_list_;
};
void ViewsAXTreeManagerTest::SetUp() {
ViewsTestBase::SetUp();
if (GetParam()) {
scoped_feature_list_.InitWithFeatures(
{features::kEnableAccessibilityTreeForViews}, {});
}
widget_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget_->Init(std::move(params));
button_ = new TestButton();
button_->SetSize(gfx::Size(20, 20));
label_ = new Label();
button_->AddChildView(label_.get());
widget_->GetContentsView()->AddChildView(button_.get());
widget_->Show();
// AccessibilityTreeForViewsEnabled will create and manage its own
// ViewsAXTreeManager, so we don't need to create one for testing.
if (features::IsAccessibilityTreeForViewsEnabled()) {
manager_ = widget_->GetRootView()->GetViewAccessibility().AXTreeManager();
} else {
manager_ = std::make_unique<ViewsAXTreeManager>(widget_.get());
}
ASSERT_NE(nullptr, manager());
manager()->SetGeneratedEventCallbackForTesting(base::BindRepeating(
&ViewsAXTreeManagerTest::OnGeneratedEvent, base::Unretained(this)));
WaitFor(ui::AXEventGenerator::Event::SUBTREE_CREATED);
}
void ViewsAXTreeManagerTest::TearDown() {
if (manager())
manager()->UnsetGeneratedEventCallbackForTesting();
if (features::IsAccessibilityTreeForViewsEnabled())
manager_.emplace<WidgetOwnedManager>(nullptr);
else
manager_.emplace<TestOwnedManager>(nullptr);
CloseWidget();
ViewsTestBase::TearDown();
}
void ViewsAXTreeManagerTest::CloseWidget() {
if (!widget_->IsClosed())
widget_->CloseNow();
RunPendingMessages();
}
ui::AXNode* ViewsAXTreeManagerTest::FindNode(
const ax::mojom::Role role,
const std::string& name_or_value) const {
ui::AXNode* root = manager()->GetRoot();
// If the manager has been closed, it will return nullptr as root.
if (!root)
return nullptr;
return FindNodeInSubtree(root, role, name_or_value);
}
void ViewsAXTreeManagerTest::WaitFor(const ui::AXEventGenerator::Event event) {
ASSERT_FALSE(loop_runner_ && loop_runner_->IsRunningOnCurrentThread())
<< "Waiting for multiple events is currently not supported.";
loop_runner_ = std::make_unique<base::RunLoop>();
event_to_wait_for_ = event;
loop_runner_->Run();
}
ui::AXNode* ViewsAXTreeManagerTest::FindNodeInSubtree(
ui::AXNode* root,
const ax::mojom::Role role,
const std::string& name_or_value) const {
EXPECT_NE(nullptr, root);
const std::string& name =
root->GetStringAttribute(ax::mojom::StringAttribute::kName);
const std::string& value =
root->GetStringAttribute(ax::mojom::StringAttribute::kValue);
if (root->GetRole() == role &&
(name == name_or_value || value == name_or_value)) {
return root;
}
for (ui::AXNode* child : root->children()) {
ui::AXNode* result = FindNodeInSubtree(child, role, name_or_value);
if (result)
return result;
}
return nullptr;
}
void ViewsAXTreeManagerTest::OnGeneratedEvent(Widget* widget,
ui::AXEventGenerator::Event event,
ui::AXNodeID node_id) {
ASSERT_NE(nullptr, manager()) << "Should not be called after TearDown().";
if (loop_runner_ && event == event_to_wait_for_)
loop_runner_->Quit();
}
} // namespace
INSTANTIATE_TEST_SUITE_P(All, ViewsAXTreeManagerTest, testing::Bool());
TEST_P(ViewsAXTreeManagerTest, MirrorInitialTree) {
ui::AXNodeData button_data;
button()->GetViewAccessibility().GetAccessibleNodeData(&button_data);
ui::AXNode* ax_button = FindNode(ax::mojom::Role::kButton, "");
ASSERT_NE(nullptr, ax_button);
EXPECT_EQ(button_data.role, ax_button->GetRole());
EXPECT_EQ(
button_data.GetStringAttribute(ax::mojom::StringAttribute::kDescription),
ax_button->GetStringAttribute(ax::mojom::StringAttribute::kDescription));
EXPECT_EQ(
button_data.GetIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb),
ax_button->GetIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb));
EXPECT_TRUE(ax_button->HasState(ax::mojom::State::kFocusable));
}
TEST_P(ViewsAXTreeManagerTest, PerformAction) {
ui::AXNode* ax_button = FindNode(ax::mojom::Role::kButton, "");
ASSERT_NE(nullptr, ax_button);
ASSERT_FALSE(
ax_button->HasIntAttribute(ax::mojom::IntAttribute::kCheckedState));
button()->SetState(TestButton::STATE_PRESSED);
button()->NotifyAccessibilityEvent(ax::mojom::Event::kCheckedStateChanged,
true);
WaitFor(ui::AXEventGenerator::Event::CHECKED_STATE_CHANGED);
}
TEST_P(ViewsAXTreeManagerTest, MultipleTopLevelWidgets) {
// This test is only relevant when IsAccessibilityTreeForViewsEnabled is set,
// as it tests the lifetime management of ViewsAXTreeManager when a Widget is
// closed.
if (!features::IsAccessibilityTreeForViewsEnabled())
return;
UniqueWidgetPtr second_widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
second_widget->Init(std::move(params));
std::unique_ptr<TestButton> second_button = std::make_unique<TestButton>();
second_button->SetSize(gfx::Size(20, 20));
std::unique_ptr<Label> second_label = std::make_unique<Label>();
second_button->AddChildView(second_label.get());
// If the load complete event is fired synchronously from
// |ViewsAXtreeManager|, creating a second widget will inadvertently create
// another ViewsAXTreeManager and hit DCHECK's due to the cache not being
// up to date.
second_widget->GetContentsView()->AddChildView(second_button.get());
second_widget->Show();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/views_ax_tree_manager_unittest.cc | C++ | unknown | 8,933 |
// 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/accessibility/views_utilities_aura.h"
#include "ui/aura/window.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/window_util.h"
namespace views {
aura::Window* GetWindowParentIncludingTransient(aura::Window* window) {
aura::Window* transient_parent = wm::GetTransientParent(window);
if (transient_parent)
return transient_parent;
return window->parent();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/views_utilities_aura.cc | C++ | unknown | 567 |
// 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_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
#define UI_VIEWS_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
namespace aura {
class Window;
}
namespace views {
// Return the parent of |window|, first checking to see if it has a
// transient parent. This allows us to walk up the aura::Window
// hierarchy when it spans multiple window tree hosts, each with
// their own native window.
aura::Window* GetWindowParentIncludingTransient(aura::Window* window);
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/views_utilities_aura.h | C++ | unknown | 686 |
// 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/accessibility/widget_ax_tree_id_map.h"
#include "base/containers/contains.h"
#include "base/no_destructor.h"
namespace views {
WidgetAXTreeIDMap::WidgetAXTreeIDMap() = default;
WidgetAXTreeIDMap::~WidgetAXTreeIDMap() = default;
// static
WidgetAXTreeIDMap& WidgetAXTreeIDMap::GetInstance() {
static base::NoDestructor<WidgetAXTreeIDMap> instance;
return *instance;
}
bool WidgetAXTreeIDMap::HasWidget(Widget* widget) {
return base::Contains(widget_map_, widget);
}
void WidgetAXTreeIDMap::AddWidget(ui::AXTreeID tree_id, Widget* widget) {
DCHECK_NE(tree_id, ui::AXTreeIDUnknown());
DCHECK(widget);
DCHECK(!HasWidget(widget));
widget_map_[widget] = tree_id;
}
void WidgetAXTreeIDMap::RemoveWidget(Widget* widget) {
widget_map_.erase(widget);
}
ui::AXTreeID WidgetAXTreeIDMap::GetWidgetTreeID(Widget* widget) {
DCHECK(widget);
if (!base::Contains(widget_map_, widget))
return ui::AXTreeIDUnknown();
return widget_map_.at(widget);
}
const std::vector<Widget*> WidgetAXTreeIDMap::GetWidgets() const {
std::vector<Widget*> widgets;
widgets.reserve(widget_map_.size());
for (auto iter : widget_map_)
widgets.push_back(iter.first);
return widgets;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/widget_ax_tree_id_map.cc | C++ | unknown | 1,380 |
// 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_ACCESSIBILITY_WIDGET_AX_TREE_ID_MAP_H_
#define UI_VIEWS_ACCESSIBILITY_WIDGET_AX_TREE_ID_MAP_H_
#include <map>
#include <vector>
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/ax_tree_manager.h"
#include "ui/views/views_export.h"
namespace views {
class Widget;
// This class manages mapping between Widgets and their associated AXTreeIDs.
// It is a singleton wrapper around a std::map. Widget pointers are used as the
// key for the map and AXTreeID's are used as the value returned.
class VIEWS_EXPORT WidgetAXTreeIDMap {
public:
WidgetAXTreeIDMap();
~WidgetAXTreeIDMap();
static WidgetAXTreeIDMap& GetInstance();
bool HasWidget(Widget* widget);
void AddWidget(ui::AXTreeID tree_id, Widget* widget);
void RemoveWidget(Widget* widget);
ui::AXTreeID GetWidgetTreeID(views::Widget* widget);
const std::vector<Widget*> GetWidgets() const;
private:
std::map<Widget*, ui::AXTreeID> widget_map_;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_WIDGET_AX_TREE_ID_MAP_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/widget_ax_tree_id_map.h | C++ | unknown | 1,185 |
// 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/accessible_pane_view.h"
#include <memory>
#include "base/memory/raw_ptr.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/views/focus/focus_search.h"
#include "ui/views/view_tracker.h"
#include "ui/views/widget/widget.h"
namespace views {
// Create tiny subclass of FocusSearch that overrides GetParent and Contains,
// delegating these to methods in AccessiblePaneView. This is needed so that
// subclasses of AccessiblePaneView can customize the focus search logic and
// include views that aren't part of the AccessiblePaneView's view
// hierarchy in the focus order.
class AccessiblePaneViewFocusSearch : public FocusSearch {
public:
explicit AccessiblePaneViewFocusSearch(AccessiblePaneView* pane_view)
: FocusSearch(pane_view, true, true), accessible_pane_view_(pane_view) {}
AccessiblePaneViewFocusSearch(const AccessiblePaneViewFocusSearch&) = delete;
AccessiblePaneViewFocusSearch& operator=(
const AccessiblePaneViewFocusSearch&) = delete;
protected:
View* GetParent(View* v) override {
return accessible_pane_view_->ContainsForFocusSearch(root(), v)
? accessible_pane_view_->GetParentForFocusSearch(v)
: nullptr;
}
// Returns true if |v| is contained within the hierarchy rooted at |root|.
// Subclasses can override this if they need custom focus search behavior.
bool Contains(View* root, const View* v) override {
return accessible_pane_view_->ContainsForFocusSearch(root, v);
}
private:
raw_ptr<AccessiblePaneView> accessible_pane_view_;
};
AccessiblePaneView::AccessiblePaneView()
: last_focused_view_tracker_(std::make_unique<ViewTracker>()) {
focus_search_ = std::make_unique<AccessiblePaneViewFocusSearch>(this);
SetAccessibilityProperties(ax::mojom::Role::kPane);
}
AccessiblePaneView::~AccessiblePaneView() {
if (pane_has_focus_) {
RemovePaneFocus();
}
}
bool AccessiblePaneView::SetPaneFocus(views::View* initial_focus) {
if (!GetVisible())
return false;
if (!focus_manager_)
focus_manager_ = GetFocusManager();
View* focused_view = focus_manager_->GetFocusedView();
if (focused_view && !ContainsForFocusSearch(this, focused_view))
last_focused_view_tracker_->SetView(focused_view);
// Use the provided initial focus if it's visible and enabled, otherwise
// use the first focusable child.
if (!initial_focus || !ContainsForFocusSearch(this, initial_focus) ||
!initial_focus->GetVisible() || !initial_focus->GetEnabled()) {
initial_focus = GetFirstFocusableChild();
}
// Return false if there are no focusable children.
if (!initial_focus)
return false;
focus_manager_->SetFocusedView(initial_focus);
// TODO(pbos): Move this behavior into FocusManager. Focusing an unfocusable
// view should do something smart (move focus to its children or clear focus).
// DownloadItemView is an example (isn't focusable, has focusable children).
// See https://crbug.com/1000998.
// The initially-focused view may not be focusable (but one of its children
// might). We may need to advance focus here to make sure focus is on
// something focusable.
focus_manager_->AdvanceFocusIfNecessary();
// If we already have pane focus, we're done.
if (pane_has_focus_)
return true;
// Otherwise, set accelerators and start listening for focus change events.
pane_has_focus_ = true;
ui::AcceleratorManager::HandlerPriority normal =
ui::AcceleratorManager::kNormalPriority;
focus_manager_->RegisterAccelerator(home_key_, normal, this);
focus_manager_->RegisterAccelerator(end_key_, normal, this);
focus_manager_->RegisterAccelerator(escape_key_, normal, this);
focus_manager_->RegisterAccelerator(left_key_, normal, this);
focus_manager_->RegisterAccelerator(right_key_, normal, this);
focus_manager_->AddFocusChangeListener(this);
return true;
}
bool AccessiblePaneView::SetPaneFocusAndFocusDefault() {
return SetPaneFocus(GetDefaultFocusableChild());
}
views::View* AccessiblePaneView::GetDefaultFocusableChild() {
return nullptr;
}
View* AccessiblePaneView::GetParentForFocusSearch(View* v) {
return v->parent();
}
bool AccessiblePaneView::ContainsForFocusSearch(View* root, const View* v) {
return root->Contains(v);
}
void AccessiblePaneView::RemovePaneFocus() {
focus_manager_->RemoveFocusChangeListener(this);
pane_has_focus_ = false;
focus_manager_->UnregisterAccelerator(home_key_, this);
focus_manager_->UnregisterAccelerator(end_key_, this);
focus_manager_->UnregisterAccelerator(escape_key_, this);
focus_manager_->UnregisterAccelerator(left_key_, this);
focus_manager_->UnregisterAccelerator(right_key_, this);
}
views::View* AccessiblePaneView::GetFirstFocusableChild() {
FocusTraversable* dummy_focus_traversable;
views::View* dummy_focus_traversable_view;
return focus_search_->FindNextFocusableView(
nullptr, FocusSearch::SearchDirection::kForwards,
FocusSearch::TraversalDirection::kDown,
FocusSearch::StartingViewPolicy::kSkipStartingView,
FocusSearch::AnchoredDialogPolicy::kCanGoIntoAnchoredDialog,
&dummy_focus_traversable, &dummy_focus_traversable_view);
}
views::View* AccessiblePaneView::GetLastFocusableChild() {
FocusTraversable* dummy_focus_traversable;
views::View* dummy_focus_traversable_view;
return focus_search_->FindNextFocusableView(
this, FocusSearch::SearchDirection::kBackwards,
FocusSearch::TraversalDirection::kDown,
FocusSearch::StartingViewPolicy::kSkipStartingView,
FocusSearch::AnchoredDialogPolicy::kCanGoIntoAnchoredDialog,
&dummy_focus_traversable, &dummy_focus_traversable_view);
}
////////////////////////////////////////////////////////////////////////////////
// View overrides:
views::FocusTraversable* AccessiblePaneView::GetPaneFocusTraversable() {
if (pane_has_focus_)
return this;
else
return nullptr;
}
bool AccessiblePaneView::AcceleratorPressed(
const ui::Accelerator& accelerator) {
views::View* focused_view = focus_manager_->GetFocusedView();
if (!ContainsForFocusSearch(this, focused_view))
return false;
using FocusChangeReason = views::FocusManager::FocusChangeReason;
switch (accelerator.key_code()) {
case ui::VKEY_ESCAPE: {
RemovePaneFocus();
View* last_focused_view = last_focused_view_tracker_->view();
// Ignore |last_focused_view| if it's no longer in the same widget.
if (last_focused_view && GetWidget() != last_focused_view->GetWidget())
last_focused_view = nullptr;
if (last_focused_view) {
focus_manager_->SetFocusedViewWithReason(
last_focused_view, FocusChangeReason::kFocusRestore);
} else if (allow_deactivate_on_esc_) {
focused_view->GetWidget()->Deactivate();
}
return true;
}
case ui::VKEY_LEFT:
focus_manager_->AdvanceFocus(true);
return true;
case ui::VKEY_RIGHT:
focus_manager_->AdvanceFocus(false);
return true;
case ui::VKEY_HOME:
focus_manager_->SetFocusedViewWithReason(
GetFirstFocusableChild(), FocusChangeReason::kFocusTraversal);
return true;
case ui::VKEY_END:
focus_manager_->SetFocusedViewWithReason(
GetLastFocusableChild(), FocusChangeReason::kFocusTraversal);
return true;
default:
return false;
}
}
void AccessiblePaneView::SetVisible(bool flag) {
if (GetVisible() && !flag && pane_has_focus_) {
RemovePaneFocus();
focus_manager_->RestoreFocusedView();
}
View::SetVisible(flag);
}
void AccessiblePaneView::RequestFocus() {
SetPaneFocusAndFocusDefault();
}
////////////////////////////////////////////////////////////////////////////////
// FocusChangeListener overrides:
void AccessiblePaneView::OnWillChangeFocus(views::View* focused_before,
views::View* focused_now) {
// Act when focus has changed.
}
void AccessiblePaneView::OnDidChangeFocus(views::View* focused_before,
views::View* focused_now) {
if (!focused_now)
return;
views::FocusManager::FocusChangeReason reason =
focus_manager_->focus_change_reason();
if (!ContainsForFocusSearch(this, focused_now) ||
reason == views::FocusManager::FocusChangeReason::kDirectFocusChange) {
// We should remove pane focus (i.e. make most of the controls
// not focusable again) because the focus has left the pane,
// or because the focus changed within the pane due to the user
// directly focusing to a specific view (e.g., clicking on it).
RemovePaneFocus();
}
}
////////////////////////////////////////////////////////////////////////////////
// FocusTraversable overrides:
views::FocusSearch* AccessiblePaneView::GetFocusSearch() {
DCHECK(pane_has_focus_);
return focus_search_.get();
}
views::FocusTraversable* AccessiblePaneView::GetFocusTraversableParent() {
DCHECK(pane_has_focus_);
return nullptr;
}
views::View* AccessiblePaneView::GetFocusTraversableParentView() {
DCHECK(pane_has_focus_);
return nullptr;
}
BEGIN_METADATA(AccessiblePaneView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessible_pane_view.cc | C++ | unknown | 9,415 |
// 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_ACCESSIBLE_PANE_VIEW_H_
#define UI_VIEWS_ACCESSIBLE_PANE_VIEW_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
namespace views {
class FocusSearch;
class ViewTracker;
// This class provides keyboard access to any view that extends it, typically
// a toolbar. The user sets focus to a control in this view by pressing
// F6 to traverse all panes, or by pressing a shortcut that jumps directly
// to this pane.
class VIEWS_EXPORT AccessiblePaneView : public View,
public FocusChangeListener,
public FocusTraversable {
public:
METADATA_HEADER(AccessiblePaneView);
AccessiblePaneView();
AccessiblePaneView(const AccessiblePaneView&) = delete;
AccessiblePaneView& operator=(const AccessiblePaneView&) = delete;
~AccessiblePaneView() override;
// Set focus to the pane with complete keyboard access.
// Focus will be restored to the last focused view if the user escapes.
// If |initial_focus| is not NULL, that control will get
// the initial focus, if it's enabled and focusable. Returns true if
// the pane was able to receive focus.
bool SetPaneFocus(View* initial_focus);
bool pane_has_focus() const { return pane_has_focus_; }
// Set focus to the pane with complete keyboard access, with the
// focus initially set to the default child. Focus will be restored
// to the last focused view if the user escapes.
// Returns true if the pane was able to receive focus.
virtual bool SetPaneFocusAndFocusDefault();
// Overridden from View:
FocusTraversable* GetPaneFocusTraversable() override;
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
void SetVisible(bool flag) override;
void RequestFocus() override;
// Overridden from FocusChangeListener:
void OnWillChangeFocus(View* focused_before, View* focused_now) override;
void OnDidChangeFocus(View* focused_before, View* focused_now) override;
// Overridden from FocusTraversable:
FocusSearch* GetFocusSearch() override;
FocusTraversable* GetFocusTraversableParent() override;
View* GetFocusTraversableParentView() override;
// For testing only.
const ui::Accelerator& home_key() const { return home_key_; }
const ui::Accelerator& end_key() const { return end_key_; }
const ui::Accelerator& escape_key() const { return escape_key_; }
const ui::Accelerator& left_key() const { return left_key_; }
const ui::Accelerator& right_key() const { return right_key_; }
protected:
// A subclass can override this to provide a default focusable child
// other than the first focusable child.
virtual View* GetDefaultFocusableChild();
// Returns the parent of |v|. Subclasses can override this if
// they need custom focus search behavior.
View* GetParentForFocusSearch(View* v);
// Returns true if |v| is contained within the hierarchy rooted at |root|
// for the purpose of focus searching. Subclasses can override this if
// they need custom focus search behavior.
bool ContainsForFocusSearch(View* root, const View* v);
// Remove pane focus.
void RemovePaneFocus();
View* GetFirstFocusableChild();
View* GetLastFocusableChild();
FocusManager* focus_manager() const { return focus_manager_; }
// When finishing navigation by pressing ESC, it is allowed to surrender the
// focus to another window if if |allow| is set and no previous view can be
// found.
void set_allow_deactivate_on_esc(bool allow) {
allow_deactivate_on_esc_ = allow;
}
private:
bool pane_has_focus_ = false;
// If true, the panel should be de-activated upon escape when no active view
// is known where to return to.
bool allow_deactivate_on_esc_ = false;
// Save the focus manager rather than calling GetFocusManager(),
// so that we can remove focus listeners in the destructor.
raw_ptr<FocusManager> focus_manager_ = nullptr;
// Our custom focus search implementation that traps focus in this
// pane and traverses all views that are focusable for accessibility,
// not just those that are normally focusable.
std::unique_ptr<FocusSearch> focus_search_;
// Registered accelerators
ui::Accelerator home_key_{ui::VKEY_HOME, ui::EF_NONE};
ui::Accelerator end_key_{ui::VKEY_END, ui::EF_NONE};
ui::Accelerator escape_key_{ui::VKEY_ESCAPE, ui::EF_NONE};
ui::Accelerator left_key_{ui::VKEY_LEFT, ui::EF_NONE};
ui::Accelerator right_key_{ui::VKEY_RIGHT, ui::EF_NONE};
// Holds the last focused view that's not within this pane.
std::unique_ptr<ViewTracker> last_focused_view_tracker_;
friend class AccessiblePaneViewFocusSearch;
base::WeakPtrFactory<AccessiblePaneView> method_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBLE_PANE_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessible_pane_view.h | C++ | unknown | 5,071 |
// 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/accessible_pane_view.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget.h"
namespace views {
// TODO(alicet): bring pane rotation into views and add tests.
// See browser_view.cc for details.
using AccessiblePaneViewTest = ViewsTestBase;
class TestBarView : public AccessiblePaneView {
public:
TestBarView();
TestBarView(const TestBarView&) = delete;
TestBarView& operator=(const TestBarView&) = delete;
~TestBarView() override;
LabelButton* child_button() const { return child_button_; }
LabelButton* second_child_button() const { return second_child_button_; }
LabelButton* third_child_button() const { return third_child_button_; }
LabelButton* not_child_button() const { return not_child_button_.get(); }
View* GetDefaultFocusableChild() override;
private:
void Init();
raw_ptr<LabelButton> child_button_;
raw_ptr<LabelButton> second_child_button_;
raw_ptr<LabelButton> third_child_button_;
std::unique_ptr<LabelButton> not_child_button_;
};
TestBarView::TestBarView() {
Init();
set_allow_deactivate_on_esc(true);
}
TestBarView::~TestBarView() = default;
void TestBarView::Init() {
SetLayoutManager(std::make_unique<FillLayout>());
std::u16string label;
child_button_ = AddChildView(std::make_unique<LabelButton>());
second_child_button_ = AddChildView(std::make_unique<LabelButton>());
third_child_button_ = AddChildView(std::make_unique<LabelButton>());
not_child_button_ = std::make_unique<LabelButton>();
}
View* TestBarView::GetDefaultFocusableChild() {
return child_button_;
}
TEST_F(AccessiblePaneViewTest, SimpleSetPaneFocus) {
TestBarView* test_view = new TestBarView();
std::unique_ptr<Widget> widget(new Widget());
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
root->AddChildView(test_view);
widget->Show();
widget->Activate();
// Set pane focus succeeds, focus on child.
EXPECT_TRUE(test_view->SetPaneFocusAndFocusDefault());
EXPECT_EQ(test_view, test_view->GetPaneFocusTraversable());
EXPECT_EQ(test_view->child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// Set focus on non child view, focus failed, stays on pane.
EXPECT_TRUE(test_view->SetPaneFocus(test_view->not_child_button()));
EXPECT_FALSE(test_view->not_child_button() ==
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
EXPECT_EQ(test_view->child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
widget->CloseNow();
widget.reset();
}
TEST_F(AccessiblePaneViewTest, SetPaneFocusAndRestore) {
View* test_view_main = new View();
std::unique_ptr<Widget> widget_main(new Widget());
Widget::InitParams params_main =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params_main.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params_main.bounds = gfx::Rect(0, 0, 20, 20);
widget_main->Init(std::move(params_main));
View* root_main = widget_main->GetRootView();
root_main->AddChildView(test_view_main);
widget_main->Show();
widget_main->Activate();
test_view_main->GetFocusManager()->SetFocusedView(test_view_main);
EXPECT_TRUE(widget_main->IsActive());
EXPECT_TRUE(test_view_main->HasFocus());
TestBarView* test_view_bar = new TestBarView();
std::unique_ptr<Widget> widget_bar(new Widget());
Widget::InitParams params_bar =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params_bar.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params_bar.bounds = gfx::Rect(50, 50, 650, 650);
widget_bar->Init(std::move(params_bar));
View* root_bar = widget_bar->GetRootView();
root_bar->AddChildView(test_view_bar);
widget_bar->Show();
widget_bar->Activate();
// Set pane focus succeeds, focus on child.
EXPECT_TRUE(test_view_bar->SetPaneFocusAndFocusDefault());
EXPECT_FALSE(test_view_main->HasFocus());
EXPECT_FALSE(widget_main->IsActive());
EXPECT_EQ(test_view_bar, test_view_bar->GetPaneFocusTraversable());
EXPECT_EQ(test_view_bar->child_button(),
test_view_bar->GetWidget()->GetFocusManager()->GetFocusedView());
// Deactivate() is only reliable on Ash. On Windows it uses
// ::GetNextWindow() to simply activate another window, and which one is not
// predictable. On Mac, Deactivate() is not implemented. Note that
// TestBarView calls set_allow_deactivate_on_esc(true), which is only
// otherwise used in Ash.
#if !BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS_ASH)
// Esc should deactivate the widget.
test_view_bar->AcceleratorPressed(test_view_bar->escape_key());
EXPECT_TRUE(widget_main->IsActive());
EXPECT_FALSE(widget_bar->IsActive());
#endif
widget_bar->CloseNow();
widget_bar.reset();
widget_main->CloseNow();
widget_main.reset();
}
TEST_F(AccessiblePaneViewTest, TwoSetPaneFocus) {
TestBarView* test_view = new TestBarView();
TestBarView* test_view_2 = new TestBarView();
std::unique_ptr<Widget> widget(new Widget());
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
root->AddChildView(test_view);
root->AddChildView(test_view_2);
widget->Show();
widget->Activate();
// Set pane focus succeeds, focus on child.
EXPECT_TRUE(test_view->SetPaneFocusAndFocusDefault());
EXPECT_EQ(test_view, test_view->GetPaneFocusTraversable());
EXPECT_EQ(test_view->child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// Set focus on another test_view, focus move to that pane.
EXPECT_TRUE(test_view_2->SetPaneFocus(test_view_2->second_child_button()));
EXPECT_FALSE(test_view->child_button() ==
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
EXPECT_EQ(test_view_2->second_child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
widget->CloseNow();
widget.reset();
}
TEST_F(AccessiblePaneViewTest, PaneFocusTraversal) {
TestBarView* test_view = new TestBarView();
TestBarView* original_test_view = new TestBarView();
std::unique_ptr<Widget> widget(new Widget());
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
root->AddChildView(original_test_view);
root->AddChildView(test_view);
widget->Show();
widget->Activate();
// Set pane focus on first view.
EXPECT_TRUE(original_test_view->SetPaneFocus(
original_test_view->third_child_button()));
// Test traversal in second view.
// Set pane focus on second child.
EXPECT_TRUE(test_view->SetPaneFocus(test_view->second_child_button()));
// home
test_view->AcceleratorPressed(test_view->home_key());
EXPECT_EQ(test_view->child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// end
test_view->AcceleratorPressed(test_view->end_key());
EXPECT_EQ(test_view->third_child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// left
test_view->AcceleratorPressed(test_view->left_key());
EXPECT_EQ(test_view->second_child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// right, right
test_view->AcceleratorPressed(test_view->right_key());
test_view->AcceleratorPressed(test_view->right_key());
EXPECT_EQ(test_view->child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
// ESC
test_view->AcceleratorPressed(test_view->escape_key());
EXPECT_EQ(original_test_view->third_child_button(),
test_view->GetWidget()->GetFocusManager()->GetFocusedView());
widget->CloseNow();
widget.reset();
}
// TODO(crbug.com/1314275): Re-enable this test
#if defined(ADDRESS_SANITIZER) && defined(LEAK_SANITIZER)
#define MAYBE_DoesntCrashOnEscapeWithRemovedView \
DISABLED_DoesntCrashOnEscapeWithRemovedView
#else
#define MAYBE_DoesntCrashOnEscapeWithRemovedView \
DoesntCrashOnEscapeWithRemovedView
#endif
TEST_F(AccessiblePaneViewTest, MAYBE_DoesntCrashOnEscapeWithRemovedView) {
TestBarView* test_view1 = new TestBarView();
TestBarView* test_view2 = new TestBarView();
Widget widget;
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget.Init(std::move(params));
View* root = widget.GetRootView();
root->AddChildView(test_view1);
root->AddChildView(test_view2);
widget.Show();
widget.Activate();
View* v1 = test_view1->child_button();
View* v2 = test_view2->child_button();
// Do the following:
// 1. focus |v1|.
// 2. focus |v2|. This makes |test_view2| remember |v1| as having focus.
// 3. Removes |v1| from it's parent.
// 4. Presses escape on |test_view2|. Escape attempts to revert focus to |v1|
// (because of step 2). Because |v1| is not in a widget this should not
// attempt to focus anything.
EXPECT_TRUE(test_view1->SetPaneFocus(v1));
EXPECT_TRUE(test_view2->SetPaneFocus(v2));
v1->parent()->RemoveChildView(v1);
// This shouldn't hit a CHECK in the FocusManager.
EXPECT_TRUE(test_view2->AcceleratorPressed(test_view2->escape_key()));
}
TEST_F(AccessiblePaneViewTest, AccessibleProperties) {
std::unique_ptr<TestBarView> test_view = std::make_unique<TestBarView>();
test_view->SetAccessibleName(u"Name");
test_view->SetAccessibleDescription(u"Description");
EXPECT_EQ(test_view->GetAccessibleName(), u"Name");
EXPECT_EQ(test_view->GetAccessibleDescription(), u"Description");
EXPECT_EQ(test_view->GetAccessibleRole(), ax::mojom::Role::kPane);
ui::AXNodeData data;
test_view->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
EXPECT_EQ(data.role, ax::mojom::Role::kPane);
data = ui::AXNodeData();
test_view->SetAccessibleRole(ax::mojom::Role::kToolbar);
test_view->GetAccessibleNodeData(&data);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
EXPECT_EQ(data.role, ax::mojom::Role::kToolbar);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessible_pane_view_unittest.cc | C++ | unknown | 11,393 |
// 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/animation_abort_handle.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
namespace views {
AnimationAbortHandle::AnimationAbortHandle(AnimationBuilder::Observer* observer)
: observer_(observer) {
observer_->SetAbortHandle(this);
}
AnimationAbortHandle::~AnimationAbortHandle() {
DCHECK_NE(animation_state_, AnimationState::kNotStarted)
<< "You can't destroy the handle before the animation starts.";
if (observer_)
observer_->SetAbortHandle(nullptr);
if (animation_state_ != AnimationState::kEnded) {
for (ui::Layer* layer : tracked_layers_) {
if (deleted_layers_.find(layer) != deleted_layers_.end())
continue;
layer->GetAnimator()->AbortAllAnimations();
}
}
// Remove the abort handle itself from the alive tracked layers.
for (ui::Layer* layer : tracked_layers_) {
if (deleted_layers_.find(layer) != deleted_layers_.end())
continue;
layer->RemoveObserver(this);
}
}
void AnimationAbortHandle::OnObserverDeleted() {
observer_ = nullptr;
}
void AnimationAbortHandle::AddLayer(ui::Layer* layer) {
// Do not allow to add the layer that was deleted before.
DCHECK(deleted_layers_.find(layer) == deleted_layers_.end());
bool inserted = tracked_layers_.insert(layer).second;
// In case that one layer is added to the abort handle multiple times.
if (inserted)
layer->AddObserver(this);
}
void AnimationAbortHandle::OnAnimationStarted() {
DCHECK_EQ(animation_state_, AnimationState::kNotStarted);
animation_state_ = AnimationState::kRunning;
}
void AnimationAbortHandle::OnAnimationEnded() {
DCHECK_EQ(animation_state_, AnimationState::kRunning);
animation_state_ = AnimationState::kEnded;
}
void AnimationAbortHandle::LayerDestroyed(ui::Layer* layer) {
layer->RemoveObserver(this);
// NOTE: layer deletion may be caused by animation abortion. In addition,
// aborting an animation may lead to multiple layer deletions (for example, a
// animation abort callback could delete multiple views' layers). Therefore
// the destroyed layer should not be removed from `tracked_layers_` directly.
// Otherwise, iterating `tracked_layers_` in the animation abort handle's
// destructor is risky.
bool inserted = deleted_layers_.insert(layer).second;
DCHECK(inserted);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_abort_handle.cc | C++ | unknown | 2,510 |
// 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_ANIMATION_ABORT_HANDLE_H_
#define UI_VIEWS_ANIMATION_ANIMATION_ABORT_HANDLE_H_
#include <set>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "ui/compositor/layer_observer.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
} // namespace ui
namespace views {
// A handle that aborts associated animations on destruction.
// Caveat: ALL properties will be aborted on handle destruction,
// including those not initiated by the builder.
class VIEWS_EXPORT AnimationAbortHandle : public ui::LayerObserver {
public:
~AnimationAbortHandle() override;
void OnObserverDeleted();
private:
friend class AnimationBuilder;
FRIEND_TEST_ALL_PREFIXES(AnimationBuilderTest, AbortHandle);
enum class AnimationState { kNotStarted, kRunning, kEnded };
explicit AnimationAbortHandle(AnimationBuilder::Observer* observer);
// Called when an animation is created for `layer`.
void AddLayer(ui::Layer* layer);
void OnAnimationStarted();
void OnAnimationEnded();
// ui::LayerObserver:
void LayerDestroyed(ui::Layer* layer) override;
AnimationState animation_state() const { return animation_state_; }
raw_ptr<AnimationBuilder::Observer, DanglingUntriaged> observer_;
AnimationState animation_state_ = AnimationState::kNotStarted;
// Stores the layers tracked by the animation abort handle.
std::set<ui::Layer*> tracked_layers_;
// Stores the layers that are deleted during tracking.
std::set<ui::Layer*> deleted_layers_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_ANIMATION_ABORT_HANDLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_abort_handle.h | C++ | unknown | 1,802 |
// 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/animation_builder.h"
#include <algorithm>
#include <tuple>
#include <utility>
#include <vector>
#include "base/check_op.h"
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/no_destructor.h"
#include "base/ranges/algorithm.h"
#include "base/time/time.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/layer_owner.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/views/animation/animation_abort_handle.h"
#include "ui/views/animation/animation_key.h"
#include "ui/views/animation/animation_sequence_block.h"
namespace views {
AnimationBuilder::Observer::Observer() = default;
AnimationBuilder::Observer::~Observer() {
DCHECK(attached_to_sequence_)
<< "You must register callbacks and get abort handle before "
<< "creating a sequence block.";
if (abort_handle_)
abort_handle_->OnObserverDeleted();
base::RepeatingClosure& on_observer_deleted =
AnimationBuilder::GetObserverDeletedCallback();
if (on_observer_deleted)
on_observer_deleted.Run();
}
void AnimationBuilder::Observer::SetOnStarted(base::OnceClosure callback) {
DCHECK(!on_started_);
on_started_ = std::move(callback);
}
void AnimationBuilder::Observer::SetOnEnded(base::OnceClosure callback) {
DCHECK(!on_ended_);
on_ended_ = std::move(callback);
}
void AnimationBuilder::Observer::SetOnWillRepeat(
base::RepeatingClosure callback) {
DCHECK(!on_will_repeat_);
on_will_repeat_ = std::move(callback);
}
void AnimationBuilder::Observer::SetOnAborted(base::OnceClosure callback) {
DCHECK(!on_aborted_);
on_aborted_ = std::move(callback);
}
void AnimationBuilder::Observer::SetOnScheduled(base::OnceClosure callback) {
DCHECK(!on_scheduled_);
on_scheduled_ = std::move(callback);
}
void AnimationBuilder::Observer::OnLayerAnimationStarted(
ui::LayerAnimationSequence* sequence) {
if (abort_handle_ && abort_handle_->animation_state() ==
AnimationAbortHandle::AnimationState::kNotStarted) {
abort_handle_->OnAnimationStarted();
}
if (on_started_)
std::move(on_started_).Run();
}
void AnimationBuilder::Observer::SetAbortHandle(
AnimationAbortHandle* abort_handle) {
abort_handle_ = abort_handle;
}
void AnimationBuilder::Observer::OnLayerAnimationEnded(
ui::LayerAnimationSequence* sequence) {
if (--sequences_to_run_ == 0) {
if (on_ended_)
std::move(on_ended_).Run();
if (abort_handle_ && abort_handle_->animation_state() ==
AnimationAbortHandle::AnimationState::kRunning)
abort_handle_->OnAnimationEnded();
}
}
void AnimationBuilder::Observer::OnLayerAnimationWillRepeat(
ui::LayerAnimationSequence* sequence) {
if (!on_will_repeat_)
return;
// First time through, initialize the repeat_map_ with the sequences.
if (repeat_map_.empty()) {
for (auto* seq : attached_sequences())
repeat_map_[seq] = 0;
}
// Only trigger the repeat callback on the last LayerAnimationSequence on
// which this observer is attached.
const int next_cycle = ++repeat_map_[sequence];
if (base::ranges::none_of(
repeat_map_, [next_cycle](int count) { return count < next_cycle; },
&RepeatMap::value_type::second)) {
on_will_repeat_.Run();
}
}
void AnimationBuilder::Observer::OnLayerAnimationAborted(
ui::LayerAnimationSequence* sequence) {
if (on_aborted_)
std::move(on_aborted_).Run();
if (abort_handle_ && abort_handle_->animation_state() ==
AnimationAbortHandle::AnimationState::kRunning)
abort_handle_->OnAnimationEnded();
}
void AnimationBuilder::Observer::OnLayerAnimationScheduled(
ui::LayerAnimationSequence* sequence) {
if (on_scheduled_)
std::move(on_scheduled_).Run();
}
void AnimationBuilder::Observer::OnAttachedToSequence(
ui::LayerAnimationSequence* sequence) {
ui::LayerAnimationObserver::OnAttachedToSequence(sequence);
attached_to_sequence_ = true;
sequences_to_run_++;
}
void AnimationBuilder::Observer::OnDetachedFromSequence(
ui::LayerAnimationSequence* sequence) {
if (attached_sequences().empty())
delete this;
}
bool AnimationBuilder::Observer::RequiresNotificationWhenAnimatorDestroyed()
const {
return true;
}
struct AnimationBuilder::Value {
base::TimeDelta start;
// Save the original duration because the duration on the element can be a
// scaled version. The scale can potentially be zero.
base::TimeDelta original_duration;
std::unique_ptr<ui::LayerAnimationElement> element;
bool operator<(const Value& key) const {
// Animations with zero duration need to be ordered before animations with
// nonzero of the same start time to prevent the DCHECK from happening in
// TerminateSequence(). These animations don't count as overlapping
// properties.
auto element_properties = element->properties();
auto key_element_properties = key.element->properties();
return std::tie(start, original_duration, element_properties) <
std::tie(key.start, key.original_duration, key_element_properties);
}
};
AnimationBuilder::AnimationBuilder() = default;
AnimationBuilder::AnimationBuilder(AnimationBuilder&& rhs) = default;
AnimationBuilder& AnimationBuilder::operator=(AnimationBuilder&& rhs) = default;
AnimationBuilder::~AnimationBuilder() {
// Terminate `current_sequence_` to complete layer animation configuration.
current_sequence_.reset();
DCHECK(!next_animation_observer_)
<< "Callbacks were scheduled without creating a sequence block "
"afterwards. There are no animations to run these callbacks on.";
// The observer needs to outlive the AnimationBuilder and will manage its own
// lifetime. GetAttachedToSequence should not return false here. This is
// DCHECKed in the observer’s destructor.
if (animation_observer_ && animation_observer_->GetAttachedToSequence())
animation_observer_.release();
for (auto it = layer_animation_sequences_.begin();
it != layer_animation_sequences_.end();) {
auto* const target = it->first;
auto end_it = layer_animation_sequences_.upper_bound(target);
if (abort_handle_)
abort_handle_->AddLayer(target);
ui::ScopedLayerAnimationSettings settings(target->GetAnimator());
if (preemption_strategy_)
settings.SetPreemptionStrategy(preemption_strategy_.value());
std::vector<ui::LayerAnimationSequence*> sequences;
std::transform(it, end_it, std::back_inserter(sequences),
[](auto& it) { return it.second.release(); });
target->GetAnimator()->StartTogether(std::move(sequences));
it = end_it;
}
}
AnimationBuilder& AnimationBuilder::SetPreemptionStrategy(
ui::LayerAnimator::PreemptionStrategy preemption_strategy) {
preemption_strategy_ = preemption_strategy;
return *this;
}
AnimationBuilder& AnimationBuilder::OnStarted(base::OnceClosure callback) {
GetObserver()->SetOnStarted(std::move(callback));
return *this;
}
AnimationBuilder& AnimationBuilder::OnEnded(base::OnceClosure callback) {
GetObserver()->SetOnEnded(std::move(callback));
return *this;
}
AnimationBuilder& AnimationBuilder::OnWillRepeat(
base::RepeatingClosure callback) {
GetObserver()->SetOnWillRepeat(std::move(callback));
return *this;
}
AnimationBuilder& AnimationBuilder::OnAborted(base::OnceClosure callback) {
GetObserver()->SetOnAborted(std::move(callback));
return *this;
}
AnimationBuilder& AnimationBuilder::OnScheduled(base::OnceClosure callback) {
GetObserver()->SetOnScheduled(std::move(callback));
return *this;
}
AnimationSequenceBlock& AnimationBuilder::Once() {
return NewSequence(false);
}
AnimationSequenceBlock& AnimationBuilder::Repeatedly() {
return NewSequence(true);
}
void AnimationBuilder::AddLayerAnimationElement(
base::PassKey<AnimationSequenceBlock>,
AnimationKey key,
base::TimeDelta start,
base::TimeDelta original_duration,
std::unique_ptr<ui::LayerAnimationElement> element) {
auto& values = values_[key];
Value value = {start, original_duration, std::move(element)};
auto it = base::ranges::upper_bound(values, value);
values.insert(it, std::move(value));
}
std::unique_ptr<AnimationSequenceBlock> AnimationBuilder::SwapCurrentSequence(
base::PassKey<AnimationSequenceBlock>,
std::unique_ptr<AnimationSequenceBlock> new_sequence) {
auto old_sequence = std::move(current_sequence_);
current_sequence_ = std::move(new_sequence);
return old_sequence;
}
void AnimationBuilder::BlockEndedAt(base::PassKey<AnimationSequenceBlock>,
base::TimeDelta end) {
end_ = std::max(end_, end);
}
void AnimationBuilder::TerminateSequence(base::PassKey<AnimationSequenceBlock>,
bool repeating) {
for (auto& pair : values_) {
auto sequence = std::make_unique<ui::LayerAnimationSequence>();
sequence->set_is_repeating(repeating);
if (animation_observer_)
sequence->AddObserver(animation_observer_.get());
base::TimeDelta start;
ui::LayerAnimationElement::AnimatableProperties properties =
ui::LayerAnimationElement::UNKNOWN;
for (auto& value : pair.second) {
DCHECK_GE(value.start, start)
<< "Do not overlap animations of the same property on the same view.";
properties = value.element->properties();
if (value.start > start) {
sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement(
properties, value.start - start));
start = value.start;
}
start += value.original_duration;
sequence->AddElement(std::move(value.element));
}
if (start < end_) {
sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement(
properties, end_ - start));
}
layer_animation_sequences_.insert({pair.first.target, std::move(sequence)});
}
values_.clear();
}
AnimationSequenceBlock& AnimationBuilder::GetCurrentSequence() {
DCHECK(current_sequence_);
return *current_sequence_;
}
std::unique_ptr<AnimationAbortHandle> AnimationBuilder::GetAbortHandle() {
DCHECK(!abort_handle_) << "An abort handle is already created.";
abort_handle_ = new AnimationAbortHandle(GetObserver());
return base::WrapUnique(abort_handle_.get());
}
AnimationBuilder::Observer* AnimationBuilder::GetObserver() {
if (!next_animation_observer_)
next_animation_observer_ = std::make_unique<Observer>();
return next_animation_observer_.get();
}
// static
void AnimationBuilder::SetObserverDeletedCallbackForTesting(
base::RepeatingClosure deleted_closure) {
GetObserverDeletedCallback() = std::move(deleted_closure);
}
AnimationSequenceBlock& AnimationBuilder::NewSequence(bool repeating) {
// Each sequence should have its own observer.
// Ensure to terminate the current sequence block before touching the
// animation sequence observer so that the sequence observer is attached to
// the layer animation sequence.
if (current_sequence_)
current_sequence_.reset();
// The observer needs to outlive the AnimationBuilder and will manage its own
// lifetime. GetAttachedToSequence should not return false here. This is
// DCHECKed in the observer’s destructor.
if (animation_observer_ && animation_observer_->GetAttachedToSequence())
animation_observer_.release();
if (next_animation_observer_) {
animation_observer_ = std::move(next_animation_observer_);
next_animation_observer_.reset();
}
end_ = base::TimeDelta();
current_sequence_ = std::make_unique<AnimationSequenceBlock>(
base::PassKey<AnimationBuilder>(), this, base::TimeDelta(), repeating);
return *current_sequence_;
}
// static
base::RepeatingClosure& AnimationBuilder::GetObserverDeletedCallback() {
static base::NoDestructor<base::RepeatingClosure> on_observer_deleted;
return *on_observer_deleted;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_builder.cc | C++ | unknown | 12,284 |
// 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_ANIMATION_BUILDER_H_
#define UI_VIEWS_ANIMATION_ANIMATION_BUILDER_H_
#include <map>
#include <memory>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/layer_animator.h"
#include "ui/views/animation/animation_key.h"
#include "ui/views/animation/animation_sequence_block.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
}
namespace views {
class AnimationAbortHandle;
// Provides an unfinalized animation sequence block if any to build animations.
// Usage notes for callbacks set on AnimationBuilder:
// When setting callbacks for the animations note that the AnimationBuilder’s
// observer that calls these callbacks may outlive the callback's parameters.
// The OnEnded callback runs when all animations created on the AnimationBuilder
// have finished. The OnAborted callback runs when any one animation created on
// the AnimationBuilder has been aborted. Therefore, these callbacks and every
// object the callback accesses needs to outlive all the Layers/LayerOwners
// being animated on since the Layers ultimately own the objects that run the
// animation. Otherwise, developers may need to use weak pointers or force
// animations to be cancelled in the object’s destructor to prevent accessing
// destroyed objects. Note that aborted notifications can be sent during the
// destruction process. Therefore subclasses that own the Layers may actually be
// destroyed before the OnAborted callback is run.
class VIEWS_EXPORT AnimationBuilder {
public:
class Observer : public ui::LayerAnimationObserver {
public:
Observer();
Observer(const Observer&) = delete;
Observer& operator=(const Observer&) = delete;
~Observer() override;
void SetOnStarted(base::OnceClosure callback);
void SetOnEnded(base::OnceClosure callback);
void SetOnWillRepeat(base::RepeatingClosure callback);
void SetOnAborted(base::OnceClosure callback);
void SetOnScheduled(base::OnceClosure callback);
void SetAbortHandle(AnimationAbortHandle* abort_handle);
// ui::LayerAnimationObserver:
void OnLayerAnimationStarted(ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationWillRepeat(
ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationScheduled(
ui::LayerAnimationSequence* sequence) override;
bool GetAttachedToSequence() const { return attached_to_sequence_; }
protected:
void OnAttachedToSequence(ui::LayerAnimationSequence* sequence) override;
void OnDetachedFromSequence(ui::LayerAnimationSequence* sequence) override;
bool RequiresNotificationWhenAnimatorDestroyed() const override;
private:
using RepeatMap = base::flat_map<ui::LayerAnimationSequence*, int>;
RepeatMap repeat_map_;
base::OnceClosure on_started_;
base::OnceClosure on_ended_;
base::RepeatingClosure on_will_repeat_;
base::OnceClosure on_aborted_;
base::OnceClosure on_scheduled_;
bool attached_to_sequence_ = false;
// Incremented when a sequence is attached and decremented when a sequence
// ends. Does not account for aborted sequences. This provides a more
// reliable way of tracking when all sequences have ended since IsFinished
// can return true before a sequence is started if the duration is zero.
int sequences_to_run_ = 0;
raw_ptr<AnimationAbortHandle, DanglingUntriaged> abort_handle_ = nullptr;
};
AnimationBuilder();
AnimationBuilder(AnimationBuilder&& rhs);
AnimationBuilder& operator=(AnimationBuilder&& rhs);
~AnimationBuilder();
// Options for the whole animation
AnimationBuilder& SetPreemptionStrategy(
ui::LayerAnimator::PreemptionStrategy preemption_strategy);
// Registers |callback| to be called when the animation starts.
// Must use before creating a sequence block.
AnimationBuilder& OnStarted(base::OnceClosure callback);
// Registers |callback| to be called when the animation ends. Not called if
// animation is aborted.
// Must use before creating a sequence block.
AnimationBuilder& OnEnded(base::OnceClosure callback);
// Registers |callback| to be called when a sequence repetition ends and will
// repeat. Not called if sequence is aborted.
// Must use before creating a sequence block.
AnimationBuilder& OnWillRepeat(base::RepeatingClosure callback);
// Registers |callback| to be called if animation is aborted for any reason.
// Should never do anything that may cause another animation to be started.
// Must use before creating a sequence block.
AnimationBuilder& OnAborted(base::OnceClosure callback);
// Registers |callback| to be called when the animation is scheduled.
// Must use before creating a sequence block.
AnimationBuilder& OnScheduled(base::OnceClosure callback);
// Returns a handle that can be destroyed later to abort all running
// animations. Must use before creating a sequence block.
// Caveat: ALL properties will be aborted, including those not initiated
// by the builder.
std::unique_ptr<AnimationAbortHandle> GetAbortHandle();
// Creates a new sequence (that optionally repeats).
AnimationSequenceBlock& Once();
AnimationSequenceBlock& Repeatedly();
// Adds an animation element `element` for `key` at `start` to `values`.
void AddLayerAnimationElement(
base::PassKey<AnimationSequenceBlock>,
AnimationKey key,
base::TimeDelta start,
base::TimeDelta original_duration,
std::unique_ptr<ui::LayerAnimationElement> element);
// Swaps `current_sequence_` with `new_sequence` and returns the old one.
[[nodiscard]] std::unique_ptr<AnimationSequenceBlock> SwapCurrentSequence(
base::PassKey<AnimationSequenceBlock>,
std::unique_ptr<AnimationSequenceBlock> new_sequence);
// Called when a block ends. Ensures all animations in the sequence will run
// until at least `end`.
void BlockEndedAt(base::PassKey<AnimationSequenceBlock>, base::TimeDelta end);
// Called when the sequence is ended. Converts `values_` to
// `layer_animation_sequences_`.
void TerminateSequence(base::PassKey<AnimationSequenceBlock>, bool repeating);
// Returns a left value reference to the object held by `current_sequence_`.
// Assumes that `current_sequence_` is set.
// NOTE: be wary when keeping this method's return value because the current
// sequence held by an `AnimationBuilder` instance could be destroyed during
// `AnimationBuilder` instance's life cycle.
AnimationSequenceBlock& GetCurrentSequence();
static void SetObserverDeletedCallbackForTesting(
base::RepeatingClosure deleted_closure);
private:
struct Value;
Observer* GetObserver();
// Resets data for the current sequence as necessary, creates a new sequence
// block and returns the new block's left value reference.
AnimationSequenceBlock& NewSequence(bool repeating);
// Returns a reference to the observer deleted callback used for testing.
static base::RepeatingClosure& GetObserverDeletedCallback();
// Data for all sequences.
std::multimap<ui::Layer*, std::unique_ptr<ui::LayerAnimationSequence>>
layer_animation_sequences_;
std::unique_ptr<Observer> animation_observer_;
// Sets up observer callbacks before .Once() or .Repeatedly() is called to
// start the sequence. next_animation_observer_ is moved to
// animation_observer_ once .Once() or Repeatedly() is called.
std::unique_ptr<Observer> next_animation_observer_;
absl::optional<ui::LayerAnimator::PreemptionStrategy> preemption_strategy_;
// Data for the current sequence.
base::TimeDelta end_;
// Each vector is kept in sorted order.
std::map<AnimationKey, std::vector<Value>> values_;
raw_ptr<AnimationAbortHandle, DanglingUntriaged> abort_handle_ = nullptr;
// An unfinalized sequence block currently used to build animations. NOTE: the
// animation effects carried by `current_sequence_` attach to a layer only
// after `current_sequence_` is destroyed.
// The life cycle of `current_sequence_`:
// (1) The old sequence is replaced by a new one. When being replaced, the
// old sequence is destroyed.
// (2) Gets destroyed when the host `AnimationBuilder` is destroyed.
std::unique_ptr<AnimationSequenceBlock> current_sequence_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_ANIMATION_BUILDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_builder.h | C++ | unknown | 8,915 |
// 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/animation_builder.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/test/gtest_util.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/layer_owner.h"
#include "ui/compositor/property_change_reason.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/test/layer_animator_test_controller.h"
#include "ui/compositor/test/test_layer_animation_delegate.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/interpolated_transform.h"
#include "ui/views/animation/animation_abort_handle.h"
namespace views {
namespace {
class TestAnimatibleLayerOwner : public ui::LayerOwner {
public:
TestAnimatibleLayerOwner() : ui::LayerOwner(std::make_unique<ui::Layer>()) {
layer()->GetAnimator()->set_disable_timer_for_test(true);
layer()->GetAnimator()->SetDelegate(&delegate_);
}
ui::LayerAnimationDelegate* delegate() { return &delegate_; }
private:
ui::TestLayerAnimationDelegate delegate_;
};
// Configures the layer animation on `layer_owner` and returns the builder.
AnimationBuilder BuildLayerOpacityAnimationAndReturnBuilder(
ui::LayerOwner* layer_owner,
const base::TimeDelta& duration) {
EXPECT_NE(0.f, layer_owner->layer()->opacity());
AnimationBuilder builder;
builder.Once().SetDuration(duration).SetOpacity(layer_owner, 0.f);
return builder;
}
} // namespace
class AnimationBuilderTest : public testing::Test {
public:
AnimationBuilderTest() = default;
TestAnimatibleLayerOwner* CreateTestLayerOwner() {
layer_owners_.push_back(std::make_unique<TestAnimatibleLayerOwner>());
animator_controllers_.push_back(
std::make_unique<ui::LayerAnimatorTestController>(
layer_owners_.back()->layer()->GetAnimator()));
return layer_owners_.back().get();
}
void Step(const base::TimeDelta& duration) {
DCHECK_GT(duration, base::TimeDelta());
for (const auto& controller : animator_controllers_) {
controller->StartThreadedAnimationsIfNeeded(
controller->animator()->last_step_time());
controller->Step(duration);
}
elapsed_ += duration;
}
protected:
void SetUp() override {
testing::Test::SetUp();
AnimationBuilder::SetObserverDeletedCallbackForTesting(base::BindRepeating(
[](int* deleted_count) { ++(*deleted_count); }, &deleted_observers_));
}
void TearDown() override {
testing::Test::TearDown();
// Delete the layer owners and animator controllers here to ensure any
// lingering animations are aborted and all the observers are destroyed.
layer_owners_.clear();
animator_controllers_.clear();
AnimationBuilder::SetObserverDeletedCallbackForTesting(
base::NullCallback());
if (expected_observers_deleted_)
EXPECT_EQ(expected_observers_deleted_.value(), deleted_observers_);
}
// Call this function to also ensure any implicitly created observers have
// also been properly cleaned up. One observer is created per
// AnimationSequenceBlock which sets callbacks.
void set_expected_observers_deleted(int expected_observers_deleted) {
expected_observers_deleted_ = expected_observers_deleted;
}
private:
std::vector<std::unique_ptr<TestAnimatibleLayerOwner>> layer_owners_;
std::vector<std::unique_ptr<ui::LayerAnimatorTestController>>
animator_controllers_;
base::TimeDelta elapsed_;
absl::optional<int> expected_observers_deleted_;
int deleted_observers_ = 0;
};
// This test builds two animation sequences and checks that the properties are
// animated in the specified durations.
TEST_F(AnimationBuilderTest, SimpleAnimation) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* first_delegate = first_animating_view->delegate();
ui::LayerAnimationDelegate* second_delegate =
second_animating_view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
constexpr auto kDelay = base::Seconds(3);
{
AnimationBuilder()
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.SetRoundedCorners(first_animating_view, rounded_corners)
.Offset(base::TimeDelta())
.SetDuration(kDelay * 2)
.SetOpacity(second_animating_view, 0.9f);
}
// Original value before the animation steps.
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_FLOAT_EQ(first_delegate->GetOpacityForAnimation(), 1.0);
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
0.0);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 1.0);
Step(kDelay);
EXPECT_FLOAT_EQ(first_delegate->GetOpacityForAnimation(), 0.4f);
// Sanity check one of the corners.
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
// This animation should not be finished yet.
EXPECT_NE(second_delegate->GetOpacityForAnimation(), 0.9f);
Step(kDelay);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.9f);
}
// This test checks that after setting the animation duration scale to be larger
// than 1, animations behave as expected of that scale.
TEST_F(AnimationBuilderTest, ModifiedSlowAnimationDuration) {
ui::ScopedAnimationDurationScaleMode scoped_animation_duration_scale_mode(
ui::ScopedAnimationDurationScaleMode::SLOW_DURATION);
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* first_delegate = first_animating_view->delegate();
ui::LayerAnimationDelegate* second_delegate =
second_animating_view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
constexpr auto kDelay = base::Seconds(3);
{
AnimationBuilder()
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.SetRoundedCorners(first_animating_view, rounded_corners)
.Offset(base::TimeDelta())
.SetDuration(kDelay * 2)
.SetOpacity(second_animating_view, 0.9f)
.Then()
.SetDuration(kDelay)
.Then()
.SetDuration(kDelay)
.SetOpacity(second_animating_view, 0.4f);
}
Step(kDelay * ui::ScopedAnimationDurationScaleMode::SLOW_DURATION);
EXPECT_FLOAT_EQ(first_delegate->GetOpacityForAnimation(), 0.4f);
// Sanity check one of the corners.
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
// This animation should not be finished yet.
EXPECT_NE(second_delegate->GetOpacityForAnimation(), 0.9f);
Step(kDelay * ui::ScopedAnimationDurationScaleMode::SLOW_DURATION);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.9f);
Step(kDelay * 2 * ui::ScopedAnimationDurationScaleMode::SLOW_DURATION);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.4f);
}
// This test checks that after setting the animation duration scale to be
// between 0 and 1, animations behave as expected of that scale.
TEST_F(AnimationBuilderTest, ModifiedFastAnimationDuration) {
ui::ScopedAnimationDurationScaleMode scoped_animation_duration_scale_mode(
ui::ScopedAnimationDurationScaleMode::FAST_DURATION);
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* first_delegate = first_animating_view->delegate();
ui::LayerAnimationDelegate* second_delegate =
second_animating_view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
constexpr auto kDelay = base::Seconds(3);
{
AnimationBuilder()
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.SetRoundedCorners(first_animating_view, rounded_corners)
.Offset(base::TimeDelta())
.SetDuration(kDelay * 2)
.SetOpacity(second_animating_view, 0.9f)
.Then()
.SetDuration(kDelay)
.Then()
.SetDuration(kDelay)
.SetOpacity(second_animating_view, 0.4f);
}
Step(kDelay * ui::ScopedAnimationDurationScaleMode::FAST_DURATION);
EXPECT_FLOAT_EQ(first_delegate->GetOpacityForAnimation(), 0.4f);
// Sanity check one of the corners.
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
// This animation should not be finished yet.
EXPECT_NE(second_delegate->GetOpacityForAnimation(), 0.9f);
Step(kDelay * ui::ScopedAnimationDurationScaleMode::FAST_DURATION);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.9f);
Step(kDelay * 2 * ui::ScopedAnimationDurationScaleMode::FAST_DURATION);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.4f);
}
// This test checks that after setting the animation duration scale to be 0,
// animations behave as expected of that scale.
TEST_F(AnimationBuilderTest, ModifiedZeroAnimationDuration) {
ui::ScopedAnimationDurationScaleMode scoped_animation_duration_scale_mode(
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* first_delegate = first_animating_view->delegate();
ui::LayerAnimationDelegate* second_delegate =
second_animating_view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
constexpr auto kDelay = base::Seconds(3);
{
AnimationBuilder()
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.SetRoundedCorners(first_animating_view, rounded_corners)
.Offset(base::TimeDelta())
.SetDuration(kDelay * 2)
.SetOpacity(second_animating_view, 0.9f)
.Then()
.SetDuration(kDelay)
.Then()
.SetDuration(kDelay)
.SetOpacity(second_animating_view, 0.4f);
}
EXPECT_FLOAT_EQ(first_delegate->GetOpacityForAnimation(), 0.4f);
// Sanity check one of the corners.
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
EXPECT_FLOAT_EQ(second_delegate->GetOpacityForAnimation(), 0.4f);
}
// This test checks that the callback supplied to .OnEnded is not called before
// all sequences have finished running. This test will crash if .OnEnded is
// called prematurely.
TEST_F(AnimationBuilderTest, ModifiedZeroAnimationDurationWithOnEndedCallback) {
ui::ScopedAnimationDurationScaleMode scoped_animation_duration_scale_mode(
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
auto first_animating_view = std::make_unique<TestAnimatibleLayerOwner>();
auto second_animating_view = std::make_unique<TestAnimatibleLayerOwner>();
views::AnimationBuilder b;
b.OnEnded(base::BindRepeating(
[](TestAnimatibleLayerOwner* layer_owner,
TestAnimatibleLayerOwner* second_layer_owner) {
delete layer_owner;
delete second_layer_owner;
},
first_animating_view.get(), second_animating_view.get()))
.Once()
.SetDuration(base::Seconds(3))
.SetOpacity(first_animating_view.get(), 0.4f)
.SetOpacity(second_animating_view.get(), 0.9f);
first_animating_view.release();
second_animating_view.release();
}
TEST_F(AnimationBuilderTest, ZeroDurationBlock) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* first_delegate = first_animating_view->delegate();
gfx::RoundedCornersF first_corners(6.0f, 6.0f, 6.0f, 6.0f);
gfx::RoundedCornersF second_corners(12.0f, 12.0f, 12.0f, 12.0f);
constexpr auto kDelay = base::Seconds(3);
{
AnimationBuilder()
.Once()
.SetDuration(base::TimeDelta())
.SetRoundedCorners(first_animating_view, first_corners)
.Then()
.SetDuration(kDelay)
.SetRoundedCorners(first_animating_view, second_corners)
.Then()
.SetDuration(base::TimeDelta())
.SetRoundedCorners(first_animating_view, first_corners);
}
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
6.0f);
Step(kDelay / 2);
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
9.0f);
Step(kDelay / 2);
EXPECT_FLOAT_EQ(first_delegate->GetRoundedCornersForAnimation().upper_left(),
6.0f);
}
TEST_F(AnimationBuilderTest, CheckTweenType) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
gfx::Tween::Type tween_type = gfx::Tween::EASE_IN;
constexpr auto kDelay = base::Seconds(4);
// Set initial opacity.
first_animating_view->delegate()->SetOpacityFromAnimation(
0.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
constexpr float opacity_end_val = 0.5f;
{
AnimationBuilder().Once().SetDuration(kDelay).SetOpacity(
first_animating_view, opacity_end_val, tween_type);
}
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
Step(kDelay / 2);
// Force an update to the delegate by aborting the animation.
first_animating_view->layer()->GetAnimator()->AbortAllAnimations();
// Values at intermediate steps may not be exact.
EXPECT_NEAR(gfx::Tween::CalculateValue(tween_type, 0.5) * opacity_end_val,
first_animating_view->delegate()->GetOpacityForAnimation(),
0.001f);
}
// Verify that destroying the layers tracked by the animation abort handle
// before the animation ends should not cause any crash.
TEST_F(AnimationBuilderTest, DestroyLayerBeforeAnimationEnd) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
std::unique_ptr<AnimationAbortHandle> abort_handle;
{
AnimationBuilder builder;
abort_handle = builder.GetAbortHandle();
builder.Once()
.SetDuration(base::Seconds(3))
.SetOpacity(first_animating_view, 0.5f)
.SetOpacity(second_animating_view, 0.5f);
}
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating());
first_animating_view->ReleaseLayer();
second_animating_view->ReleaseLayer();
}
// Verify that destroying layers tracked by the animation abort handle when
// the animation ends should not cause any crash.
TEST_F(AnimationBuilderTest, DestroyLayerWhenAnimationEnd) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
auto end_callback = [](TestAnimatibleLayerOwner* first_animating_view,
TestAnimatibleLayerOwner* second_animating_view) {
first_animating_view->ReleaseLayer();
second_animating_view->ReleaseLayer();
};
constexpr auto kDelay = base::Seconds(3);
std::unique_ptr<AnimationAbortHandle> abort_handle;
{
AnimationBuilder builder;
abort_handle = builder.GetAbortHandle();
builder
.OnEnded(base::BindOnce(end_callback, first_animating_view,
second_animating_view))
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.5f)
.SetOpacity(second_animating_view, 0.5f);
}
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating());
Step(kDelay * 2);
// Verify that layers are destroyed when the animation ends.
EXPECT_FALSE(first_animating_view->layer());
EXPECT_FALSE(second_animating_view->layer());
}
// Verify that destroying layers tracked by the animation abort handle when
// the animation is aborted should not cause any crash.
TEST_F(AnimationBuilderTest, DestroyLayerWhenAnimationAborted) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
auto abort_callback = [](TestAnimatibleLayerOwner* first_animating_view,
TestAnimatibleLayerOwner* second_animating_view) {
first_animating_view->ReleaseLayer();
second_animating_view->ReleaseLayer();
};
constexpr auto kDelay = base::Seconds(3);
std::unique_ptr<AnimationAbortHandle> abort_handle;
{
AnimationBuilder builder;
abort_handle = builder.GetAbortHandle();
builder
.OnAborted(base::BindOnce(abort_callback, first_animating_view,
second_animating_view))
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.5f)
.SetOpacity(second_animating_view, 0.5f);
}
Step(0.5 * kDelay);
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating());
// Abort the animation in the half way.
first_animating_view->layer()->GetAnimator()->AbortAllAnimations();
// Verify that layers are destroyed by the animation abortion callback.
EXPECT_FALSE(first_animating_view->layer());
EXPECT_FALSE(second_animating_view->layer());
}
TEST_F(AnimationBuilderTest, CheckStartEndCallbacks) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
constexpr auto kDelay = base::Seconds(3);
bool started = false;
bool ended = false;
{
AnimationBuilder()
.OnStarted(
base::BindOnce([](bool* started) { *started = true; }, &started))
.OnEnded(base::BindOnce([](bool* ended) { *ended = true; }, &ended))
.Once()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.Offset(base::TimeDelta())
.SetDuration(kDelay * 2)
.SetOpacity(second_animating_view, 0.9f)
.Then()
.SetDuration(kDelay)
.SetOpacity(second_animating_view, 0.4f);
}
// Only one Observer should have been created in the above block. Make sure
// it has been cleaned up.
set_expected_observers_deleted(1);
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(started);
Step(kDelay * 2);
EXPECT_FALSE(ended);
Step(kDelay);
EXPECT_TRUE(ended);
}
// This test checks that repeat callbacks are called after each sequence
// repetition and callbacks from one sequence do not affect calls from another
// sequence.
TEST_F(AnimationBuilderTest, CheckOnWillRepeatCallbacks) {
int first_repeat_count = 0;
int second_repeat_count = 0;
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
constexpr auto kDelay = base::Seconds(3);
gfx::RoundedCornersF first_rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
gfx::RoundedCornersF second_rounded_corners(5.0f, 5.0f, 5.0f, 5.0f);
{
AnimationBuilder b;
b.OnWillRepeat(base::BindRepeating([](int& repeat) { repeat = repeat + 1; },
std::ref(first_repeat_count)))
.Repeatedly()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.4f)
.Then()
.SetDuration(kDelay)
.SetOpacity(first_animating_view, 0.9f);
b.OnWillRepeat(base::BindRepeating([](int& repeat) { repeat = repeat + 1; },
std::ref(second_repeat_count)))
.Repeatedly()
.SetDuration(kDelay)
.SetRoundedCorners(first_animating_view, first_rounded_corners)
.Then()
.SetDuration(kDelay)
.SetRoundedCorners(first_animating_view, second_rounded_corners);
}
set_expected_observers_deleted(2);
Step(kDelay * 2);
EXPECT_EQ(first_repeat_count, 1);
EXPECT_EQ(second_repeat_count, 1);
Step(kDelay * 2);
EXPECT_EQ(first_repeat_count, 2);
EXPECT_EQ(second_repeat_count, 2);
}
// We use these notations to illustrate the tested timeline,
// Pause: ---|
// KeyFrame: -->|
// Repeat: [...]
//
// Opacity ---|-->|
TEST_F(AnimationBuilderTest, DelayedStart) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDelay = base::Seconds(1);
constexpr auto kDuration = base::Seconds(1);
{
// clang-format off
AnimationBuilder()
.Once()
.At(kDelay)
.SetDuration(kDuration)
.SetOpacity(view, 0.4f);
// clang-format on
}
Step(kDelay);
// The animation on opacity is not yet started.
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 1.0);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
}
// Opacity -->|-->|
TEST_F(AnimationBuilderTest, TwoKeyFrame) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDuration = base::Seconds(1);
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f);
}
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
}
// Opacity -->|---|-->|
TEST_F(AnimationBuilderTest, PauseInTheMiddle) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDuration = base::Seconds(1);
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.Offset(kDuration)
.SetDuration(kDuration)
.SetOpacity(view, 0.9f);
}
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
}
// Opacity -->|
// RoundedCorners ----->|
TEST_F(AnimationBuilderTest, TwoPropertiesOfDifferentDuration) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
// Make sure that the opacity keyframe finishes at the middle of the rounded
// corners keyframe.
constexpr auto kDurationShort = base::Seconds(1);
constexpr auto kDurationLong = kDurationShort * 2;
{
AnimationBuilder()
.Once()
.SetDuration(kDurationShort)
.SetOpacity(view, 0.4f)
.At(base::TimeDelta())
.SetDuration(kDurationLong)
.SetRoundedCorners(view, rounded_corners);
}
Step(kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 6.0f);
Step(kDurationLong - kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
}
// Opacity ----->|
// RoundedCorners ----->|
TEST_F(AnimationBuilderTest, TwoPropertiesOfDifferentStartTime) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
// Make sure that the opacity keyframe finishes at the middle of the rounded
// corners keyframe.
constexpr auto kDelay = base::Seconds(1);
constexpr auto kDuration = kDelay * 2;
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.At(kDelay)
.SetDuration(kDuration)
.SetRoundedCorners(view, rounded_corners);
}
Step(kDelay);
// Unfortunately, we can't test threaded animations in the midst of a frame
// because they don't update LayerAnimationDelegate in OnProgress().
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 0.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 6.0f);
Step(kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
}
// Opacity ----->|---|-->|
// RoundedCorners ----->|-->|
TEST_F(AnimationBuilderTest, ThenAddsImplicitPause) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners1(12.0f, 12.0f, 12.0f, 12.0f);
gfx::RoundedCornersF rounded_corners2(5.0f, 5.0f, 5.0f, 5.0f);
// Make sure that the first opacity keyframe finishes at the middle of the
// first rounded corners keyframe.
constexpr auto kDelay = base::Seconds(1);
constexpr auto kDuration = kDelay * 2;
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.At(kDelay)
.SetDuration(kDuration)
.SetRoundedCorners(view, rounded_corners1)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f)
.SetRoundedCorners(view, rounded_corners2);
}
Step(kDelay);
// Unfortunately, we can't test threaded animations in the midst of a frame
// because they don't update LayerAnimationDelegate in OnProgress().
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 0.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 6.0f);
Step(kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(),
12.0f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 5.0f);
}
// Opacity [-->|-->]
TEST_F(AnimationBuilderTest, Repeat) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDuration = base::Seconds(1);
{
AnimationBuilder()
.Repeatedly()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f);
}
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
}
// Opacity [-->|-->| ]
TEST_F(AnimationBuilderTest, RepeatWithExplicitTrailingPause) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDuration = base::Seconds(1);
{
AnimationBuilder()
.Repeatedly()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f)
.Then()
.SetDuration(kDuration);
}
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
}
// Opacity [-->|-->]
// RoundedCorners [-->|-->]
TEST_F(AnimationBuilderTest, RepeatTwoProperties) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners1(12.0f, 12.0f, 12.0f, 12.0f);
gfx::RoundedCornersF rounded_corners2(5.0f, 5.0f, 5.0f, 5.0f);
constexpr auto kDuration = base::Seconds(1);
{
AnimationBuilder()
.Repeatedly()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.SetRoundedCorners(view, rounded_corners1)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f)
.SetRoundedCorners(view, rounded_corners2);
}
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 5.0);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 5.0);
}
// Opacity -->|-->|
// RoundedCorners -->|-->|
TEST_F(AnimationBuilderTest, AtCanSkipThenBlock) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners1(12.0f, 12.0f, 12.0f, 12.0f);
gfx::RoundedCornersF rounded_corners2(4.0f, 4.0f, 4.0f, 4.0f);
// Make sure that the first opacity keyframe finishes at the middle of the
// first rounded corners keyframe.
constexpr auto kDelay = base::Seconds(1);
constexpr auto kDuration = kDelay * 2;
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f)
.At(kDelay)
.SetDuration(kDuration)
.SetRoundedCorners(view, rounded_corners1)
.Then()
.SetDuration(kDuration)
.SetRoundedCorners(view, rounded_corners2);
}
Step(kDelay);
// Unfortunately, we can't test threaded animations in the midst of a frame
// because they don't update LayerAnimationDelegate in OnProgress().
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 0.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 6.0);
Step(kDelay);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 8.0);
Step(kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 4.0);
}
// Opacity -->|-->|
// RoundedCorners -->|
TEST_F(AnimationBuilderTest, OffsetCanRewindTime) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
// Make sure that the first opacity keyframe finishes at the middle of the
// first rounded corners keyframe.
constexpr auto kDelay = base::Seconds(1);
constexpr auto kDuration = kDelay * 2;
{
AnimationBuilder()
.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.Then()
.SetDuration(kDuration)
.SetOpacity(view, 0.9f)
.Offset(kDelay - kDuration)
.SetDuration(kDuration)
.SetRoundedCorners(view, rounded_corners);
}
Step(kDelay);
// Unfortunately, we can't test threaded animations in the midst of a frame
// because they don't update LayerAnimationDelegate in OnProgress().
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 0.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 6.0);
Step(kDelay);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDuration - kDelay);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
}
// Opacity [-->|--> ]
// RoundedCorners [-->|---->]
TEST_F(AnimationBuilderTest, RepeatedlyImplicitlyAppendsTrailingPause) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
gfx::RoundedCornersF rounded_corners1(12.0f, 12.0f, 12.0f, 12.0f);
gfx::RoundedCornersF rounded_corners2(4.0f, 4.0f, 4.0f, 4.0f);
// Make sure that the second opacity keyframe finishes at the middle of the
// second rounded corners keyframe.
constexpr auto kDurationShort = base::Seconds(1);
constexpr auto kDurationLong = kDurationShort * 2;
{
AnimationBuilder()
.Repeatedly()
.SetDuration(kDurationShort)
.SetOpacity(view, 0.4f)
.SetRoundedCorners(view, rounded_corners1)
.Then()
.SetDuration(kDurationShort)
.SetOpacity(view, 0.9f)
.Offset(base::TimeDelta())
.SetDuration(kDurationLong)
.SetRoundedCorners(view, rounded_corners2);
}
Step(kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 8.0);
Step(kDurationLong - kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 4.0);
// Repeat
Step(kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.4f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 12.0);
Step(kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 8.0);
Step(kDurationLong - kDurationShort);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.9f);
EXPECT_FLOAT_EQ(delegate->GetRoundedCornersForAnimation().upper_left(), 4.0);
}
// Opacity -->|-->|--> with a loop for setting these blocks.
TEST_F(AnimationBuilderTest, RepeatedBlocks) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kDuration = base::Seconds(1);
constexpr float kOpacity[] = {0.4f, 0.9f, 0.6f};
{
AnimationBuilder builder;
builder.Repeatedly();
for (const auto& opacity : kOpacity) {
builder.GetCurrentSequence()
.SetDuration(kDuration)
.SetOpacity(view, opacity)
.Then();
}
}
for (const auto& opacity : kOpacity) {
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), opacity);
}
}
TEST_F(AnimationBuilderTest, PreemptionStrategyTest) {
using ps = ui::LayerAnimator::PreemptionStrategy;
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
constexpr auto kStepSize = base::Seconds(1);
constexpr auto kDuration = base::Seconds(5);
// Set the initial value to animate.
delegate->SetBrightnessFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
{
AnimationBuilder().Once().SetDuration(kDuration).SetBrightness(view, 0.0f);
}
// The animation hasn't started.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 1.0f);
// Step the animation, but don't complete it.
Step(kStepSize);
// Make sure the animation is progressing.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.8f);
// Make sure we're still animatiing.
EXPECT_TRUE(view->layer()->GetAnimator()->is_animating());
// Now start a new animation to a different target.
{
AnimationBuilder()
.SetPreemptionStrategy(ps::IMMEDIATELY_SET_NEW_TARGET)
.Once()
.SetDuration(
kStepSize) // We only moved previous animation by kStepSize
.SetBrightness(view, 1.0f);
}
Step(kStepSize);
// The above animation should have been aborted, and set the brightness to the
// new target immediately.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 1.0f);
EXPECT_FALSE(view->layer()->GetAnimator()->is_animating());
// Start another animation which we'll preemtp to test another strategy.
{
AnimationBuilder().Once().SetDuration(kDuration).SetBrightness(view, 0.0f);
}
// This should start out like the one above.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 1.0f);
Step(kStepSize);
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.8f);
EXPECT_TRUE(view->layer()->GetAnimator()->is_animating());
{
AnimationBuilder()
.SetPreemptionStrategy(ps::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(kStepSize)
.SetBrightness(view, 1.0f);
}
// The new animation should pick up where the last one left off.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.8f);
Step(kStepSize);
// The new animation is in force if it steps toward the new target.
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 1.0f);
// Make sure the animation is fully complete.
Step(kStepSize);
// The animation should be done now.
EXPECT_FALSE(view->layer()->GetAnimator()->is_animating());
}
TEST_F(AnimationBuilderTest, AbortHandle) {
TestAnimatibleLayerOwner* view = CreateTestLayerOwner();
ui::LayerAnimationDelegate* delegate = view->delegate();
std::unique_ptr<AnimationAbortHandle> abort_handle;
constexpr auto kStepSize = base::Seconds(1);
constexpr auto kDuration = kStepSize * 2;
{
delegate->SetBrightnessFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
delegate->SetOpacityFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
{
AnimationBuilder b;
abort_handle = b.GetAbortHandle();
b.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.At(base::TimeDelta())
.SetDuration(kDuration)
.SetBrightness(view, 0.4f);
}
Step(kStepSize);
// Destroy abort handle should stop all animations.
abort_handle.reset();
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.7f);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.7f);
Step(kStepSize);
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.7f);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.7f);
}
// The builder crashes if the handle is destroyed before animation starts.
{
delegate->SetBrightnessFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
delegate->SetOpacityFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
{
AnimationBuilder b;
abort_handle = b.GetAbortHandle();
b.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.At(base::TimeDelta())
.SetDuration(kDuration)
.SetBrightness(view, 0.4f);
// Early destroy should crash the builder.
EXPECT_DCHECK_DEATH(abort_handle.reset());
}
}
// The handle shouldn't abort animations subsequent to the builder.
{
delegate->SetBrightnessFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
delegate->SetOpacityFromAnimation(
1.0f, ui::PropertyChangeReason::NOT_FROM_ANIMATION);
{
AnimationBuilder b;
abort_handle = b.GetAbortHandle();
b.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.4f)
.At(base::TimeDelta())
.SetDuration(kDuration)
.SetBrightness(view, 0.4f);
}
EXPECT_EQ(abort_handle->animation_state(),
AnimationAbortHandle::AnimationState::kRunning);
// Step to the end of the animation.
Step(kDuration);
EXPECT_EQ(abort_handle->animation_state(),
AnimationAbortHandle::AnimationState::kEnded);
{
AnimationBuilder b;
b.Once()
.SetDuration(kDuration)
.SetOpacity(view, 0.8f)
.At(base::TimeDelta())
.SetDuration(kDuration)
.SetBrightness(view, 0.8f);
}
// Destroy the handle on the finihsed animation shouldn't affect other
// unfinihsed animations.
abort_handle.reset();
Step(kDuration);
EXPECT_FLOAT_EQ(delegate->GetBrightnessForAnimation(), 0.8f);
EXPECT_FLOAT_EQ(delegate->GetOpacityForAnimation(), 0.8f);
}
}
// Verifies that configuring layer animations with an animation builder returned
// from a function works as expected.
TEST_F(AnimationBuilderTest, BuildAnimationWithBuilderFromScope) {
TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner();
TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner();
EXPECT_EQ(1.f, first_animating_view->layer()->opacity());
EXPECT_EQ(1.f, second_animating_view->layer()->opacity());
constexpr auto kDuration = base::Seconds(3);
{
// Build a layer animation on `second_animating_view` with a builder
// returned from a function.
AnimationBuilder builder = BuildLayerOpacityAnimationAndReturnBuilder(
first_animating_view, kDuration);
builder.GetCurrentSequence().SetOpacity(second_animating_view, 0.f);
}
// Verify that both views are under animation.
EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating());
Step(kDuration);
// Verify that after `kDuration` time, both layer animations end. In addition,
// both layers are set with the target opacity.
EXPECT_FALSE(first_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_FALSE(second_animating_view->layer()->GetAnimator()->is_animating());
EXPECT_EQ(0.f, first_animating_view->delegate()->GetOpacityForAnimation());
EXPECT_EQ(0.f, second_animating_view->delegate()->GetOpacityForAnimation());
}
// Verifies that it is disallowed to animate transform using both
// `SetInterpolatedTransform()` and `SetTransform()` in the same block on the
// same target.
TEST_F(AnimationBuilderTest,
DisallowMultipleSameBlockSameTargetTransformPropertyAnimations) {
TestAnimatibleLayerOwner* target = CreateTestLayerOwner();
EXPECT_DCHECK_DEATH_WITH(
AnimationBuilder()
.Once()
.SetInterpolatedTransform(
target, std::make_unique<ui::InterpolatedMatrixTransform>(
/*start_transform=*/gfx::Transform(),
/*end_transform=*/gfx::Transform()))
.SetTransform(target, gfx::Transform()),
"Animate \\(target, property\\) at most once per block.");
}
// Verifies that transform can be animated using `SetInterpolatedTransform()`.
TEST_F(AnimationBuilderTest, SetInterpolatedTransform) {
// Create a nested transform. Note the use of irregular `start_time` and
// `end_time` to verify that out of bounds values are handled.
auto transform = std::make_unique<ui::InterpolatedScale>(
/*start_scale=*/0.f, /*end_scale=*/1.f, /*start_time=*/-1.f,
/*end_time=*/2.f);
transform->SetChild(std::make_unique<ui::InterpolatedRotation>(
/*start_degrees=*/0.f, /*end_degrees=*/360.f, /*start_time=*/0.5f,
/*end_time=*/0.75f));
// Cache expected transforms at key animation points.
const gfx::Transform expected_start_transform = transform->Interpolate(0.f);
const gfx::Transform expected_mid_transform = transform->Interpolate(0.5f);
const gfx::Transform expected_end_transform = transform->Interpolate(1.f);
// Verify initial state.
TestAnimatibleLayerOwner* target = CreateTestLayerOwner();
EXPECT_EQ(target->delegate()->GetTransformForAnimation(), gfx::Transform());
// Start animation.
constexpr auto kDuration = base::Seconds(2);
AnimationBuilder().Once().SetDuration(kDuration).SetInterpolatedTransform(
target, std::move(transform));
// Verify state at animation start.
EXPECT_TRUE(target->layer()->GetAnimator()->is_animating());
EXPECT_EQ(target->delegate()->GetTransformForAnimation(),
expected_start_transform);
// Verify state at animation midpoint.
Step(kDuration / 2);
EXPECT_TRUE(target->layer()->GetAnimator()->is_animating());
EXPECT_EQ(target->delegate()->GetTransformForAnimation(),
expected_mid_transform);
// Verify state at animation end.
Step(kDuration / 2);
EXPECT_FALSE(target->layer()->GetAnimator()->is_animating());
EXPECT_EQ(target->delegate()->GetTransformForAnimation(),
expected_end_transform);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_builder_unittest.cc | C++ | unknown | 45,777 |
// 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/animation/animation_delegate_views.h"
#include <memory>
#include <utility>
#include "ui/gfx/animation/animation_container.h"
#include "ui/views/animation/compositor_animation_runner.h"
#include "ui/views/widget/widget.h"
namespace views {
AnimationDelegateViews::AnimationDelegateViews(View* view) : view_(view) {
if (view)
scoped_observation_.Observe(view);
}
AnimationDelegateViews::~AnimationDelegateViews() {
// Reset the delegate so that we don't attempt to notify our observer from
// the destructor.
if (container_)
container_->set_observer(nullptr);
}
void AnimationDelegateViews::AnimationContainerWasSet(
gfx::AnimationContainer* container) {
if (container_ == container)
return;
if (container_)
container_->set_observer(nullptr);
container_ = container;
container_->set_observer(this);
UpdateAnimationRunner(FROM_HERE);
}
void AnimationDelegateViews::OnViewAddedToWidget(View* observed_view) {
UpdateAnimationRunner(FROM_HERE);
}
void AnimationDelegateViews::OnViewRemovedFromWidget(View* observed_view) {
ClearAnimationRunner();
}
void AnimationDelegateViews::OnViewIsDeleting(View* observed_view) {
DCHECK(scoped_observation_.IsObservingSource(view_.get()));
scoped_observation_.Reset();
view_ = nullptr;
UpdateAnimationRunner(FROM_HERE);
}
void AnimationDelegateViews::AnimationContainerShuttingDown(
gfx::AnimationContainer* container) {
container_ = nullptr;
ClearAnimationRunner();
}
base::TimeDelta AnimationDelegateViews::GetAnimationDurationForReporting()
const {
return base::TimeDelta();
}
void AnimationDelegateViews::UpdateAnimationRunner(
const base::Location& location) {
if (!view_ || !view_->GetWidget() || !view_->GetWidget()->GetCompositor()) {
ClearAnimationRunner();
return;
}
if (!container_ || container_->has_custom_animation_runner())
return;
auto compositor_animation_runner =
std::make_unique<CompositorAnimationRunner>(view_->GetWidget(), location);
compositor_animation_runner_ = compositor_animation_runner.get();
container_->SetAnimationRunner(std::move(compositor_animation_runner));
}
void AnimationDelegateViews::ClearAnimationRunner() {
// `compositor_animation_runner_` holds a pointer owned by `container_`, so
// we need to release it before `container_` actually releases the memory it
// points to.
compositor_animation_runner_ = nullptr;
// TODO(https://crbug.com/960621): make sure the container has a correct
// compositor-assisted runner.
if (container_)
container_->SetAnimationRunner(nullptr);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_delegate_views.cc | C++ | unknown | 2,772 |
// 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_ANIMATION_ANIMATION_DELEGATE_VIEWS_H_
#define UI_VIEWS_ANIMATION_ANIMATION_DELEGATE_VIEWS_H_
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/gfx/animation/animation_container_observer.h"
#include "ui/gfx/animation/animation_delegate.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/views_export.h"
namespace base {
class Location;
}
namespace views {
class CompositorAnimationRunner;
// Provides default implementation to adapt CompositorAnimationRunner for
// Animation. Falls back to the default animation runner when |view| is nullptr.
class VIEWS_EXPORT AnimationDelegateViews
: public gfx::AnimationDelegate,
public ViewObserver,
public gfx::AnimationContainerObserver {
public:
explicit AnimationDelegateViews(View* view);
~AnimationDelegateViews() override;
// gfx::AnimationDelegate:
void AnimationContainerWasSet(gfx::AnimationContainer* container) override;
// ViewObserver:
void OnViewAddedToWidget(View* observed_view) final;
void OnViewRemovedFromWidget(View* observed_view) final;
void OnViewIsDeleting(View* observed_view) final;
// gfx::AnimationContainerObserver:
void AnimationContainerProgressed(
gfx::AnimationContainer* container) override {}
void AnimationContainerEmpty(gfx::AnimationContainer* container) override {}
void AnimationContainerShuttingDown(
gfx::AnimationContainer* container) override;
// Returns the expected animation duration for metrics reporting purposes.
// Should be overriden to provide a non-zero value and used with
// |set_animation_metrics_reporter()|.
virtual base::TimeDelta GetAnimationDurationForReporting() const;
gfx::AnimationContainer* container() { return container_; }
private:
// Sets CompositorAnimationRunner to |container_| if possible. Otherwise,
// clears AnimationRunner of |container_|.
void UpdateAnimationRunner(const base::Location& location);
void ClearAnimationRunner();
raw_ptr<View> view_;
raw_ptr<gfx::AnimationContainer> container_ = nullptr;
// The animation runner that |container_| uses.
raw_ptr<CompositorAnimationRunner> compositor_animation_runner_ = nullptr;
base::ScopedObservation<View, ViewObserver> scoped_observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_ANIMATION_DELEGATE_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_delegate_views.h | C++ | unknown | 2,526 |
// 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_ANIMATION_KEY_H_
#define UI_VIEWS_ANIMATION_ANIMATION_KEY_H_
#include <tuple>
#include "base/memory/raw_ptr.h"
#include "ui/compositor/layer_animation_element.h"
namespace ui {
class Layer;
}
namespace views {
struct AnimationKey {
raw_ptr<ui::Layer> target;
ui::LayerAnimationElement::AnimatableProperty property;
bool operator<(const AnimationKey& key) const {
return std::tie(target, property) < std::tie(key.target, key.property);
}
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_ANIMATION_KEY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_key.h | C++ | unknown | 700 |
// 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/animation_sequence_block.h"
#include <map>
#include <memory>
#include <utility>
#include "base/check.h"
#include "base/functional/callback.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_owner.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/interpolated_transform.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/animation_key.h"
namespace views {
using PassKey = base::PassKey<AnimationSequenceBlock>;
AnimationSequenceBlock::AnimationSequenceBlock(
base::PassKey<AnimationBuilder> builder_key,
AnimationBuilder* owner,
base::TimeDelta start,
bool repeating)
: builder_key_(builder_key),
owner_(owner),
start_(start),
repeating_(repeating) {}
AnimationSequenceBlock::~AnimationSequenceBlock() {
if (!finalized_) {
TerminateBlock();
owner_->TerminateSequence(PassKey(), repeating_);
}
}
AnimationSequenceBlock& AnimationSequenceBlock::SetDuration(
base::TimeDelta duration) {
DCHECK(!finalized_) << "Do not access old blocks after creating new ones.";
DCHECK(!duration_.has_value()) << "Duration may be set at most once.";
duration_ = duration;
return *this;
}
AnimationSequenceBlock& AnimationSequenceBlock::SetBounds(
ui::Layer* target,
const gfx::Rect& bounds,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::BOUNDS},
Element(bounds, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetBounds(
ui::LayerOwner* target,
const gfx::Rect& bounds,
gfx::Tween::Type tween_type) {
return SetBounds(target->layer(), bounds, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetBrightness(
ui::Layer* target,
float brightness,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::BRIGHTNESS},
Element(brightness, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetBrightness(
ui::LayerOwner* target,
float brightness,
gfx::Tween::Type tween_type) {
return SetBrightness(target->layer(), brightness, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetClipRect(
ui::Layer* target,
const gfx::Rect& clip_rect,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::CLIP},
Element(clip_rect, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetClipRect(
ui::LayerOwner* target,
const gfx::Rect& clip_rect,
gfx::Tween::Type tween_type) {
return SetClipRect(target->layer(), clip_rect, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetColor(
ui::Layer* target,
SkColor color,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::COLOR},
Element(color, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetColor(
ui::LayerOwner* target,
SkColor color,
gfx::Tween::Type tween_type) {
return SetColor(target->layer(), color, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetGrayscale(
ui::Layer* target,
float grayscale,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::GRAYSCALE},
Element(grayscale, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetGrayscale(
ui::LayerOwner* target,
float grayscale,
gfx::Tween::Type tween_type) {
return SetGrayscale(target->layer(), grayscale, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetOpacity(
ui::Layer* target,
float opacity,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::OPACITY},
Element(opacity, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetOpacity(
ui::LayerOwner* target,
float opacity,
gfx::Tween::Type tween_type) {
return SetOpacity(target->layer(), opacity, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetTransform(
ui::Layer* target,
gfx::Transform transform,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::TRANSFORM},
Element(std::move(transform), tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetTransform(
ui::LayerOwner* target,
gfx::Transform transform,
gfx::Tween::Type tween_type) {
return SetTransform(target->layer(), std::move(transform), tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetRoundedCorners(
ui::Layer* target,
const gfx::RoundedCornersF& rounded_corners,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::ROUNDED_CORNERS},
Element(rounded_corners, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetRoundedCorners(
ui::LayerOwner* target,
const gfx::RoundedCornersF& rounded_corners,
gfx::Tween::Type tween_type) {
return SetRoundedCorners(target->layer(), rounded_corners, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetGradientMask(
ui::Layer* target,
const gfx::LinearGradient& gradient_mask,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::GRADIENT_MASK},
Element(gradient_mask, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetGradientMask(
ui::LayerOwner* target,
const gfx::LinearGradient& gradient_mask,
gfx::Tween::Type tween_type) {
return SetGradientMask(target->layer(), gradient_mask, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetVisibility(
ui::Layer* target,
bool visible,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::VISIBILITY},
Element(visible, tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetVisibility(
ui::LayerOwner* target,
bool visible,
gfx::Tween::Type tween_type) {
return SetVisibility(target->layer(), visible, tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::SetInterpolatedTransform(
ui::Layer* target,
std::unique_ptr<ui::InterpolatedTransform> interpolated_transform,
gfx::Tween::Type tween_type) {
return AddAnimation({target, ui::LayerAnimationElement::TRANSFORM},
Element(std::move(interpolated_transform), tween_type));
}
AnimationSequenceBlock& AnimationSequenceBlock::SetInterpolatedTransform(
ui::LayerOwner* target,
std::unique_ptr<ui::InterpolatedTransform> interpolated_transform,
gfx::Tween::Type tween_type) {
return SetInterpolatedTransform(
target->layer(), std::move(interpolated_transform), tween_type);
}
AnimationSequenceBlock& AnimationSequenceBlock::At(
base::TimeDelta since_sequence_start) {
// NOTE: at the end of this function, this object is destroyed.
DCHECK(!finalized_) << "Do not access old blocks after creating new ones.";
TerminateBlock();
finalized_ = true;
// NOTE: `old_sequence` is actually the sequence block itself. Do not destruct
// this object until the function end.
auto old_sequence = owner_->SwapCurrentSequence(
PassKey(), std::make_unique<AnimationSequenceBlock>(
builder_key_, owner_, since_sequence_start, repeating_));
return owner_->GetCurrentSequence();
}
AnimationSequenceBlock& AnimationSequenceBlock::Offset(
base::TimeDelta since_last_block_start) {
return At(start_ + since_last_block_start);
}
AnimationSequenceBlock& AnimationSequenceBlock::Then() {
return Offset(duration_.value_or(base::TimeDelta()));
}
AnimationSequenceBlock::Element::Element(AnimationValue animation_value,
gfx::Tween::Type tween_type)
: animation_value_(std::move(animation_value)), tween_type_(tween_type) {}
AnimationSequenceBlock::Element::~Element() = default;
AnimationSequenceBlock::Element::Element(Element&&) = default;
AnimationSequenceBlock::Element& AnimationSequenceBlock::Element::operator=(
Element&&) = default;
AnimationSequenceBlock& AnimationSequenceBlock::AddAnimation(AnimationKey key,
Element element) {
DCHECK(!finalized_) << "Do not access old blocks after creating new ones.";
DCHECK(key.target) << "Animation targets must paint to a layer.";
const auto result =
elements_.insert(std::make_pair(std::move(key), std::move(element)));
DCHECK(result.second) << "Animate (target, property) at most once per block.";
return *this;
}
void AnimationSequenceBlock::TerminateBlock() {
const auto duration = duration_.value_or(base::TimeDelta());
for (auto& pair : elements_) {
std::unique_ptr<ui::LayerAnimationElement> element;
switch (pair.first.property) {
case ui::LayerAnimationElement::TRANSFORM:
if (absl::holds_alternative<std::unique_ptr<ui::InterpolatedTransform>>(
pair.second.animation_value_)) {
element =
ui::LayerAnimationElement::CreateInterpolatedTransformElement(
absl::get<std::unique_ptr<ui::InterpolatedTransform>>(
std::move(pair.second.animation_value_)),
duration);
} else {
DCHECK(absl::holds_alternative<gfx::Transform>(
pair.second.animation_value_));
element = ui::LayerAnimationElement::CreateTransformElement(
absl::get<gfx::Transform>(
std::move(pair.second.animation_value_)),
duration);
}
break;
case ui::LayerAnimationElement::BOUNDS:
element = ui::LayerAnimationElement::CreateBoundsElement(
absl::get<gfx::Rect>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::OPACITY:
element = ui::LayerAnimationElement::CreateOpacityElement(
absl::get<float>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::VISIBILITY:
element = ui::LayerAnimationElement::CreateVisibilityElement(
absl::get<bool>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::BRIGHTNESS:
element = ui::LayerAnimationElement::CreateBrightnessElement(
absl::get<float>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::GRAYSCALE:
element = ui::LayerAnimationElement::CreateGrayscaleElement(
absl::get<float>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::COLOR:
element = ui::LayerAnimationElement::CreateColorElement(
absl::get<SkColor>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::CLIP:
element = ui::LayerAnimationElement::CreateClipRectElement(
absl::get<gfx::Rect>(pair.second.animation_value_), duration);
break;
case ui::LayerAnimationElement::ROUNDED_CORNERS:
element = ui::LayerAnimationElement::CreateRoundedCornersElement(
absl::get<gfx::RoundedCornersF>(pair.second.animation_value_),
duration);
break;
case ui::LayerAnimationElement::GRADIENT_MASK:
element = ui::LayerAnimationElement::CreateGradientMaskElement(
absl::get<gfx::LinearGradient>(pair.second.animation_value_),
duration);
break;
default:
NOTREACHED_NORETURN();
}
element->set_tween_type(pair.second.tween_type_);
owner_->AddLayerAnimationElement(PassKey(), pair.first, start_, duration,
std::move(element));
}
owner_->BlockEndedAt(PassKey(), start_ + duration);
elements_.clear();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_sequence_block.cc | C++ | unknown | 12,415 |
// 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_ANIMATION_SEQUENCE_BLOCK_H_
#define UI_VIEWS_ANIMATION_ANIMATION_SEQUENCE_BLOCK_H_
#include <map>
#include <memory>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/animation_key.h"
#include "ui/views/views_export.h"
namespace gfx {
class Rect;
class RoundedCornersF;
class LinearGradient;
} // namespace gfx
namespace ui {
class InterpolatedTransform;
class Layer;
class LayerOwner;
} // namespace ui
namespace views {
class AnimationBuilder;
// An animation sequence block is a single unit of a larger animation sequence,
// which has a start time, duration, and zero or more (target, property)
// animations. There may be multiple properties animating on a single target,
// and/or multiple targets animating, but the same property on the same target
// may only be animated at most once per block. Animations can be added by
// calling SetXXX(). Calling At(), Offset(), or Then() create a new block.
class VIEWS_EXPORT AnimationSequenceBlock {
public:
AnimationSequenceBlock(base::PassKey<AnimationBuilder> builder_key,
AnimationBuilder* owner,
base::TimeDelta start,
bool repeating);
AnimationSequenceBlock(AnimationSequenceBlock&& other) = delete;
AnimationSequenceBlock& operator=(AnimationSequenceBlock&& other) = delete;
~AnimationSequenceBlock();
// Sets the duration of this block. The duration may be set at most once and
// will be zero if unspecified.
AnimationSequenceBlock& SetDuration(base::TimeDelta duration);
// Adds animation elements to this block. Each (target, property) pair may be
// added at most once.
AnimationSequenceBlock& SetBounds(
ui::Layer* target,
const gfx::Rect& bounds,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetBounds(
ui::LayerOwner* target,
const gfx::Rect& bounds,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetBrightness(
ui::Layer* target,
float brightness,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetBrightness(
ui::LayerOwner* target,
float brightness,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetClipRect(
ui::Layer* target,
const gfx::Rect& clip_rect,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetClipRect(
ui::LayerOwner* target,
const gfx::Rect& clip_rect,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetColor(
ui::Layer* target,
SkColor color,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetColor(
ui::LayerOwner* target,
SkColor color,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetGrayscale(
ui::Layer* target,
float grayscale,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetGrayscale(
ui::LayerOwner* target,
float grayscale,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetOpacity(
ui::Layer* target,
float opacity,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetOpacity(
ui::LayerOwner* target,
float opacity,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetTransform(
ui::Layer* target,
gfx::Transform transform,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetTransform(
ui::LayerOwner* target,
gfx::Transform transform,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetRoundedCorners(
ui::Layer* target,
const gfx::RoundedCornersF& rounded_corners,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetRoundedCorners(
ui::LayerOwner* target,
const gfx::RoundedCornersF& rounded_corners,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetGradientMask(
ui::Layer* target,
const gfx::LinearGradient& gradient_mask,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetGradientMask(
ui::LayerOwner* target,
const gfx::LinearGradient& gradient_mask,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetVisibility(
ui::Layer* target,
bool visible,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetVisibility(
ui::LayerOwner* target,
bool visible,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
// NOTE: Generally an `ui::InterpolatedTransform` animation can be expressed
// more simply as a `gfx::Transform` animation. As such, `SetTransform()` APIs
// are preferred over `SetInterpolatedTransform()` APIs where possible.
//
// Exception #1: It may be preferable to use `SetInterpolatedTransform()` APIs
// to animate overlapping transforms on the same `target`.
//
// Exception #2: It may be preferable to use `SetInterpolatedTransform()` APIs
// when synchronous updates are required, as these APIs dispatch updates at
// each animation step whereas `SetTransform()` APIs dispatch updates only at
// animation start, complete, and abort.
AnimationSequenceBlock& SetInterpolatedTransform(
ui::Layer* target,
std::unique_ptr<ui::InterpolatedTransform> interpolated_transform,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
AnimationSequenceBlock& SetInterpolatedTransform(
ui::LayerOwner* target,
std::unique_ptr<ui::InterpolatedTransform> interpolated_transform,
gfx::Tween::Type tween_type = gfx::Tween::LINEAR);
// Creates a new block.
AnimationSequenceBlock& At(base::TimeDelta since_sequence_start);
AnimationSequenceBlock& Offset(base::TimeDelta since_last_block_start);
AnimationSequenceBlock& Then();
private:
using AnimationValue =
absl::variant<gfx::Rect,
float,
SkColor,
gfx::RoundedCornersF,
gfx::LinearGradient,
bool,
gfx::Transform,
std::unique_ptr<ui::InterpolatedTransform>>;
// Data for the animation of a given AnimationKey.
struct Element {
Element(AnimationValue animation_value, gfx::Tween::Type tween_type);
~Element();
Element(Element&&);
Element& operator=(Element&&);
AnimationValue animation_value_;
gfx::Tween::Type tween_type_;
};
AnimationSequenceBlock& AddAnimation(AnimationKey key, Element element);
// Called when the block is ended by At(), EndSequence(), or a variant
// thereof. Converts `elements_` to LayerAnimationElements on the `owner_`.
void TerminateBlock();
base::PassKey<AnimationBuilder> builder_key_;
raw_ptr<AnimationBuilder> owner_;
base::TimeDelta start_;
// The block duration. This will contain nullopt (interpreted as zero) until
// explicitly set by the caller, at which point it may not be reset.
absl::optional<base::TimeDelta> duration_;
// The animation element data for this block. LayerAnimationElements are not
// used directly because they must be created with a duration, whereas blocks
// support setting the duration after creating elements. The conversion is
// done in TerminateBlock().
std::map<AnimationKey, Element> elements_;
// Is this block part of a repeating sequence?
bool repeating_ = false;
// True when this block has been terminated or used to create another block.
// At this point, it's an error to use the block further.
bool finalized_ = false;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_ANIMATION_SEQUENCE_BLOCK_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/animation_sequence_block.h | C++ | unknown | 8,354 |
// 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/animation/bounds_animator.h"
#include <memory>
#include <utility>
#include "base/containers/contains.h"
#include "base/observer_list.h"
#include "ui/gfx/animation/animation_container.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/geometry/transform_util.h"
#include "ui/views/animation/bounds_animator_observer.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
// This should be after all other #includes.
#if defined(_WINDOWS_) // Detect whether windows.h was included.
#include "base/win/windows_h_disallowed.h"
#endif // defined(_WINDOWS_)
namespace views {
BoundsAnimator::BoundsAnimator(View* parent, bool use_transforms)
: AnimationDelegateViews(parent),
parent_(parent),
use_transforms_(use_transforms),
container_(new gfx::AnimationContainer()) {}
BoundsAnimator::~BoundsAnimator() {
// Delete all the animations, but don't remove any child views. We assume the
// view owns us and is going to be deleted anyway. However, deleting a
// delegate may results in removing a child view, so empty the data_ first so
// that it won't call AnimationCanceled().
ViewToDataMap data;
data.swap(data_);
for (auto& entry : data)
CleanupData(false, &entry.second);
}
void BoundsAnimator::AnimateViewTo(
View* view,
const gfx::Rect& target,
std::unique_ptr<gfx::AnimationDelegate> delegate) {
DCHECK(view);
DCHECK_EQ(view->parent(), parent_);
const bool is_animating = IsAnimating(view);
// Return early if the existing animation on |view| has the same target
// bounds.
if (is_animating && target == data_[view].target_bounds) {
// If this animation specifies a different delegate, swap them out.
if (delegate && delegate != data_[view].delegate)
SetAnimationDelegate(view, std::move(delegate));
return;
}
Data existing_data;
if (is_animating) {
DCHECK(base::Contains(data_, view));
const bool used_transforms = data_[view].target_transform.has_value();
if (used_transforms) {
// Using transforms means a view does not have the proper bounds until an
// animation is complete or canceled. So here we cancel the animation so
// that the bounds can be updated. Note that this means that callers who
// want to set bounds (i.e. View::SetBoundsRect()) directly before calling
// this function will have to explicitly call StopAnimatingView() before
// doing so.
StopAnimatingView(view);
} else {
// Don't immediately delete the animation, that might trigger a callback
// from the animation container.
existing_data = RemoveFromMaps(view);
}
}
// NOTE: we don't check if the view is already at the target location. Doing
// so leads to odd cases where no animations may be present after invoking
// AnimateViewTo. AnimationProgressed does nothing when the bounds of the
// view don't change.
Data& data = data_[view];
data.start_bounds = view->bounds();
data.target_bounds = target;
data.animation = CreateAnimation();
data.delegate = std::move(delegate);
// If the start bounds are empty we cannot derive a transform from start to
// target. Views with existing transforms are not supported. Default back to
// using the bounds update animation in these cases.
// Note that transform is not used if bounds animation requires scaling.
// Because for some views, their children cannot be scaled with the same scale
// factor. For example, ShelfAppButton's size in normal state and dense state
// is 56 and 48 respectively while the size of icon image, the child of
// ShelfAppButton, is 44 and 36 respectively.
if (use_transforms_ && !data.start_bounds.IsEmpty() &&
view->GetTransform().IsIdentity() &&
data.start_bounds.size() == data.target_bounds.size()) {
// Calculate the target transform. Note that we don't reset the transform if
// there already was one, otherwise users will end up with visual bounds
// different than what they set.
// Note that View::SetTransform() does not handle RTL, which is different
// from View::SetBounds(). So mirror the start bounds and target bounds
// manually if necessary.
const gfx::Transform target_transform = gfx::TransformBetweenRects(
gfx::RectF(parent_->GetMirroredRect(data.start_bounds)),
gfx::RectF(parent_->GetMirroredRect(data.target_bounds)));
data.target_transform = target_transform;
}
animation_to_view_[data.animation.get()] = view;
data.animation->Show();
CleanupData(true, &existing_data);
}
void BoundsAnimator::SetTargetBounds(View* view, const gfx::Rect& target) {
const auto i = data_.find(view);
if (i == data_.end())
AnimateViewTo(view, target);
else
i->second.target_bounds = target;
}
gfx::Rect BoundsAnimator::GetTargetBounds(const View* view) const {
const auto i = data_.find(view);
return (i == data_.end()) ? view->bounds() : i->second.target_bounds;
}
const gfx::SlideAnimation* BoundsAnimator::GetAnimationForView(View* view) {
const auto i = data_.find(view);
return (i == data_.end()) ? nullptr : i->second.animation.get();
}
void BoundsAnimator::SetAnimationDelegate(
View* view,
std::unique_ptr<AnimationDelegate> delegate) {
const auto i = data_.find(view);
DCHECK(i != data_.end());
i->second.delegate = std::move(delegate);
}
void BoundsAnimator::StopAnimatingView(View* view) {
const auto i = data_.find(view);
if (i != data_.end())
i->second.animation->Stop();
}
bool BoundsAnimator::IsAnimating(View* view) const {
return data_.find(view) != data_.end();
}
bool BoundsAnimator::IsAnimating() const {
return !data_.empty();
}
void BoundsAnimator::Complete() {
if (data_.empty())
return;
while (!data_.empty())
data_.begin()->second.animation->End();
// Invoke AnimationContainerProgressed to force a repaint and notify delegate.
AnimationContainerProgressed(container_.get());
}
void BoundsAnimator::Cancel() {
if (data_.empty())
return;
while (!data_.empty())
data_.begin()->second.animation->Stop();
// Invoke AnimationContainerProgressed to force a repaint and notify delegate.
AnimationContainerProgressed(container_.get());
}
void BoundsAnimator::SetAnimationDuration(base::TimeDelta duration) {
animation_duration_ = duration;
}
void BoundsAnimator::AddObserver(BoundsAnimatorObserver* observer) {
observers_.AddObserver(observer);
}
void BoundsAnimator::RemoveObserver(BoundsAnimatorObserver* observer) {
observers_.RemoveObserver(observer);
}
std::unique_ptr<gfx::SlideAnimation> BoundsAnimator::CreateAnimation() {
auto animation = std::make_unique<gfx::SlideAnimation>(this);
animation->SetContainer(container_.get());
animation->SetSlideDuration(animation_duration_);
animation->SetTweenType(tween_type_);
return animation;
}
BoundsAnimator::Data::Data() = default;
BoundsAnimator::Data::Data(Data&&) = default;
BoundsAnimator::Data& BoundsAnimator::Data::operator=(Data&&) = default;
BoundsAnimator::Data::~Data() = default;
BoundsAnimator::Data BoundsAnimator::RemoveFromMaps(View* view) {
const auto i = data_.find(view);
DCHECK(i != data_.end());
DCHECK_GT(animation_to_view_.count(i->second.animation.get()), 0u);
Data old_data = std::move(i->second);
data_.erase(view);
animation_to_view_.erase(old_data.animation.get());
return old_data;
}
void BoundsAnimator::CleanupData(bool send_cancel, Data* data) {
if (send_cancel && data->delegate)
data->delegate->AnimationCanceled(data->animation.get());
data->delegate.reset();
if (data->animation) {
data->animation->set_delegate(nullptr);
data->animation.reset();
}
}
std::unique_ptr<gfx::Animation> BoundsAnimator::ResetAnimationForView(
View* view) {
const auto i = data_.find(view);
if (i == data_.end())
return nullptr;
std::unique_ptr<gfx::Animation> old_animation =
std::move(i->second.animation);
animation_to_view_.erase(old_animation.get());
// Reset the delegate so that we don't attempt any processing when the
// animation calls us back.
old_animation->set_delegate(nullptr);
return old_animation;
}
void BoundsAnimator::AnimationEndedOrCanceled(const gfx::Animation* animation,
AnimationEndType type) {
DCHECK(animation_to_view_.find(animation) != animation_to_view_.end());
View* view = animation_to_view_[animation];
DCHECK(view);
// Notify the delegate so it has a chance to paint the final state of a
// completed animation.
if (type == AnimationEndType::kEnded) {
DCHECK_EQ(animation->GetCurrentValue(), 1.0);
AnimationProgressed(animation);
}
// Save the data for later clean up.
Data data = RemoveFromMaps(view);
if (data.target_transform) {
if (type == AnimationEndType::kEnded) {
// Set the bounds at the end of the animation and reset the transform.
view->SetBoundsRect(data.target_bounds);
} else {
DCHECK_EQ(AnimationEndType::kCanceled, type);
// Get the existing transform and apply it to the start bounds which is
// the current bounds of the view. This will place the bounds at the place
// where the animation stopped. See comment in AnimateViewTo() for details
// as to why GetMirroredRect() is used.
const gfx::Transform transform = view->GetTransform();
gfx::Rect bounds = parent_->GetMirroredRect(view->bounds());
bounds = gfx::ToRoundedRect(transform.MapRect(gfx::RectF(bounds)));
view->SetBoundsRect(parent_->GetMirroredRect(bounds));
}
view->SetTransform(gfx::Transform());
}
if (data.delegate) {
if (type == AnimationEndType::kEnded) {
data.delegate->AnimationEnded(animation);
} else {
DCHECK_EQ(AnimationEndType::kCanceled, type);
data.delegate->AnimationCanceled(animation);
}
}
CleanupData(false, &data);
}
void BoundsAnimator::AnimationProgressed(const gfx::Animation* animation) {
DCHECK(animation_to_view_.find(animation) != animation_to_view_.end());
View* view = animation_to_view_[animation];
DCHECK(view);
const Data& data = data_[view];
if (data.target_transform) {
const gfx::Transform current_transform = gfx::Tween::TransformValueBetween(
animation->GetCurrentValue(), gfx::Transform(), *data.target_transform);
view->SetTransform(current_transform);
} else {
gfx::Rect new_bounds =
animation->CurrentValueBetween(data.start_bounds, data.target_bounds);
if (new_bounds != view->bounds()) {
gfx::Rect total_bounds = gfx::UnionRects(new_bounds, view->bounds());
// Build up the region to repaint in repaint_bounds_. We'll do the repaint
// when all animations complete (in AnimationContainerProgressed).
repaint_bounds_.Union(total_bounds);
view->SetBoundsRect(new_bounds);
}
}
if (data.delegate)
data.delegate->AnimationProgressed(animation);
}
void BoundsAnimator::AnimationEnded(const gfx::Animation* animation) {
AnimationEndedOrCanceled(animation, AnimationEndType::kEnded);
}
void BoundsAnimator::AnimationCanceled(const gfx::Animation* animation) {
AnimationEndedOrCanceled(animation, AnimationEndType::kCanceled);
}
void BoundsAnimator::AnimationContainerProgressed(
gfx::AnimationContainer* container) {
if (!repaint_bounds_.IsEmpty()) {
// Adjust for rtl.
repaint_bounds_.set_x(parent_->GetMirroredXWithWidthInView(
repaint_bounds_.x(), repaint_bounds_.width()));
parent_->SchedulePaintInRect(repaint_bounds_);
repaint_bounds_.SetRect(0, 0, 0, 0);
}
for (BoundsAnimatorObserver& observer : observers_)
observer.OnBoundsAnimatorProgressed(this);
if (!IsAnimating()) {
// Notify here rather than from AnimationXXX to avoid deleting the animation
// while the animation is calling us.
for (BoundsAnimatorObserver& observer : observers_)
observer.OnBoundsAnimatorDone(this);
}
}
void BoundsAnimator::AnimationContainerEmpty(
gfx::AnimationContainer* container) {}
void BoundsAnimator::OnChildViewRemoved(views::View* observed_view,
views::View* removed) {
DCHECK_EQ(parent_, observed_view);
const auto iter = data_.find(removed);
if (iter == data_.end())
return;
AnimationCanceled(iter->second.animation.get());
}
base::TimeDelta BoundsAnimator::GetAnimationDurationForReporting() const {
return GetAnimationDuration();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bounds_animator.cc | C++ | unknown | 12,676 |
// 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_ANIMATION_BOUNDS_ANIMATOR_H_
#define UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_H_
#include <map>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/observer_list.h"
#include "ui/gfx/animation/animation_container.h"
#include "ui/gfx/animation/animation_container_observer.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/animation/animation_delegate_views.h"
#include "ui/views/views_export.h"
namespace gfx {
class SlideAnimation;
}
namespace views {
class BoundsAnimatorObserver;
class View;
// Bounds animator is responsible for animating the bounds of a view from the
// the views current location and size to a target position and size. To use
// BoundsAnimator invoke AnimateViewTo for the set of views you want to
// animate.
//
// BoundsAnimator internally creates an animation for each view. If you need
// a specific animation invoke SetAnimationForView after invoking AnimateViewTo.
// You can attach an AnimationDelegate to the individual animation for a view
// by way of SetAnimationDelegate. Additionally you can attach an observer to
// the BoundsAnimator that is notified when all animations are complete.
//
// There is an option to apply transforms on the view instead of repainting and
// relayouting each animation tick. This should be used if the size of the view
// is not changing. It can be considered, but may have funny looking visuals for
// other cases, depending on the content. If layers are not present, they are
// created and destroyed as necessary.
class VIEWS_EXPORT BoundsAnimator : public AnimationDelegateViews {
public:
explicit BoundsAnimator(View* view, bool use_transforms = false);
BoundsAnimator(const BoundsAnimator&) = delete;
BoundsAnimator& operator=(const BoundsAnimator&) = delete;
~BoundsAnimator() override;
// Starts animating |view| from its current bounds to |target|. If there is
// already an animation running for the view it's stopped and a new one
// started. If an AnimationDelegate has been set for |view| it is removed
// (after being notified that the animation was canceled).
void AnimateViewTo(
View* view,
const gfx::Rect& target,
std::unique_ptr<gfx::AnimationDelegate> delegate = nullptr);
// Similar to |AnimateViewTo|, but does not reset the animation, only the
// target bounds. If |view| is not being animated this is the same as
// invoking |AnimateViewTo|.
void SetTargetBounds(View* view, const gfx::Rect& target);
// Returns the target bounds for the specified view. If |view| is not
// animating its current bounds is returned.
gfx::Rect GetTargetBounds(const View* view) const;
// Returns the animation for the specified view. BoundsAnimator owns the
// returned Animation.
const gfx::SlideAnimation* GetAnimationForView(View* view);
// Stops animating the specified view.
void StopAnimatingView(View* view);
// Sets the delegate for the animation for the specified view.
void SetAnimationDelegate(View* view,
std::unique_ptr<gfx::AnimationDelegate> delegate);
// Returns true if BoundsAnimator is animating the bounds of |view|.
bool IsAnimating(View* view) const;
// Returns true if BoundsAnimator is animating any view.
bool IsAnimating() const;
// Finishes all animations, teleporting the views to their target bounds. Any
// views marked for deletion are deleted.
void Complete();
// Cancels all animations, leaving the views at their current location and
// size. Any views marked for deletion are deleted.
void Cancel();
// Overrides default animation duration.
void SetAnimationDuration(base::TimeDelta duration);
// Gets the currently used animation duration.
base::TimeDelta GetAnimationDuration() const { return animation_duration_; }
// Sets the tween type for new animations. Default is EASE_OUT.
void set_tween_type(gfx::Tween::Type type) { tween_type_ = type; }
void AddObserver(BoundsAnimatorObserver* observer);
void RemoveObserver(BoundsAnimatorObserver* observer);
gfx::AnimationContainer* container() { return container_.get(); }
protected:
// Creates the animation to use for animating views.
virtual std::unique_ptr<gfx::SlideAnimation> CreateAnimation();
private:
// Tracks data about the view being animated.
struct Data {
Data();
Data(Data&&);
Data& operator=(Data&&);
~Data();
// The initial bounds.
gfx::Rect start_bounds;
// Target bounds.
gfx::Rect target_bounds;
// The animation.
std::unique_ptr<gfx::SlideAnimation> animation;
// Delegate for the animation, may be nullptr.
std::unique_ptr<gfx::AnimationDelegate> delegate;
// Will only exist if |use_transforms_| is true.
absl::optional<gfx::Transform> target_transform;
};
// Used by AnimationEndedOrCanceled.
enum class AnimationEndType { kEnded, kCanceled };
using ViewToDataMap = std::map<const View*, Data>;
using AnimationToViewMap = std::map<const gfx::Animation*, View*>;
// Removes references to |view| and its animation. Returns the data for the
// caller to handle cleanup.
Data RemoveFromMaps(View* view);
// Does the necessary cleanup for |data|. If |send_cancel| is true and a
// delegate has been installed on |data| AnimationCanceled is invoked on it.
void CleanupData(bool send_cancel, Data* data);
// Used when changing the animation for a view. This resets the maps for
// the animation used by view and returns the current animation. Ownership
// of the returned animation passes to the caller.
std::unique_ptr<gfx::Animation> ResetAnimationForView(View* view);
// Invoked from AnimationEnded and AnimationCanceled.
void AnimationEndedOrCanceled(const gfx::Animation* animation,
AnimationEndType type);
// AnimationDelegateViews overrides.
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
void AnimationContainerProgressed(
gfx::AnimationContainer* container) override;
void AnimationContainerEmpty(gfx::AnimationContainer* container) override;
void OnChildViewRemoved(views::View* observed_view,
views::View* child) override;
base::TimeDelta GetAnimationDurationForReporting() const override;
// Parent of all views being animated.
raw_ptr<View> parent_;
// A more performant version of the bounds animations which updates the
// transform of the views and therefore skips repainting and relayouting until
// the end of the animation. Note that this may not look as good as the
// regular version, depending on the content and the source and destination
// bounds. In the case the provided source bounds is empty, we cannot derive a
// transform so that particular view will still use a bounds animation, even
// with this flag on.
const bool use_transforms_;
base::ObserverList<BoundsAnimatorObserver>::Unchecked observers_;
// All animations we create up with the same container.
scoped_refptr<gfx::AnimationContainer> container_;
// Maps from view being animated to info about the view.
ViewToDataMap data_;
// Maps from animation to view.
AnimationToViewMap animation_to_view_;
// As the animations we create update (AnimationProgressed is invoked) this
// is updated. When all the animations have completed for a given tick of
// the timer (AnimationContainerProgressed is invoked) the parent_ is asked
// to repaint these bounds.
gfx::Rect repaint_bounds_;
base::TimeDelta animation_duration_ = base::Milliseconds(200);
gfx::Tween::Type tween_type_ = gfx::Tween::EASE_OUT;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bounds_animator.h | C++ | unknown | 8,043 |
// 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_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_
#define UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_
#include "ui/views/views_export.h"
namespace views {
class BoundsAnimator;
class VIEWS_EXPORT BoundsAnimatorObserver {
public:
// Invoked when animations have progressed.
virtual void OnBoundsAnimatorProgressed(BoundsAnimator* animator) = 0;
// Invoked when all animations are complete.
virtual void OnBoundsAnimatorDone(BoundsAnimator* animator) = 0;
protected:
virtual ~BoundsAnimatorObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bounds_animator_observer.h | C++ | unknown | 765 |
// 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/animation/bounds_animator.h"
#include <algorithm>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/icu_test_util.h"
#include "base/test/task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/animation/test_animation_delegate.h"
#include "ui/views/view.h"
using gfx::Animation;
using gfx::SlideAnimation;
using gfx::TestAnimationDelegate;
namespace views {
namespace {
class OwnedDelegate : public gfx::AnimationDelegate {
public:
OwnedDelegate() = default;
OwnedDelegate(const OwnedDelegate&) = delete;
OwnedDelegate& operator=(const OwnedDelegate&) = delete;
~OwnedDelegate() override { deleted_ = true; }
static bool GetAndClearDeleted() {
bool value = deleted_;
deleted_ = false;
return value;
}
static bool GetAndClearCanceled() {
bool value = canceled_;
canceled_ = false;
return value;
}
// Overridden from gfx::AnimationDelegate:
void AnimationCanceled(const Animation* animation) override {
canceled_ = true;
}
private:
static bool deleted_;
static bool canceled_;
};
// static
bool OwnedDelegate::deleted_ = false;
bool OwnedDelegate::canceled_ = false;
class TestView : public View {
public:
TestView() = default;
TestView(const TestView&) = delete;
TestView& operator=(const TestView&) = delete;
void OnDidSchedulePaint(const gfx::Rect& r) override {
++repaint_count_;
if (dirty_rect_.IsEmpty())
dirty_rect_ = r;
else
dirty_rect_.Union(r);
}
const gfx::Rect& dirty_rect() const { return dirty_rect_; }
void set_repaint_count(int val) { repaint_count_ = val; }
int repaint_count() const { return repaint_count_; }
private:
gfx::Rect dirty_rect_;
int repaint_count_ = 0;
};
class RTLAnimationTestDelegate : public gfx::AnimationDelegate {
public:
RTLAnimationTestDelegate(const gfx::Rect& start,
const gfx::Rect& target,
View* view,
base::RepeatingClosure quit_closure)
: start_(start),
target_(target),
view_(view),
quit_closure_(std::move(quit_closure)) {}
~RTLAnimationTestDelegate() override = default;
private:
// gfx::AnimationDelegate:
void AnimationProgressed(const Animation* animation) override {
gfx::Transform transform = view_->GetTransform();
ASSERT_TRUE(!transform.IsIdentity());
// In this test, assume that |parent| is root view.
View* parent = view_->parent();
const gfx::Rect start_rect_in_screen = parent->GetMirroredRect(start_);
const gfx::Rect target_rect_in_screen = parent->GetMirroredRect(target_);
gfx::Rect current_bounds_in_screen =
transform.MapRect(parent->GetMirroredRect(view_->bounds()));
// Verify that |view_|'s current bounds in screen are valid.
EXPECT_GE(current_bounds_in_screen.x(),
std::min(start_rect_in_screen.x(), target_rect_in_screen.x()));
EXPECT_LE(
current_bounds_in_screen.right(),
std::max(start_rect_in_screen.right(), target_rect_in_screen.right()));
quit_closure_.Run();
}
// Animation initial bounds.
gfx::Rect start_;
// Animation target bounds.
gfx::Rect target_;
// view to be animated.
raw_ptr<View> view_;
base::RepeatingClosure quit_closure_;
};
} // namespace
class BoundsAnimatorTest : public testing::Test {
public:
BoundsAnimatorTest()
: task_environment_(
base::test::TaskEnvironment::TimeSource::MOCK_TIME,
base::test::SingleThreadTaskEnvironment::MainThreadType::UI),
child_(new TestView()) {
parent_.AddChildView(child_.get());
RecreateAnimator(/*use_transforms=*/false);
}
BoundsAnimatorTest(const BoundsAnimatorTest&) = delete;
BoundsAnimatorTest& operator=(const BoundsAnimatorTest&) = delete;
TestView* parent() { return &parent_; }
TestView* child() { return child_; }
BoundsAnimator* animator() { return animator_.get(); }
protected:
void RecreateAnimator(bool use_transforms) {
animator_ = std::make_unique<BoundsAnimator>(&parent_, use_transforms);
animator_->SetAnimationDuration(base::Milliseconds(10));
}
// Animates |child_| to |target_bounds|. Returns the repaint time.
// |use_long_duration| indicates whether long or short bounds animation is
// created.
int GetRepaintTimeFromBoundsAnimation(const gfx::Rect& target_bounds,
bool use_long_duration) {
child()->set_repaint_count(0);
const base::TimeDelta animation_duration =
base::Milliseconds(use_long_duration ? 2000 : 10);
animator()->SetAnimationDuration(animation_duration);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(),
std::make_unique<TestAnimationDelegate>());
// The animator should be animating now.
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Run the message loop; the delegate exits the loop when the animation is
// done.
if (use_long_duration)
task_environment_.FastForwardBy(animation_duration);
base::RunLoop().Run();
// Make sure the bounds match of the view that was animated match and the
// layer is destroyed.
EXPECT_EQ(target_bounds, child()->bounds());
EXPECT_FALSE(child()->layer());
// |child| shouldn't be animating anymore.
EXPECT_FALSE(animator()->IsAnimating(child()));
return child()->repaint_count();
}
base::test::SingleThreadTaskEnvironment task_environment_;
private:
TestView parent_;
raw_ptr<TestView> child_; // Owned by |parent_|.
std::unique_ptr<BoundsAnimator> animator_;
};
// Checks animate view to.
TEST_F(BoundsAnimatorTest, AnimateViewTo) {
gfx::Rect initial_bounds(0, 0, 10, 10);
child()->SetBoundsRect(initial_bounds);
gfx::Rect target_bounds(10, 10, 20, 20);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(),
std::make_unique<TestAnimationDelegate>());
// The animator should be animating now.
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Run the message loop; the delegate exits the loop when the animation is
// done.
base::RunLoop().Run();
// Make sure the bounds match of the view that was animated match.
EXPECT_EQ(target_bounds, child()->bounds());
// |child| shouldn't be animating anymore.
EXPECT_FALSE(animator()->IsAnimating(child()));
// The parent should have been told to repaint as the animation progressed.
// The resulting rect is the union of the original and target bounds.
EXPECT_EQ(gfx::UnionRects(target_bounds, initial_bounds),
parent()->dirty_rect());
}
// Make sure that removing/deleting a child view while animating stops the
// view's animation and will not result in a crash.
TEST_F(BoundsAnimatorTest, DeleteWhileAnimating) {
animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10));
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Make sure that animation is removed upon deletion.
delete child();
EXPECT_FALSE(animator()->GetAnimationForView(child()));
EXPECT_FALSE(animator()->IsAnimating(child()));
}
// Make sure an AnimationDelegate is deleted when canceled.
TEST_F(BoundsAnimatorTest, DeleteDelegateOnCancel) {
animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10));
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
animator()->Cancel();
// The animator should no longer be animating.
EXPECT_FALSE(animator()->IsAnimating());
EXPECT_FALSE(animator()->IsAnimating(child()));
// The cancel should both cancel the delegate and delete it.
EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled());
EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted());
}
// Make sure that the AnimationDelegate of the running animation is deleted when
// a new animation is scheduled.
TEST_F(BoundsAnimatorTest, DeleteDelegateOnNewAnimate) {
const gfx::Rect target_bounds_first(0, 0, 10, 10);
animator()->AnimateViewTo(child(), target_bounds_first);
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
// Start an animation on the same view with different target bounds.
const gfx::Rect target_bounds_second(0, 5, 10, 10);
animator()->AnimateViewTo(child(), target_bounds_second);
// Starting a new animation should both cancel the delegate and delete it.
EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted());
EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled());
}
// Make sure that the duplicate animation request does not interrupt the running
// animation.
TEST_F(BoundsAnimatorTest, HandleDuplicateAnimation) {
const gfx::Rect target_bounds(0, 0, 10, 10);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
// Request the animation with the same view/target bounds.
animator()->AnimateViewTo(child(), target_bounds);
// Verify that the existing animation is not interrupted.
EXPECT_FALSE(OwnedDelegate::GetAndClearDeleted());
EXPECT_FALSE(OwnedDelegate::GetAndClearCanceled());
}
// Make sure that a duplicate animation request that specifies a different
// delegate swaps out that delegate.
TEST_F(BoundsAnimatorTest, DuplicateAnimationsCanReplaceDelegate) {
const gfx::Rect target_bounds(0, 0, 10, 10);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
// Request the animation with the same view/target bounds but a different
// delegate.
animator()->AnimateViewTo(child(), target_bounds,
std::make_unique<OwnedDelegate>());
// Verify that the delegate was replaced.
EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted());
// The animation still should not have been canceled.
EXPECT_FALSE(OwnedDelegate::GetAndClearCanceled());
}
// Makes sure StopAnimating works.
TEST_F(BoundsAnimatorTest, StopAnimating) {
std::unique_ptr<OwnedDelegate> delegate(std::make_unique<OwnedDelegate>());
animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10));
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
animator()->StopAnimatingView(child());
// Shouldn't be animating now.
EXPECT_FALSE(animator()->IsAnimating());
EXPECT_FALSE(animator()->IsAnimating(child()));
// Stopping should both cancel the delegate and delete it.
EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted());
EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled());
}
// Make sure Complete completes in-progress animations.
TEST_F(BoundsAnimatorTest, CompleteAnimation) {
std::unique_ptr<OwnedDelegate> delegate(std::make_unique<OwnedDelegate>());
const gfx::Rect target_bounds = gfx::Rect(0, 0, 10, 10);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(), std::make_unique<OwnedDelegate>());
animator()->Complete();
// Shouldn't be animating now.
EXPECT_FALSE(animator()->IsAnimating());
EXPECT_FALSE(animator()->IsAnimating(child()));
// Child should have been moved to the animation's target.
EXPECT_EQ(target_bounds, child()->bounds());
// Completing should delete the delegate.
EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted());
EXPECT_FALSE(OwnedDelegate::GetAndClearCanceled());
}
// Verify that transform is used when the animation target bounds have the
// same size with the current bounds' meanwhile having the transform option
// enabled.
TEST_F(BoundsAnimatorTest, UseTransformsAnimateViewTo) {
RecreateAnimator(/*use_transforms=*/true);
const gfx::Rect initial_bounds(0, 0, 10, 10);
child()->SetBoundsRect(initial_bounds);
// Ensure that the target bounds have the same size with the initial bounds'
// to apply transform to bounds animation.
const gfx::Rect target_bounds_without_resize(gfx::Point(10, 10),
initial_bounds.size());
const int repaint_time_from_short_animation =
GetRepaintTimeFromBoundsAnimation(target_bounds_without_resize,
/*use_long_duration=*/false);
const int repaint_time_from_long_animation =
GetRepaintTimeFromBoundsAnimation(initial_bounds,
/*use_long_duration=*/true);
// The number of repaints in long animation should be the same as with the
// short animation.
EXPECT_EQ(repaint_time_from_short_animation,
repaint_time_from_long_animation);
}
// Verify that transform is not used when the animation target bounds have the
// different size from the current bounds' even if transform is preferred.
TEST_F(BoundsAnimatorTest, NoTransformForScalingAnimation) {
RecreateAnimator(/*use_transforms=*/true);
const gfx::Rect initial_bounds(0, 0, 10, 10);
child()->SetBoundsRect(initial_bounds);
// Ensure that the target bounds have the different size with the initial
// bounds' to repaint bounds in each animation tick.
const gfx::Rect target_bounds_with_reize(gfx::Point(10, 10),
gfx::Size(20, 20));
const int repaint_time_from_short_animation =
GetRepaintTimeFromBoundsAnimation(target_bounds_with_reize,
/*use_long_duration=*/false);
const int repaint_time_from_long_animation =
GetRepaintTimeFromBoundsAnimation(initial_bounds,
/*use_long_duration=*/true);
// When creating bounds animation with repaint, the longer bounds animation
// should have more repaint counts.
EXPECT_GT(repaint_time_from_long_animation,
repaint_time_from_short_animation);
}
// Tests that the transforms option does not crash when a view's bounds start
// off empty.
TEST_F(BoundsAnimatorTest, UseTransformsAnimateViewToEmptySrc) {
RecreateAnimator(/*use_transforms=*/true);
gfx::Rect initial_bounds(0, 0, 0, 0);
child()->SetBoundsRect(initial_bounds);
gfx::Rect target_bounds(10, 10, 20, 20);
child()->set_repaint_count(0);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(),
std::make_unique<TestAnimationDelegate>());
// The animator should be animating now.
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Run the message loop; the delegate exits the loop when the animation is
// done.
base::RunLoop().Run();
EXPECT_EQ(target_bounds, child()->bounds());
}
// Tests that when using the transform option on the bounds animator, cancelling
// the animation part way results in the correct bounds applied.
TEST_F(BoundsAnimatorTest, UseTransformsCancelAnimation) {
RecreateAnimator(/*use_transforms=*/true);
// Ensure that |initial_bounds| has the same size with |target_bounds| to
// create bounds animation via the transform.
const gfx::Rect initial_bounds(0, 0, 10, 10);
const gfx::Rect target_bounds(10, 10, 10, 10);
child()->SetBoundsRect(initial_bounds);
const base::TimeDelta duration = base::Milliseconds(200);
animator()->SetAnimationDuration(duration);
// Use a linear tween so we can estimate the expected bounds.
animator()->set_tween_type(gfx::Tween::LINEAR);
animator()->AnimateViewTo(child(), target_bounds);
animator()->SetAnimationDelegate(child(),
std::make_unique<TestAnimationDelegate>());
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Stop halfway and cancel. The child should have its bounds updated to
// exactly halfway between |initial_bounds| and |target_bounds|.
const gfx::Rect expected_bounds(5, 5, 10, 10);
task_environment_.FastForwardBy(base::Milliseconds(100));
EXPECT_EQ(initial_bounds, child()->bounds());
animator()->Cancel();
EXPECT_EQ(expected_bounds, child()->bounds());
}
// Test that when using the transform option on the bounds animator, cancelling
// the animation part way under RTL results in the correct bounds applied.
TEST_F(BoundsAnimatorTest, UseTransformsCancelAnimationRTL) {
// Enable RTL.
base::test::ScopedRestoreICUDefaultLocale scoped_locale("he");
RecreateAnimator(/*use_transforms=*/true);
// Ensure that |initial_bounds| has the same size with |target_bounds| to
// create bounds animation via the transform.
const gfx::Rect initial_bounds(0, 0, 10, 10);
const gfx::Rect target_bounds(10, 10, 10, 10);
child()->SetBoundsRect(initial_bounds);
const base::TimeDelta duration = base::Milliseconds(200);
animator()->SetAnimationDuration(duration);
// Use a linear tween so we can estimate the expected bounds.
animator()->set_tween_type(gfx::Tween::LINEAR);
animator()->AnimateViewTo(child(), target_bounds);
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
// Stop halfway and cancel. The child should have its bounds updated to
// exactly halfway between |initial_bounds| and |target_bounds|.
const gfx::Rect expected_bounds(5, 5, 10, 10);
task_environment_.FastForwardBy(base::Milliseconds(100));
EXPECT_EQ(initial_bounds, child()->bounds());
animator()->Cancel();
EXPECT_EQ(expected_bounds, child()->bounds());
}
// Verify that the bounds animation which updates the transform of views work
// as expected under RTL (https://crbug.com/1067033).
TEST_F(BoundsAnimatorTest, VerifyBoundsAnimatorUnderRTL) {
// Enable RTL.
base::test::ScopedRestoreICUDefaultLocale scoped_locale("he");
RecreateAnimator(/*use_transforms=*/true);
parent()->SetBounds(0, 0, 40, 40);
const gfx::Rect initial_bounds(0, 0, 10, 10);
child()->SetBoundsRect(initial_bounds);
const gfx::Rect target_bounds(10, 10, 10, 10);
const base::TimeDelta animation_duration = base::Milliseconds(10);
animator()->SetAnimationDuration(animation_duration);
child()->set_repaint_count(0);
animator()->AnimateViewTo(child(), target_bounds);
base::RunLoop run_loop;
animator()->SetAnimationDelegate(
child(),
std::make_unique<RTLAnimationTestDelegate>(
initial_bounds, target_bounds, child(), run_loop.QuitClosure()));
// The animator should be animating now.
EXPECT_TRUE(animator()->IsAnimating());
EXPECT_TRUE(animator()->IsAnimating(child()));
run_loop.Run();
EXPECT_FALSE(animator()->IsAnimating(child()));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bounds_animator_unittest.cc | C++ | unknown | 18,836 |
// 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/bubble_slide_animator.h"
#include "base/time/time.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
namespace views {
BubbleSlideAnimator::BubbleSlideAnimator(
BubbleDialogDelegateView* bubble_delegate)
: AnimationDelegateViews(bubble_delegate),
bubble_delegate_(bubble_delegate) {
Widget* widget = bubble_delegate->GetWidget();
DCHECK(widget);
widget_observation_.Observe(widget);
constexpr base::TimeDelta kDefaultBubbleSlideAnimationTime =
base::Milliseconds(200);
slide_animation_.SetDuration(kDefaultBubbleSlideAnimationTime);
}
BubbleSlideAnimator::~BubbleSlideAnimator() = default;
void BubbleSlideAnimator::SetSlideDuration(base::TimeDelta duration) {
slide_animation_.SetDuration(duration);
}
void BubbleSlideAnimator::AnimateToAnchorView(View* desired_anchor_view) {
desired_anchor_view_ = desired_anchor_view;
starting_bubble_bounds_ =
bubble_delegate_->GetWidget()->GetWindowBoundsInScreen();
target_bubble_bounds_ = CalculateTargetBounds(desired_anchor_view);
slide_animation_.SetCurrentValue(0);
slide_animation_.Start();
}
void BubbleSlideAnimator::SnapToAnchorView(View* desired_anchor_view) {
StopAnimation();
target_bubble_bounds_ = CalculateTargetBounds(desired_anchor_view);
starting_bubble_bounds_ = target_bubble_bounds_;
bubble_delegate_->GetWidget()->SetBounds(target_bubble_bounds_);
bubble_delegate_->SetAnchorView(desired_anchor_view);
slide_progressed_callbacks_.Notify(this, 1.0);
slide_complete_callbacks_.Notify(this);
}
void BubbleSlideAnimator::UpdateTargetBounds() {
if (is_animating()) {
// This will cause a mid-animation pop due to the fact that we're not
// resetting the starting bounds but it's not clear that it's a better
// solution than rewinding and/or changing the duration of the animation.
target_bubble_bounds_ = CalculateTargetBounds(desired_anchor_view_);
} else {
View* const anchor_view = bubble_delegate_->GetAnchorView();
DCHECK(anchor_view);
SnapToAnchorView(anchor_view);
}
}
void BubbleSlideAnimator::StopAnimation() {
slide_animation_.Stop();
desired_anchor_view_ = nullptr;
}
base::CallbackListSubscription BubbleSlideAnimator::AddSlideProgressedCallback(
SlideProgressedCallback callback) {
return slide_progressed_callbacks_.Add(callback);
}
base::CallbackListSubscription BubbleSlideAnimator::AddSlideCompleteCallback(
SlideCompleteCallback callback) {
return slide_complete_callbacks_.Add(callback);
}
void BubbleSlideAnimator::AnimationProgressed(const gfx::Animation* animation) {
double value = gfx::Tween::CalculateValue(tween_type_,
slide_animation_.GetCurrentValue());
const gfx::Rect current_bounds = gfx::Tween::RectValueBetween(
value, starting_bubble_bounds_, target_bubble_bounds_);
if (current_bounds == target_bubble_bounds_ && desired_anchor_view_)
bubble_delegate_->SetAnchorView(desired_anchor_view_);
bubble_delegate_->GetWidget()->SetBounds(current_bounds);
slide_progressed_callbacks_.Notify(this, value);
}
void BubbleSlideAnimator::AnimationEnded(const gfx::Animation* animation) {
desired_anchor_view_ = nullptr;
slide_complete_callbacks_.Notify(this);
}
void BubbleSlideAnimator::AnimationCanceled(const gfx::Animation* animation) {
desired_anchor_view_ = nullptr;
}
void BubbleSlideAnimator::OnWidgetDestroying(Widget* widget) {
widget_observation_.Reset();
slide_animation_.Stop();
}
gfx::Rect BubbleSlideAnimator::CalculateTargetBounds(
const View* desired_anchor_view) const {
return bubble_delegate_->GetBubbleFrameView()->GetUpdatedWindowBounds(
desired_anchor_view->GetAnchorBoundsInScreen(), bubble_delegate_->arrow(),
bubble_delegate_->GetWidget()->client_view()->GetPreferredSize(), true);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bubble_slide_animator.cc | C++ | unknown | 4,018 |
// 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_BUBBLE_SLIDE_ANIMATOR_H_
#define UI_VIEWS_ANIMATION_BUBBLE_SLIDE_ANIMATOR_H_
#include "base/callback_list.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/geometry/rect.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 BubbleDialogDelegateView;
class View;
// Animates a bubble between anchor views on demand. Must be used with
// BubbleDialogDelegateView because of its reliance on the anchoring system.
class VIEWS_EXPORT BubbleSlideAnimator : public AnimationDelegateViews,
public WidgetObserver {
public:
// Slide complete callback is called when a slide completes and the bubble is
// safely anchored to the new view.
using SlideCompleteCallbackSignature = void(BubbleSlideAnimator*);
using SlideCompleteCallback =
base::RepeatingCallback<SlideCompleteCallbackSignature>;
// Slide progressed callback is called for each animation frame,
// |animation_value| will be between 0 and 1 and will scale according to the
// |tween_type| parameter.
using SlideProgressedCallbackSignature = void(BubbleSlideAnimator*,
double animation_value);
using SlideProgressedCallback =
base::RepeatingCallback<SlideProgressedCallbackSignature>;
// Constructs a new BubbleSlideAnimator associated with the specified
// |bubble_view|, which must already have a widget. If the bubble's widget is
// destroyed, any animations will be canceled and this animator will no longer
// be able to be used.
explicit BubbleSlideAnimator(BubbleDialogDelegateView* bubble_view);
BubbleSlideAnimator(const BubbleSlideAnimator&) = delete;
BubbleSlideAnimator& operator=(const BubbleSlideAnimator&) = delete;
~BubbleSlideAnimator() override;
bool is_animating() const { return slide_animation_.is_animating(); }
// Sets the animation duration (a default is used if not set).
void SetSlideDuration(base::TimeDelta duration);
View* desired_anchor_view() { return desired_anchor_view_; }
const View* desired_anchor_view() const { return desired_anchor_view_; }
gfx::Tween::Type tween_type() const { return tween_type_; }
void set_tween_type(gfx::Tween::Type tween_type) { tween_type_ = tween_type; }
// Animates to a new anchor view.
void AnimateToAnchorView(View* desired_anchor_view);
// Ends any ongoing animation and immediately snaps the bubble to its target
// bounds.
void SnapToAnchorView(View* desired_anchor_view);
// Retargets the current animation or snaps the bubble to its correct size
// and position if there is no current animation.
//
// Call if the bubble contents change size in a way that would require the
// bubble to be resized/repositioned. If you would like a new animation to
// always play to the new bounds, call AnimateToAnchorView() instead.
//
// Note: This method expects the bubble to have a valid anchor view.
void UpdateTargetBounds();
// Stops the animation without snapping the widget to a particular anchor
// view.
void StopAnimation();
// Adds a listener for slide progressed events.
base::CallbackListSubscription AddSlideProgressedCallback(
SlideProgressedCallback callback);
// Adds a listener for slide complete events.
base::CallbackListSubscription AddSlideCompleteCallback(
SlideCompleteCallback callback);
private:
// AnimationDelegateViews:
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
// Determines where to animate the bubble to during an animation.
gfx::Rect CalculateTargetBounds(const View* desired_anchor_view) const;
const raw_ptr<BubbleDialogDelegateView> bubble_delegate_;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
gfx::LinearAnimation slide_animation_{this};
// The desired anchor view, which is valid during a slide animation. When not
// animating, this value is null.
raw_ptr<View> desired_anchor_view_ = nullptr;
// The tween type to use when animating. The default should be aesthetically
// pleasing for most applications.
gfx::Tween::Type tween_type_ = gfx::Tween::FAST_OUT_SLOW_IN;
gfx::Rect starting_bubble_bounds_;
gfx::Rect target_bubble_bounds_;
base::RepeatingCallbackList<SlideProgressedCallbackSignature>
slide_progressed_callbacks_;
base::RepeatingCallbackList<SlideCompleteCallbackSignature>
slide_complete_callbacks_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_BUBBLE_SLIDE_ANIMATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bubble_slide_animator.h | C++ | unknown | 5,160 |
// 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/bubble_slide_animator.h"
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/test/bind.h"
#include "base/time/time.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/flex_layout_view.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
constexpr base::TimeDelta kSlideDuration = base::Milliseconds(1000);
constexpr base::TimeDelta kHalfSlideDuration = kSlideDuration / 2;
// This will be the size of the three horizontally-oriented anchor views as well
// as the target size for the floating view.
constexpr gfx::Size kTestViewSize(100, 100);
// Make this big enough that even if we anchor to a third view horizontally, no
// mirroring should happen.
constexpr gfx::Rect kAnchorWidgetRect(50, 50, 400, 250);
class TestBubbleView : public BubbleDialogDelegateView {
public:
explicit TestBubbleView(View* anchor_view)
: BubbleDialogDelegateView(anchor_view, BubbleBorder::TOP_LEFT) {
SetButtons(ui::DIALOG_BUTTON_NONE);
SetLayoutManager(std::make_unique<FillLayout>());
AddChildView(std::make_unique<View>())->SetPreferredSize(kTestViewSize);
}
protected:
void AddedToWidget() override {
BubbleDialogDelegateView::AddedToWidget();
SizeToContents();
}
};
class TestBubbleSlideAnimator : public BubbleSlideAnimator {
public:
using BubbleSlideAnimator::BubbleSlideAnimator;
~TestBubbleSlideAnimator() override = default;
void AnimationContainerWasSet(gfx::AnimationContainer* container) override {
BubbleSlideAnimator::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 BubbleSlideAnimatorTest : public test::WidgetTest {
public:
void SetUp() override {
test::WidgetTest::SetUp();
anchor_widget_ = CreateTestWidget(Widget::InitParams::Type::TYPE_WINDOW);
auto* const contents_view = anchor_widget_->GetRootView()->AddChildView(
std::make_unique<FlexLayoutView>());
contents_view->SetOrientation(LayoutOrientation::kHorizontal);
contents_view->SetMainAxisAlignment(LayoutAlignment::kStart);
contents_view->SetCrossAxisAlignment(LayoutAlignment::kStart);
view1_ = contents_view->AddChildView(std::make_unique<View>());
view2_ = contents_view->AddChildView(std::make_unique<View>());
view3_ = contents_view->AddChildView(std::make_unique<View>());
view1_->SetPreferredSize(kTestViewSize);
view2_->SetPreferredSize(kTestViewSize);
view3_->SetPreferredSize(kTestViewSize);
anchor_widget_->Show();
anchor_widget_->SetBounds(kAnchorWidgetRect);
bubble_ = new TestBubbleView(view1_);
widget_ = BubbleDialogDelegateView::CreateBubble(bubble_);
delegate_ = std::make_unique<TestBubbleSlideAnimator>(bubble_);
delegate_->SetSlideDuration(kSlideDuration);
}
void TearDown() override {
CloseWidget();
if (anchor_widget_ && !anchor_widget_->IsClosed())
anchor_widget_->CloseNow();
test::WidgetTest::TearDown();
}
void CloseWidget() {
if (widget_ && !widget_->IsClosed())
widget_->CloseNow();
widget_ = nullptr;
bubble_ = nullptr;
}
protected:
std::unique_ptr<Widget> anchor_widget_;
raw_ptr<BubbleDialogDelegateView> bubble_ = nullptr;
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<View> view1_;
raw_ptr<View> view2_;
raw_ptr<View> view3_;
std::unique_ptr<TestBubbleSlideAnimator> delegate_;
};
TEST_F(BubbleSlideAnimatorTest, InitiateSlide) {
const auto bounds = widget_->GetWindowBoundsInScreen();
delegate_->AnimateToAnchorView(view2_);
// Shouldn't animate from here yet.
EXPECT_EQ(bounds, widget_->GetWindowBoundsInScreen());
EXPECT_TRUE(delegate_->is_animating());
}
TEST_F(BubbleSlideAnimatorTest, SlideProgresses) {
const auto starting_bounds = widget_->GetWindowBoundsInScreen();
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
const auto intermediate_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_TRUE(delegate_->is_animating());
EXPECT_EQ(intermediate_bounds.y(), starting_bounds.y());
EXPECT_GT(intermediate_bounds.x(), starting_bounds.x());
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
const auto final_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(final_bounds.y(), starting_bounds.y());
EXPECT_GT(final_bounds.x(), intermediate_bounds.x());
EXPECT_EQ(final_bounds.x(), starting_bounds.x() + view2_->x() - view1_->x());
}
TEST_F(BubbleSlideAnimatorTest, SnapToAnchorView) {
const auto starting_bounds = widget_->GetWindowBoundsInScreen();
delegate_->SnapToAnchorView(view2_);
const auto final_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(final_bounds.y(), starting_bounds.y());
EXPECT_EQ(final_bounds.x(), starting_bounds.x() + view2_->x() - view1_->x());
}
TEST_F(BubbleSlideAnimatorTest, SlideCallbacksCalled) {
int progress_count = 0;
int complete_count = 0;
double last_progress = 0.0;
auto progress_sub = delegate_->AddSlideProgressedCallback(
base::BindLambdaForTesting([&](BubbleSlideAnimator*, double progress) {
last_progress = progress;
++progress_count;
}));
auto completed_sub =
delegate_->AddSlideCompleteCallback(base::BindLambdaForTesting(
[&](BubbleSlideAnimator*) { ++complete_count; }));
delegate_->AnimateToAnchorView(view2_);
EXPECT_EQ(0, progress_count);
EXPECT_EQ(0, complete_count);
EXPECT_EQ(0.0, last_progress);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
EXPECT_EQ(1, progress_count);
EXPECT_EQ(0, complete_count);
EXPECT_GT(last_progress, 0.0);
EXPECT_LT(last_progress, 1.0);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
EXPECT_EQ(2, progress_count);
EXPECT_EQ(1, complete_count);
EXPECT_EQ(1.0, last_progress);
}
TEST_F(BubbleSlideAnimatorTest, SnapCallbacksCalled) {
int progress_count = 0;
int complete_count = 0;
double last_progress = 0.0;
auto progress_sub = delegate_->AddSlideProgressedCallback(
base::BindLambdaForTesting([&](BubbleSlideAnimator*, double progress) {
last_progress = progress;
++progress_count;
}));
auto completed_sub =
delegate_->AddSlideCompleteCallback(base::BindLambdaForTesting(
[&](BubbleSlideAnimator*) { ++complete_count; }));
delegate_->SnapToAnchorView(view2_);
EXPECT_EQ(1, progress_count);
EXPECT_EQ(1, complete_count);
EXPECT_EQ(1.0, last_progress);
}
TEST_F(BubbleSlideAnimatorTest, InterruptingWithSlideCallsCorrectCallbacks) {
int progress_count = 0;
int complete_count = 0;
double last_progress = 0.0;
auto progress_sub = delegate_->AddSlideProgressedCallback(
base::BindLambdaForTesting([&](BubbleSlideAnimator*, double progress) {
last_progress = progress;
++progress_count;
}));
auto completed_sub =
delegate_->AddSlideCompleteCallback(base::BindLambdaForTesting(
[&](BubbleSlideAnimator*) { ++complete_count; }));
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
EXPECT_EQ(1, progress_count);
EXPECT_EQ(0, complete_count);
delegate_->AnimateToAnchorView(view3_);
EXPECT_EQ(1, progress_count);
EXPECT_EQ(0, complete_count);
delegate_->test_api()->IncrementTime(kSlideDuration);
EXPECT_EQ(2, progress_count);
EXPECT_EQ(1, complete_count);
}
TEST_F(BubbleSlideAnimatorTest, InterruptingWithSnapCallsCorrectCallbacks) {
int progress_count = 0;
int complete_count = 0;
double last_progress = 0.0;
auto progress_sub = delegate_->AddSlideProgressedCallback(
base::BindLambdaForTesting([&](BubbleSlideAnimator*, double progress) {
last_progress = progress;
++progress_count;
}));
auto completed_sub =
delegate_->AddSlideCompleteCallback(base::BindLambdaForTesting(
[&](BubbleSlideAnimator*) { ++complete_count; }));
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
EXPECT_EQ(1, progress_count);
EXPECT_EQ(0, complete_count);
delegate_->SnapToAnchorView(view3_);
EXPECT_EQ(2, progress_count);
EXPECT_EQ(1, complete_count);
EXPECT_EQ(1.0, last_progress);
}
TEST_F(BubbleSlideAnimatorTest, CancelAnimation) {
int progress_count = 0;
int complete_count = 0;
double last_progress = 0.0;
auto progress_sub = delegate_->AddSlideProgressedCallback(
base::BindLambdaForTesting([&](BubbleSlideAnimator*, double progress) {
last_progress = progress;
++progress_count;
}));
auto completed_sub =
delegate_->AddSlideCompleteCallback(base::BindLambdaForTesting(
[&](BubbleSlideAnimator*) { ++complete_count; }));
const auto initial_bounds = widget_->GetWindowBoundsInScreen();
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kSlideDuration);
const auto second_bounds = widget_->GetWindowBoundsInScreen();
delegate_->AnimateToAnchorView(view1_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
const auto final_bounds = widget_->GetWindowBoundsInScreen();
delegate_->StopAnimation();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(2, progress_count);
EXPECT_EQ(1, complete_count);
EXPECT_GT(last_progress, 0.0);
EXPECT_LT(last_progress, 1.0);
EXPECT_GT(final_bounds.x(), initial_bounds.x());
EXPECT_LT(final_bounds.x(), second_bounds.x());
}
TEST_F(BubbleSlideAnimatorTest, MultipleSlidesInSequence) {
// First slide.
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kSlideDuration);
const auto first_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
// Second slide.
delegate_->AnimateToAnchorView(view3_);
EXPECT_TRUE(delegate_->is_animating());
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
// Ensure we are sliding.
const auto intermediate_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_TRUE(delegate_->is_animating());
EXPECT_EQ(intermediate_bounds.y(), first_bounds.y());
EXPECT_GT(intermediate_bounds.x(), first_bounds.x());
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
// Ensure we're done.
const auto final_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(final_bounds.y(), first_bounds.y());
EXPECT_EQ(final_bounds.x(), first_bounds.x() + view3_->x() - view2_->x());
}
TEST_F(BubbleSlideAnimatorTest, SlideBackToStartingPosition) {
const auto first_bounds = widget_->GetWindowBoundsInScreen();
delegate_->AnimateToAnchorView(view3_);
delegate_->test_api()->IncrementTime(kSlideDuration);
delegate_->AnimateToAnchorView(view1_);
delegate_->test_api()->IncrementTime(kSlideDuration);
const auto final_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(final_bounds, first_bounds);
}
TEST_F(BubbleSlideAnimatorTest, InterruptingSlide) {
const auto starting_bounds = widget_->GetWindowBoundsInScreen();
// Start the first slide.
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
const auto intermediate_bounds1 = widget_->GetWindowBoundsInScreen();
EXPECT_TRUE(delegate_->is_animating());
// Interrupt mid-slide with another slide.
delegate_->AnimateToAnchorView(view3_);
EXPECT_TRUE(delegate_->is_animating());
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
// Ensure we are sliding.
const auto intermediate_bounds2 = widget_->GetWindowBoundsInScreen();
EXPECT_TRUE(delegate_->is_animating());
EXPECT_EQ(intermediate_bounds2.y(), intermediate_bounds1.y());
EXPECT_GT(intermediate_bounds2.x(), intermediate_bounds1.x());
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
// Ensure we are done.
const auto final_bounds = widget_->GetWindowBoundsInScreen();
EXPECT_FALSE(delegate_->is_animating());
EXPECT_EQ(final_bounds.y(), starting_bounds.y());
EXPECT_EQ(final_bounds.x(), starting_bounds.x() + view3_->x() - view1_->x());
}
TEST_F(BubbleSlideAnimatorTest, WidgetClosedDuringSlide) {
delegate_->AnimateToAnchorView(view2_);
CloseWidget();
EXPECT_FALSE(delegate_->is_animating());
}
TEST_F(BubbleSlideAnimatorTest, AnimatorDestroyedDuringSlide) {
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
delegate_.reset();
}
TEST_F(BubbleSlideAnimatorTest, AnimationSetsAnchorView) {
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kSlideDuration);
EXPECT_EQ(view2_, bubble_->GetAnchorView());
delegate_->AnimateToAnchorView(view3_);
delegate_->test_api()->IncrementTime(kSlideDuration);
EXPECT_EQ(view3_, bubble_->GetAnchorView());
}
TEST_F(BubbleSlideAnimatorTest, SnapSetsAnchorView) {
delegate_->SnapToAnchorView(view2_);
EXPECT_EQ(view2_, bubble_->GetAnchorView());
delegate_->SnapToAnchorView(view3_);
EXPECT_EQ(view3_, bubble_->GetAnchorView());
}
TEST_F(BubbleSlideAnimatorTest, CancelDoesntSetAnchorView) {
delegate_->AnimateToAnchorView(view2_);
delegate_->test_api()->IncrementTime(kHalfSlideDuration);
delegate_->StopAnimation();
EXPECT_EQ(view1_, bubble_->GetAnchorView());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/bubble_slide_animator_unittest.cc | C++ | unknown | 13,983 |
// 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/animation/compositor_animation_runner.h"
#include "ui/views/widget/widget.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// CompositorAnimationRunner
//
CompositorAnimationRunner::CompositorAnimationRunner(
Widget* widget,
const base::Location& location)
: ui::CompositorAnimationObserver(location), widget_(widget) {
widget_->AddObserver(this);
}
CompositorAnimationRunner::~CompositorAnimationRunner() {
// Make sure we're not observing |compositor_|.
if (widget_)
OnWidgetDestroying(widget_);
DCHECK(!compositor_ || !compositor_->HasAnimationObserver(this));
CHECK(!IsInObserverList());
}
void CompositorAnimationRunner::Stop() {
StopInternal();
}
void CompositorAnimationRunner::OnAnimationStep(base::TimeTicks timestamp) {
if (timestamp - last_tick_ < min_interval_)
return;
last_tick_ = timestamp;
Step(last_tick_);
}
void CompositorAnimationRunner::OnCompositingShuttingDown(
ui::Compositor* compositor) {
StopInternal();
}
void CompositorAnimationRunner::OnWidgetDestroying(Widget* widget) {
StopInternal();
widget_->RemoveObserver(this);
widget_ = nullptr;
}
void CompositorAnimationRunner::OnStart(base::TimeDelta min_interval,
base::TimeDelta elapsed) {
if (!widget_)
return;
ui::Compositor* current_compositor = widget_->GetCompositor();
if (!current_compositor) {
StopInternal();
return;
}
if (current_compositor != compositor_) {
if (compositor_ && compositor_->HasAnimationObserver(this))
compositor_->RemoveAnimationObserver(this);
compositor_ = current_compositor;
}
last_tick_ = base::TimeTicks::Now() - elapsed;
min_interval_ = min_interval;
DCHECK(!compositor_->HasAnimationObserver(this));
compositor_->AddAnimationObserver(this);
}
void CompositorAnimationRunner::StopInternal() {
if (compositor_ && compositor_->HasAnimationObserver(this))
compositor_->RemoveAnimationObserver(this);
min_interval_ = base::TimeDelta::Max();
compositor_ = nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/compositor_animation_runner.cc | C++ | unknown | 2,275 |
// 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_ANIMATION_COMPOSITOR_ANIMATION_RUNNER_H_
#define UI_VIEWS_ANIMATION_COMPOSITOR_ANIMATION_RUNNER_H_
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_animation_observer.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/gfx/animation/animation_container.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class Widget;
// An animation runner based on ui::Compositor.
class VIEWS_EXPORT CompositorAnimationRunner
: public gfx::AnimationRunner,
public ui::CompositorAnimationObserver,
public WidgetObserver {
public:
explicit CompositorAnimationRunner(
Widget* widget,
const base::Location& location = FROM_HERE);
CompositorAnimationRunner(CompositorAnimationRunner&) = delete;
CompositorAnimationRunner& operator=(CompositorAnimationRunner&) = delete;
~CompositorAnimationRunner() override;
// gfx::AnimationRunner:
void Stop() override;
// ui::CompositorAnimationObserver:
void OnAnimationStep(base::TimeTicks timestamp) override;
void OnCompositingShuttingDown(ui::Compositor* compositor) override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
protected:
// gfx::AnimationRunner:
void OnStart(base::TimeDelta min_interval, base::TimeDelta elapsed) override;
private:
// Called when an animation is stopped, the compositor is shutting down, or
// the widget is destroyed.
void StopInternal();
// When |widget_| is nullptr, it means the widget has been destroyed and
// |compositor_| must also be nullptr.
raw_ptr<Widget> widget_;
// When |compositor_| is nullptr, it means either the animation is not
// running, or the compositor or |widget_| associated with the compositor_ has
// been destroyed during animation.
raw_ptr<ui::Compositor> compositor_ = nullptr;
base::TimeDelta min_interval_ = base::TimeDelta::Max();
base::TimeTicks last_tick_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_COMPOSITOR_ANIMATION_RUNNER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/compositor_animation_runner.h | C++ | unknown | 2,284 |
// 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/animation/compositor_animation_runner.h"
#include "base/test/bind.h"
#include "base/timer/timer.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/compositor/throughput_tracker.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/views/animation/animation_delegate_views.h"
#include "ui/views/buildflags.h"
#include "ui/views/test/widget_test.h"
namespace views::test {
namespace {
constexpr base::TimeDelta kDuration = base::Milliseconds(100);
}
using CompositorAnimationRunnerTest = WidgetTest;
TEST_F(CompositorAnimationRunnerTest, BasicCoverageTest) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->Show();
AnimationDelegateViews delegate(widget->GetContentsView());
gfx::LinearAnimation animation(
kDuration, gfx::LinearAnimation::kDefaultFrameRate, &delegate);
base::RepeatingTimer interval_timer;
base::RunLoop run_loop;
animation.Start();
EXPECT_TRUE(animation.is_animating());
EXPECT_TRUE(delegate.container()->has_custom_animation_runner());
interval_timer.Start(FROM_HERE, kDuration, base::BindLambdaForTesting([&]() {
if (animation.is_animating())
return;
interval_timer.Stop();
run_loop.Quit();
}));
run_loop.Run();
}
namespace {
// Test AnimationDelegateView which has a non-zero expected animation duration
// time, which is required for getting smoothness reports.
class TestAnimationDelegateViews : public AnimationDelegateViews {
public:
explicit TestAnimationDelegateViews(View* view)
: AnimationDelegateViews(view) {}
TestAnimationDelegateViews(TestAnimationDelegateViews&) = delete;
TestAnimationDelegateViews& operator=(TestAnimationDelegateViews&) = delete;
~TestAnimationDelegateViews() override = default;
// AnimationDelegateViews:
base::TimeDelta GetAnimationDurationForReporting() const override {
return kDuration;
}
};
} // namespace
// Tests that ui::ThroughputTracker will report for gfx::Animation.
TEST_F(CompositorAnimationRunnerTest, ThroughputTracker) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->Show();
ui::DrawWaiterForTest::WaitForCompositingStarted(widget->GetCompositor());
int report_count = 0;
int report_count2 = 0;
TestAnimationDelegateViews delegate(widget->GetContentsView());
gfx::LinearAnimation animation(
kDuration, gfx::LinearAnimation::kDefaultFrameRate, &delegate);
base::RepeatingTimer interval_timer;
base::RunLoop run_loop;
ui::ThroughputTracker tracker1 =
widget->GetCompositor()->RequestNewThroughputTracker();
tracker1.Start(base::BindLambdaForTesting(
[&](const cc::FrameSequenceMetrics::CustomReportData& data) {
++report_count;
run_loop.Quit();
}));
animation.Start();
EXPECT_TRUE(animation.is_animating());
EXPECT_TRUE(delegate.container()->has_custom_animation_runner());
interval_timer.Start(FROM_HERE, kDuration, base::BindLambdaForTesting([&]() {
if (animation.is_animating())
return;
interval_timer.Stop();
tracker1.Stop();
}));
run_loop.Run();
EXPECT_EQ(1, report_count);
EXPECT_EQ(0, report_count2);
// Tests that switching metrics reporters for the next animation works as
// expected.
base::RunLoop run_loop2;
ui::ThroughputTracker tracker2 =
widget->GetCompositor()->RequestNewThroughputTracker();
tracker2.Start(base::BindLambdaForTesting(
[&](const cc::FrameSequenceMetrics::CustomReportData& data) {
++report_count2;
run_loop2.Quit();
}));
animation.Start();
EXPECT_TRUE(animation.is_animating());
interval_timer.Start(FROM_HERE, kDuration, base::BindLambdaForTesting([&]() {
if (animation.is_animating())
return;
interval_timer.Stop();
tracker2.Stop();
}));
run_loop2.Run();
EXPECT_EQ(1, report_count);
EXPECT_EQ(1, report_count2);
}
// No DesktopAura on ChromeOS.
// Each widget on MACOSX has its own ui::Compositor.
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
using CompositorAnimationRunnerDesktopTest = DesktopWidgetTest;
TEST_F(CompositorAnimationRunnerDesktopTest, SwitchCompositor) {
WidgetAutoclosePtr widget1(CreateTopLevelNativeWidget());
widget1->Show();
WidgetAutoclosePtr widget2(CreateTopLevelNativeWidget());
widget2->Show();
ASSERT_NE(widget1->GetCompositor(), widget2->GetCompositor());
Widget* child = CreateChildNativeWidgetWithParent(widget1.get());
child->Show();
AnimationDelegateViews delegate(child->GetContentsView());
gfx::LinearAnimation animation(
kDuration, gfx::LinearAnimation::kDefaultFrameRate, &delegate);
base::RepeatingTimer interval_timer;
animation.Start();
EXPECT_TRUE(animation.is_animating());
EXPECT_TRUE(delegate.container()->has_custom_animation_runner());
{
base::RunLoop run_loop;
interval_timer.Start(FROM_HERE, kDuration,
base::BindLambdaForTesting([&]() {
if (animation.is_animating())
return;
interval_timer.Stop();
run_loop.Quit();
}));
run_loop.Run();
}
EXPECT_FALSE(animation.is_animating());
Widget::ReparentNativeView(child->GetNativeView(), widget2->GetNativeView());
widget1.reset();
animation.Start();
EXPECT_TRUE(animation.is_animating());
EXPECT_TRUE(delegate.container()->has_custom_animation_runner());
{
base::RunLoop run_loop;
interval_timer.Start(FROM_HERE, kDuration,
base::BindLambdaForTesting([&]() {
if (animation.is_animating())
return;
interval_timer.Stop();
run_loop.Quit();
}));
run_loop.Run();
}
}
#endif
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/compositor_animation_runner_unittest.cc | C++ | unknown | 6,313 |
// 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/animation/flood_fill_ink_drop_ripple.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/ink_drop_util.h"
#include "ui/views/style/platform_style.h"
namespace {
// The minimum radius to use when scaling the painted layers. Smaller values
// were causing visual anomalies.
constexpr float kMinRadius = 1.f;
// All the sub animations that are used to animate each of the InkDropStates.
// These are used to get time durations with
// GetAnimationDuration(InkDropSubAnimations). Note that in general a sub
// animation defines the duration for either a transformation animation or an
// opacity animation but there are some exceptions where an entire InkDropState
// animation consists of only 1 sub animation and it defines the duration for
// both the transformation and opacity animations.
enum InkDropSubAnimations {
// HIDDEN sub animations.
// The HIDDEN sub animation that is fading out to a hidden opacity.
HIDDEN_FADE_OUT,
// The HIDDEN sub animation that transform the circle to a small one.
HIDDEN_TRANSFORM,
// ACTION_PENDING sub animations.
// The ACTION_PENDING sub animation that fades in to the visible opacity.
ACTION_PENDING_FADE_IN,
// The ACTION_PENDING sub animation that transforms the circle to fill the
// bounds.
ACTION_PENDING_TRANSFORM,
// ACTION_TRIGGERED sub animations.
// The ACTION_TRIGGERED sub animation that is fading out to a hidden opacity.
ACTION_TRIGGERED_FADE_OUT,
// ALTERNATE_ACTION_PENDING sub animations.
// The ALTERNATE_ACTION_PENDING animation has only one sub animation which
// animates
// the circleto fill the bounds at visible opacity.
ALTERNATE_ACTION_PENDING,
// ALTERNATE_ACTION_TRIGGERED sub animations.
// The ALTERNATE_ACTION_TRIGGERED sub animation that is fading out to a hidden
// opacity.
ALTERNATE_ACTION_TRIGGERED_FADE_OUT,
// ACTIVATED sub animations.
// The ACTIVATED sub animation that is fading in to the visible opacity.
ACTIVATED_FADE_IN,
// The ACTIVATED sub animation that transforms the circle to fill the entire
// bounds.
ACTIVATED_TRANSFORM,
// DEACTIVATED sub animations.
// The DEACTIVATED sub animation that is fading out to a hidden opacity.
DEACTIVATED_FADE_OUT,
};
// Duration constants for InkDropStateSubAnimations. See the
// InkDropStateSubAnimations enum documentation for more info.
int kAnimationDurationInMs[] = {
200, // HIDDEN_FADE_OUT
300, // HIDDEN_TRANSFORM
0, // ACTION_PENDING_FADE_IN
240, // ACTION_PENDING_TRANSFORM
300, // ACTION_TRIGGERED_FADE_OUT
200, // ALTERNATE_ACTION_PENDING
300, // ALTERNATE_ACTION_TRIGGERED_FADE_OUT
150, // ACTIVATED_FADE_IN
200, // ACTIVATED_TRANSFORM
300, // DEACTIVATED_FADE_OUT
};
gfx::Rect CalculateClipBounds(const gfx::Size& host_size,
const gfx::Insets& clip_insets) {
gfx::Rect clip_bounds(host_size);
clip_bounds.Inset(clip_insets);
return clip_bounds;
}
float CalculateCircleLayerRadius(const gfx::Rect& clip_bounds) {
return std::max(clip_bounds.width(), clip_bounds.height()) / 2.f;
}
} // namespace
namespace views {
FloodFillInkDropRipple::FloodFillInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
const gfx::Insets& clip_insets,
const gfx::Point& center_point,
SkColor color,
float visible_opacity)
: InkDropRipple(ink_drop_host),
clip_insets_(clip_insets),
center_point_(center_point),
visible_opacity_(visible_opacity),
use_hide_transform_duration_for_hide_fade_out_(false),
duration_factor_(1.f),
root_layer_(ui::LAYER_NOT_DRAWN),
circle_layer_delegate_(color,
CalculateCircleLayerRadius(
CalculateClipBounds(host_size, clip_insets))) {
gfx::Rect clip_bounds = CalculateClipBounds(host_size, clip_insets);
root_layer_.SetName("FloodFillInkDropRipple:ROOT_LAYER");
root_layer_.SetMasksToBounds(true);
root_layer_.SetBounds(clip_bounds);
root_callback_subscription_ =
root_layer_.GetAnimator()->AddSequenceScheduledCallback(
base::BindRepeating(
&FloodFillInkDropRipple::OnLayerAnimationSequenceScheduled,
base::Unretained(this)));
const int painted_size_length =
std::max(clip_bounds.width(), clip_bounds.height());
painted_layer_.SetBounds(gfx::Rect(painted_size_length, painted_size_length));
painted_layer_.SetFillsBoundsOpaquely(false);
painted_layer_.set_delegate(&circle_layer_delegate_);
painted_layer_.SetVisible(true);
painted_layer_.SetOpacity(1.0);
painted_layer_.SetMasksToBounds(false);
painted_layer_.SetName("FloodFillInkDropRipple:PAINTED_LAYER");
painted_layer_callback_subscription_ =
painted_layer_.GetAnimator()->AddSequenceScheduledCallback(
base::BindRepeating(
&FloodFillInkDropRipple::OnLayerAnimationSequenceScheduled,
base::Unretained(this)));
root_layer_.Add(&painted_layer_);
SetStateToHidden();
}
FloodFillInkDropRipple::FloodFillInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
const gfx::Point& center_point,
SkColor color,
float visible_opacity)
: FloodFillInkDropRipple(ink_drop_host,
host_size,
gfx::Insets(),
center_point,
color,
visible_opacity) {}
FloodFillInkDropRipple::~FloodFillInkDropRipple() {
// Explicitly aborting all the animations ensures all callbacks are invoked
// while this instance still exists.
AbortAllAnimations();
}
void FloodFillInkDropRipple::SnapToActivated() {
InkDropRipple::SnapToActivated();
SetOpacity(visible_opacity_);
painted_layer_.SetTransform(GetMaxSizeTargetTransform());
}
ui::Layer* FloodFillInkDropRipple::GetRootLayer() {
return &root_layer_;
}
void FloodFillInkDropRipple::AnimateStateChange(
InkDropState old_ink_drop_state,
InkDropState new_ink_drop_state) {
switch (new_ink_drop_state) {
case InkDropState::HIDDEN:
if (!IsVisible()) {
SetStateToHidden();
} else {
AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(GetAnimationDuration(HIDDEN_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT)
.At(base::TimeDelta())
.SetDuration(GetAnimationDuration(HIDDEN_TRANSFORM))
.SetTransform(&painted_layer_, CalculateTransform(kMinRadius),
gfx::Tween::EASE_IN_OUT);
}
break;
case InkDropState::ACTION_PENDING: {
DLOG_IF(WARNING, InkDropState::HIDDEN != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(GetAnimationDuration(ACTION_PENDING_FADE_IN))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN)
.At(base::TimeDelta())
.SetDuration(GetAnimationDuration(ACTION_PENDING_TRANSFORM))
.SetTransform(&painted_layer_, GetMaxSizeTargetTransform(),
gfx::Tween::FAST_OUT_SLOW_IN);
break;
}
case InkDropState::ACTION_TRIGGERED: {
DLOG_IF(WARNING, old_ink_drop_state != InkDropState::HIDDEN &&
old_ink_drop_state != InkDropState::ACTION_PENDING)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
if (old_ink_drop_state == InkDropState::HIDDEN) {
AnimateStateChange(old_ink_drop_state, InkDropState::ACTION_PENDING);
}
AnimationBuilder()
.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION)
.Once()
.SetDuration(GetAnimationDuration(ACTION_TRIGGERED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::ALTERNATE_ACTION_PENDING: {
DLOG_IF(WARNING, InkDropState::ACTION_PENDING != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(GetAnimationDuration(ALTERNATE_ACTION_PENDING))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN)
.SetTransform(&painted_layer_, GetMaxSizeTargetTransform(),
gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::ALTERNATE_ACTION_TRIGGERED:
DLOG_IF(WARNING,
InkDropState::ALTERNATE_ACTION_PENDING != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
AnimationBuilder()
.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION)
.Once()
.SetDuration(
GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT);
break;
case InkDropState::ACTIVATED: {
if (old_ink_drop_state != InkDropState::ACTION_PENDING) {
AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(GetAnimationDuration(ACTIVATED_FADE_IN))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN)
.At(base::TimeDelta())
.SetDuration(GetAnimationDuration(ACTIVATED_TRANSFORM))
.SetTransform(&painted_layer_, GetMaxSizeTargetTransform(),
gfx::Tween::EASE_IN_OUT);
}
break;
}
case InkDropState::DEACTIVATED:
AnimationBuilder()
.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION)
.Once()
.SetDuration(GetAnimationDuration(DEACTIVATED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT);
break;
}
}
void FloodFillInkDropRipple::SetStateToHidden() {
painted_layer_.SetTransform(CalculateTransform(kMinRadius));
root_layer_.SetOpacity(kHiddenOpacity);
root_layer_.SetVisible(false);
}
void FloodFillInkDropRipple::AbortAllAnimations() {
root_layer_.GetAnimator()->AbortAllAnimations();
painted_layer_.GetAnimator()->AbortAllAnimations();
}
void FloodFillInkDropRipple::SetOpacity(float opacity) {
root_layer_.SetOpacity(opacity);
}
gfx::Transform FloodFillInkDropRipple::CalculateTransform(
float target_radius) const {
const float target_scale = target_radius / circle_layer_delegate_.radius();
gfx::Transform transform = gfx::Transform();
transform.Translate(center_point_.x() - root_layer_.bounds().x(),
center_point_.y() - root_layer_.bounds().y());
transform.Scale(target_scale, target_scale);
const gfx::Vector2dF drawn_center_offset =
circle_layer_delegate_.GetCenteringOffset();
transform.Translate(-drawn_center_offset.x(), -drawn_center_offset.y());
// Add subpixel correction to the transform.
transform.PostConcat(GetTransformSubpixelCorrection(
transform, painted_layer_.device_scale_factor()));
return transform;
}
gfx::Transform FloodFillInkDropRipple::GetMaxSizeTargetTransform() const {
return CalculateTransform(MaxDistanceToCorners(center_point_));
}
float FloodFillInkDropRipple::MaxDistanceToCorners(
const gfx::Point& point) const {
const gfx::Rect bounds = root_layer_.bounds();
const float distance_to_top_left = (bounds.origin() - point).Length();
const float distance_to_top_right = (bounds.top_right() - point).Length();
const float distance_to_bottom_left = (bounds.bottom_left() - point).Length();
const float distance_to_bottom_right =
(bounds.bottom_right() - point).Length();
float largest_distance =
std::max(distance_to_top_left, distance_to_top_right);
largest_distance = std::max(largest_distance, distance_to_bottom_left);
largest_distance = std::max(largest_distance, distance_to_bottom_right);
return largest_distance;
}
// Returns the InkDropState sub animation duration for the given |state|.
base::TimeDelta FloodFillInkDropRipple::GetAnimationDuration(int state) {
if (!PlatformStyle::kUseRipples ||
!gfx::Animation::ShouldRenderRichAnimation() ||
(GetInkDropHost() && GetInkDropHost()->GetMode() ==
InkDropHost::InkDropMode::ON_NO_ANIMATE)) {
return base::TimeDelta();
}
int state_override = state;
// Override the requested state if needed.
if (use_hide_transform_duration_for_hide_fade_out_ &&
state == HIDDEN_FADE_OUT) {
state_override = HIDDEN_TRANSFORM;
}
return base::Milliseconds(kAnimationDurationInMs[state_override] *
duration_factor_);
}
void FloodFillInkDropRipple::OnLayerAnimationSequenceScheduled(
ui::LayerAnimationSequence* sequence) {
sequence->AddObserver(GetLayerAnimationObserver());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/flood_fill_ink_drop_ripple.cc | C++ | unknown | 14,712 |
// 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_ANIMATION_FLOOD_FILL_INK_DROP_RIPPLE_H_
#define UI_VIEWS_ANIMATION_FLOOD_FILL_INK_DROP_RIPPLE_H_
#include "base/callback_list.h"
#include "base/time/time.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/ink_drop_painted_layer_delegates.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
} // namespace ui
namespace views {
class CircleLayerDelegate;
class InkDropHost;
namespace test {
class FloodFillInkDropRippleTestApi;
} // namespace test
// An ink drop ripple that starts as a small circle and flood fills a rectangle
// of the size determined by |host_size| and |clip_insets| (if provided). The
// circle is clipped to this rectangle's bounds.
// Constructors take |host_size| and |clip_insets| and calculate the effective
// bounds of the flood fill based on them. This way, the ripple's bounds are
// defined relative to the host size and can be recalculated whenever the host
// size is changed.
//
// The valid InkDropState transitions are defined below:
//
// {All InkDropStates} => HIDDEN
// HIDDEN => ACTION_PENDING
// HIDDEN, ACTION_PENDING => ACTION_TRIGGERED
// ACTION_PENDING => ALTERNATE_ACTION_PENDING
// ALTERNATE_ACTION_PENDING => ALTERNATE_ACTION_TRIGGERED
// {All InkDropStates} => ACTIVATED
// {All InkDropStates} => DEACTIVATED
//
class VIEWS_EXPORT FloodFillInkDropRipple : public InkDropRipple {
public:
FloodFillInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
const gfx::Insets& clip_insets,
const gfx::Point& center_point,
SkColor color,
float visible_opacity);
FloodFillInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
const gfx::Point& center_point,
SkColor color,
float visible_opacity);
FloodFillInkDropRipple(const FloodFillInkDropRipple&) = delete;
FloodFillInkDropRipple& operator=(const FloodFillInkDropRipple&) = delete;
~FloodFillInkDropRipple() override;
// InkDropRipple:
void SnapToActivated() override;
ui::Layer* GetRootLayer() override;
void set_use_hide_transform_duration_for_hide_fade_out(bool value) {
use_hide_transform_duration_for_hide_fade_out_ = value;
}
void set_duration_factor(float duration_factor) {
duration_factor_ = duration_factor;
}
private:
friend class test::FloodFillInkDropRippleTestApi;
// InkDropRipple:
void AnimateStateChange(InkDropState old_ink_drop_state,
InkDropState new_ink_drop_state) override;
void SetStateToHidden() override;
void AbortAllAnimations() override;
// Sets the opacity of the ink drop. Note that this does not perform any
// animation.
void SetOpacity(float opacity);
// Returns the Transform to be applied to the |painted_layer_| for the given
// |target_radius|.
gfx::Transform CalculateTransform(float target_radius) const;
// Returns the target Transform for when the ink drop is fully shown.
gfx::Transform GetMaxSizeTargetTransform() const;
// Returns the largest distance from |point| to the corners of the
// |root_layer_| bounds.
float MaxDistanceToCorners(const gfx::Point& point) const;
// Returns the InkDropState sub animation duration for the given |state|.
base::TimeDelta GetAnimationDuration(int state);
// Called from LayerAnimator when a new LayerAnimationSequence is scheduled
// which allows for assigning the observer to the sequence.
void OnLayerAnimationSequenceScheduled(ui::LayerAnimationSequence* sequence);
// Insets of the clip area relative to the host bounds.
gfx::Insets clip_insets_;
// The point where the Center of the ink drop's circle should be drawn.
gfx::Point center_point_;
// Ink drop opacity when it is visible.
float visible_opacity_;
// Whether the fade out animation to hidden state should have the same
// duration as the associated scale transform animation.
bool use_hide_transform_duration_for_hide_fade_out_;
// The factor used to scale down/up animation duration.
float duration_factor_;
// The root layer that parents the animating layer. The root layer is used to
// manipulate opacity and clipping bounds, and it child is used to manipulate
// the different shape of the ink drop.
ui::Layer root_layer_;
// Sequence scheduled callback subscription for the root layer.
base::CallbackListSubscription root_callback_subscription_;
// ui::LayerDelegate to paint the |painted_layer_|.
CircleLayerDelegate circle_layer_delegate_;
// Child ui::Layer of |root_layer_|. Used to manipulate the different size
// and shape of the ink drop.
ui::Layer painted_layer_;
// Sequence scheduled callback subscriptions for the painted layer.
base::CallbackListSubscription painted_layer_callback_subscription_;
// The current ink drop state.
InkDropState ink_drop_state_ = InkDropState::HIDDEN;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_FLOOD_FILL_INK_DROP_RIPPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/flood_fill_ink_drop_ripple.h | C++ | unknown | 5,684 |
// 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/animation/flood_fill_ink_drop_ripple.h"
#include <cmath>
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/test/flood_fill_ink_drop_ripple_test_api.h"
namespace views::test {
TEST(FloodFillInkDropRippleTest, TransformedCenterPointForIrregularClipBounds) {
const gfx::Size host_size(48, 50);
const auto clip_insets = gfx::Insets::VH(9, 8);
const gfx::Point requested_center_point(25, 24);
// |expected_center_point| is in the coordinate space of ripple's clip bounds
// defined by |clip_insets|.
const gfx::Point expected_center_point(
requested_center_point.x() - clip_insets.left(),
requested_center_point.y() - clip_insets.top());
FloodFillInkDropRipple ripple(nullptr, host_size, clip_insets,
requested_center_point, SK_ColorWHITE, 0.175f);
FloodFillInkDropRippleTestApi test_api(&ripple);
gfx::Point3F actual_center = test_api.MapPoint(
10, gfx::Point3F(gfx::PointF(test_api.GetDrawnCenterPoint())));
EXPECT_EQ(expected_center_point,
gfx::ToRoundedPoint(actual_center.AsPointF()));
}
TEST(FloodFillInkDropRippleTest, MaxDistanceToCorners) {
const float kAbsError = 0.01f;
const gfx::Size host_size(70, 130);
// Rect with the following corners in clockwise order starting at the origin:
// (10, 30), (60, 30), (10, 100), (60, 100)
const auto clip_insets = gfx::Insets::VH(30, 10);
FloodFillInkDropRipple ripple(nullptr, host_size, clip_insets, gfx::Point(),
SK_ColorWHITE, 0.175f);
FloodFillInkDropRippleTestApi test_api(&ripple);
// Interior points
EXPECT_NEAR(78.10f, test_api.MaxDistanceToCorners(gfx::Point(10, 40)),
kAbsError);
EXPECT_NEAR(71.06f, test_api.MaxDistanceToCorners(gfx::Point(55, 45)),
kAbsError);
EXPECT_NEAR(64.03f, test_api.MaxDistanceToCorners(gfx::Point(50, 80)),
kAbsError);
EXPECT_NEAR(68.01f, test_api.MaxDistanceToCorners(gfx::Point(20, 85)),
kAbsError);
// Exterior points
EXPECT_NEAR(110.79f, test_api.MaxDistanceToCorners(gfx::Point(3, 5)),
kAbsError);
EXPECT_NEAR(108.17f, test_api.MaxDistanceToCorners(gfx::Point(70, 10)),
kAbsError);
EXPECT_NEAR(103.08f, test_api.MaxDistanceToCorners(gfx::Point(75, 110)),
kAbsError);
EXPECT_NEAR(101.24f, test_api.MaxDistanceToCorners(gfx::Point(5, 115)),
kAbsError);
}
// Verifies that both going directly from HIDDEN to ACTIVATED state and going
// through PENDING to ACTIVAED state lead to the same final opacity and
// transform values.
TEST(FloodFillInkDropRippleTest, ActivatedFinalState) {
const float kAbsError = 0.01f;
const gfx::Size host_size(100, 50);
const gfx::Point center_point(host_size.width() / 2, host_size.height() / 2);
const SkColor color = SK_ColorWHITE;
const float visible_opacity = 0.7f;
FloodFillInkDropRipple ripple(nullptr, host_size, center_point, color,
visible_opacity);
FloodFillInkDropRippleTestApi test_api(&ripple);
// Go to ACTIVATED state directly.
ripple.AnimateToState(InkDropState::ACTIVATED);
test_api.CompleteAnimations();
const float activated_opacity = test_api.GetCurrentOpacity();
const gfx::Transform activated_transform =
test_api.GetPaintedLayerTransform();
// Reset state.
ripple.AnimateToState(InkDropState::HIDDEN);
test_api.CompleteAnimations();
// Go to ACTIVATED state through PENDING state.
ripple.AnimateToState(InkDropState::ACTION_PENDING);
ripple.AnimateToState(InkDropState::ACTIVATED);
test_api.CompleteAnimations();
const float pending_activated_opacity = test_api.GetCurrentOpacity();
const gfx::Transform pending_activated_transform =
test_api.GetPaintedLayerTransform();
// Compare opacity and transform values.
EXPECT_NEAR(activated_opacity, pending_activated_opacity, kAbsError);
EXPECT_TRUE(
activated_transform.ApproximatelyEqual(pending_activated_transform));
}
TEST(FloodFillInkDropRippleTest, TransformIsPixelAligned) {
const float kEpsilon = 0.001f;
const gfx::Size host_size(11, 11);
// Keep the draw center different from the the host center to have a non zero
// offset in the transformation.
const gfx::Point center_point(host_size.width() / 3, host_size.height() / 3);
const SkColor color = SK_ColorYELLOW;
const float visible_opacity = 0.3f;
FloodFillInkDropRipple ripple(nullptr, host_size, center_point, color,
visible_opacity);
FloodFillInkDropRippleTestApi test_api(&ripple);
for (auto dsf : {1.25, 1.33, 1.5, 1.6, 1.75, 1.8, 2.25}) {
SCOPED_TRACE(testing::Message()
<< std::endl
<< "Device Scale Factor: " << dsf << std::endl);
ripple.GetRootLayer()->OnDeviceScaleFactorChanged(dsf);
gfx::Point3F ripple_origin =
test_api.MapPoint(host_size.width() / 2, gfx::Point3F());
// Apply device scale factor to get the final offset.
gfx::Transform dsf_transform;
dsf_transform.Scale(dsf, dsf);
ripple_origin = dsf_transform.MapPoint(ripple_origin);
EXPECT_NEAR(ripple_origin.x(), std::round(ripple_origin.x()), kEpsilon);
EXPECT_NEAR(ripple_origin.y(), std::round(ripple_origin.y()), kEpsilon);
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/flood_fill_ink_drop_ripple_unittest.cc | C++ | unknown | 5,668 |
// 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/animation/ink_drop.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/observer_list.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/layer.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/ink_drop_observer.h"
DEFINE_UI_CLASS_PROPERTY_TYPE(views::InkDropHost*)
namespace views {
namespace {
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(InkDropHost, kInkDropKey, nullptr)
// TODO(pbos): Remove this by changing the constructor parameters to
// InkDropImpl.
std::unique_ptr<InkDrop> CreateInkDropImpl(
InkDropHost* host,
InkDropImpl::AutoHighlightMode auto_highlight_mode,
bool highlight_on_hover,
bool highlight_on_focus) {
auto ink_drop = std::make_unique<InkDropImpl>(host, host->host_view()->size(),
auto_highlight_mode);
ink_drop->SetShowHighlightOnHover(highlight_on_hover);
ink_drop->SetShowHighlightOnFocus(highlight_on_focus);
return ink_drop;
}
} // namespace
InkDrop::~InkDrop() = default;
void InkDrop::Install(View* host, std::unique_ptr<InkDropHost> ink_drop) {
host->SetProperty(kInkDropKey, std::move(ink_drop));
}
void InkDrop::Remove(View* host) {
host->ClearProperty(kInkDropKey);
}
const InkDropHost* InkDrop::Get(const View* host) {
return host->GetProperty(kInkDropKey);
}
std::unique_ptr<InkDrop> InkDrop::CreateInkDropForSquareRipple(
InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus,
bool show_highlight_on_ripple) {
return CreateInkDropImpl(host,
show_highlight_on_ripple
? InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE
: InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE,
highlight_on_hover, highlight_on_focus);
}
void InkDrop::UseInkDropForSquareRipple(InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus,
bool show_highlight_on_ripple) {
host->SetCreateInkDropCallback(base::BindRepeating(
&InkDrop::CreateInkDropForSquareRipple, host, highlight_on_hover,
highlight_on_focus, show_highlight_on_ripple));
}
std::unique_ptr<InkDrop> InkDrop::CreateInkDropForFloodFillRipple(
InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus,
bool show_highlight_on_ripple) {
return CreateInkDropImpl(host,
show_highlight_on_ripple
? InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE
: InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE,
highlight_on_hover, highlight_on_focus);
}
void InkDrop::UseInkDropForFloodFillRipple(InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus,
bool show_highlight_on_ripple) {
host->SetCreateInkDropCallback(base::BindRepeating(
&InkDrop::CreateInkDropForFloodFillRipple, host, highlight_on_hover,
highlight_on_focus, show_highlight_on_ripple));
}
std::unique_ptr<InkDrop> InkDrop::CreateInkDropWithoutAutoHighlight(
InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus) {
return CreateInkDropImpl(host, InkDropImpl::AutoHighlightMode::NONE,
highlight_on_hover, highlight_on_focus);
}
void InkDrop::UseInkDropWithoutAutoHighlight(InkDropHost* host,
bool highlight_on_hover,
bool highlight_on_focus) {
host->SetCreateInkDropCallback(
base::BindRepeating(&InkDrop::CreateInkDropWithoutAutoHighlight, host,
highlight_on_hover, highlight_on_focus));
}
void InkDrop::AddObserver(InkDropObserver* observer) {
CHECK(observer);
observers_.AddObserver(observer);
}
void InkDrop::RemoveObserver(InkDropObserver* observer) {
CHECK(observer);
observers_.RemoveObserver(observer);
}
InkDrop::InkDrop() = default;
void InkDrop::NotifyInkDropAnimationStarted() {
for (InkDropObserver& observer : observers_)
observer.InkDropAnimationStarted();
}
void InkDrop::NotifyInkDropRippleAnimationEnded(InkDropState ink_drop_state) {
for (InkDropObserver& observer : observers_)
observer.InkDropRippleAnimationEnded(ink_drop_state);
}
InkDropContainerView::InkDropContainerView() {
// Ensure the container View is found as the EventTarget instead of this.
SetCanProcessEventsWithinSubtree(false);
}
BEGIN_METADATA(InkDropContainerView, views::View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop.cc | C++ | unknown | 5,048 |
// 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_ANIMATION_INK_DROP_H_
#define UI_VIEWS_ANIMATION_INK_DROP_H_
#include <memory>
#include "base/functional/callback.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/events/event_handler.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace views {
class InkDropHost;
class InkDropObserver;
class View;
// Base class that manages the lifetime and state of an ink drop ripple as
// well as visual hover state feedback.
class VIEWS_EXPORT InkDrop {
public:
InkDrop(const InkDrop&) = delete;
InkDrop& operator=(const InkDrop&) = delete;
virtual ~InkDrop();
// TODO(pbos): Make sure what's installed here implements InkDrop so that can
// be used as type instead of InkDropHost.
static void Install(View* host, std::unique_ptr<InkDropHost> ink_drop);
// Removes the InkDrop from `host`.
static void Remove(View* host);
// TODO(pbos): Make sure what's installed here implements InkDrop so that can
// be used as type instead of InkDropHost.
static const InkDropHost* Get(const View* host);
static InkDropHost* Get(View* host) {
return const_cast<InkDropHost*>(Get(const_cast<const View*>(host)));
}
// Create an InkDrop appropriate for the "square" InkDropRipple effect. This
// InkDrop hides when the ripple effect is active instead of layering
// underneath it.
static std::unique_ptr<InkDrop> CreateInkDropForSquareRipple(
InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false,
bool show_highlight_on_ripple = false);
// Configure `host` to use CreateInkDropForSquareRipple().
static void UseInkDropForSquareRipple(InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false,
bool show_highlight_on_ripple = false);
// Create an InkDrop appropriate for the "flood-fill" InkDropRipple effect.
// This InkDrop shows as a response to the ripple effect.
static std::unique_ptr<InkDrop> CreateInkDropForFloodFillRipple(
InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false,
bool show_highlight_on_ripple = true);
// Configure `host` to use CreateInkDropForFloodFillRipple().
static void UseInkDropForFloodFillRipple(
InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false,
bool show_highlight_on_ripple = true);
// Create an InkDrop whose highlight does not react to its ripple.
static std::unique_ptr<InkDrop> CreateInkDropWithoutAutoHighlight(
InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false);
// Configure `host` to use CreateInkDropWithoutAutoHighlight().
static void UseInkDropWithoutAutoHighlight(InkDropHost* host,
bool highlight_on_hover = true,
bool highlight_on_focus = false);
// Called by ink drop hosts when their size is changed.
virtual void HostSizeChanged(const gfx::Size& new_size) = 0;
// Called by ink drop hosts when their transform is changed.
virtual void HostTransformChanged(const gfx::Transform& new_transform) = 0;
// Gets the target state of the ink drop.
virtual InkDropState GetTargetInkDropState() const = 0;
// Animates from the current InkDropState to |ink_drop_state|.
virtual void AnimateToState(InkDropState ink_drop_state) = 0;
// Sets hover highlight fade animations to last for |duration|.
virtual void SetHoverHighlightFadeDuration(base::TimeDelta duration) = 0;
// Clears any set hover highlight fade durations and uses the default
// durations instead.
virtual void UseDefaultHoverHighlightFadeDuration() = 0;
// Immediately snaps the InkDropState to ACTIVATED and HIDDEN specifically.
// These are more specific implementations of the non-existent
// SnapToState(InkDropState) function are the only ones available because
// they were the only InkDropState that clients needed to skip animations
// for.
virtual void SnapToActivated() = 0;
virtual void SnapToHidden() = 0;
// Enables or disables the hover state.
virtual void SetHovered(bool is_hovered) = 0;
// Enables or disables the focus state.
virtual void SetFocused(bool is_focused) = 0;
// Returns true if the highlight animation is in the process of fading in or
// is visible.
virtual bool IsHighlightFadingInOrVisible() const = 0;
// Enables or disables the highlight when the target is hovered.
virtual void SetShowHighlightOnHover(bool show_highlight_on_hover) = 0;
// Enables or disables the highlight when the target is focused.
virtual void SetShowHighlightOnFocus(bool show_highlight_on_focus) = 0;
// Methods to add/remove observers for this object.
void AddObserver(InkDropObserver* observer);
void RemoveObserver(InkDropObserver* observer);
protected:
InkDrop();
// Notifes all of the observers that the animation has started.
void NotifyInkDropAnimationStarted();
// Notifies all of the observers that an animation to a state has ended.
void NotifyInkDropRippleAnimationEnded(InkDropState state);
private:
base::ObserverList<InkDropObserver>::Unchecked observers_;
};
// A View which can be used to parent ink drop layers. Typically this is used
// as a non-ancestor view to labels so that the labels can paint on an opaque
// canvas. This is used to avoid ugly text renderings when labels with subpixel
// rendering enabled are painted onto a non-opaque canvas.
// TODO(pbos): Replace with a function that returns unique_ptr<View>, this only
// calls SetProcessEventsWithinSubtree(false) right now.
class VIEWS_EXPORT InkDropContainerView : public View {
public:
METADATA_HEADER(InkDropContainerView);
InkDropContainerView();
InkDropContainerView(const InkDropContainerView&) = delete;
InkDropContainerView& operator=(const InkDropContainerView&) = delete;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop.h | C++ | unknown | 6,481 |
// 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/animation/ink_drop_animation_ended_reason.h"
#include <ostream>
#include "base/notreached.h"
namespace views {
std::string ToString(InkDropAnimationEndedReason reason) {
switch (reason) {
case InkDropAnimationEndedReason::SUCCESS:
return "SUCCESS";
case InkDropAnimationEndedReason::PRE_EMPTED:
return "PRE_EMPTED";
}
NOTREACHED_NORETURN();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_animation_ended_reason.cc | C++ | unknown | 559 |
// 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_ANIMATION_INK_DROP_ANIMATION_ENDED_REASON_H_
#define UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_ENDED_REASON_H_
#include <iosfwd>
#include <string>
#include "ui/views/views_export.h"
namespace views {
// Enumeration of the different reasons why an ink drop animation has finished.
enum class InkDropAnimationEndedReason {
// The animation was completed successfully.
SUCCESS,
// The animation was stopped prematurely before reaching its final state.
PRE_EMPTED
};
// Returns a human readable string for |reason|. Useful for logging.
VIEWS_EXPORT std::string ToString(InkDropAnimationEndedReason reason);
// This is declared here for use in gtest-based unit tests but is defined in
// the views_test_support target. Depend on that to use this in your unit test.
// This should not be used in production code - call ToString() instead.
void PrintTo(InkDropAnimationEndedReason reason, ::std::ostream* os);
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_ENDED_REASON_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_animation_ended_reason.h | C++ | unknown | 1,164 |
// 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/animation/ink_drop_event_handler.h"
#include <memory>
#include "build/build_config.h"
#include "ui/events/scoped_target_handler.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
bool InkDropStateIsVisible(InkDropState state) {
return state != InkDropState::HIDDEN && state != InkDropState::DEACTIVATED;
}
} // namespace
InkDropEventHandler::InkDropEventHandler(View* host_view, Delegate* delegate)
: target_handler_(
std::make_unique<ui::ScopedTargetHandler>(host_view, this)),
host_view_(host_view),
delegate_(delegate) {
observation_.Observe(host_view_.get());
}
InkDropEventHandler::~InkDropEventHandler() = default;
void InkDropEventHandler::AnimateToState(InkDropState state,
const ui::LocatedEvent* event) {
#if BUILDFLAG(IS_WIN)
// On Windows, don't initiate ink-drops for touch/gesture events.
// Additionally, certain event states should dismiss existing ink-drop
// animations. If the state is already other than HIDDEN, presumably from
// a mouse or keyboard event, then the state should be allowed. Conversely,
// if the requested state is ACTIVATED, then it should always be allowed.
if (event && (event->IsTouchEvent() || event->IsGestureEvent()) &&
delegate_->GetInkDrop()->GetTargetInkDropState() ==
InkDropState::HIDDEN &&
state != InkDropState::ACTIVATED) {
return;
}
#endif
last_ripple_triggering_event_.reset(
event ? event->Clone().release()->AsLocatedEvent() : nullptr);
// If no ink drop exists and we are not transitioning to a visible ink drop
// state the transition have no visual effect. The call to GetInkDrop() will
// lazily create the ink drop when called. Avoid creating the ink drop in
// these cases to prevent the creation of unnecessary layers.
if (delegate_->HasInkDrop() || InkDropStateIsVisible(state))
delegate_->GetInkDrop()->AnimateToState(state);
}
ui::LocatedEvent* InkDropEventHandler::GetLastRippleTriggeringEvent() const {
return last_ripple_triggering_event_.get();
}
void InkDropEventHandler::OnGestureEvent(ui::GestureEvent* event) {
if (!host_view_->GetEnabled() || !delegate_->SupportsGestureEvents())
return;
InkDropState current_ink_drop_state =
delegate_->GetInkDrop()->GetTargetInkDropState();
InkDropState ink_drop_state = InkDropState::HIDDEN;
switch (event->type()) {
case ui::ET_GESTURE_TAP_DOWN:
if (current_ink_drop_state == InkDropState::ACTIVATED)
return;
ink_drop_state = InkDropState::ACTION_PENDING;
// The ui::ET_GESTURE_TAP_DOWN event needs to be marked as handled so
// that subsequent events for the gesture are sent to |this|.
event->SetHandled();
break;
case ui::ET_GESTURE_LONG_PRESS:
#ifdef OHOS_DRAG_DROP
case ui::ET_GESTURE_DRAG_LONG_PRESS:
#endif
if (current_ink_drop_state == InkDropState::ACTIVATED)
return;
ink_drop_state = InkDropState::ALTERNATE_ACTION_PENDING;
break;
case ui::ET_GESTURE_LONG_TAP:
ink_drop_state = InkDropState::ALTERNATE_ACTION_TRIGGERED;
break;
case ui::ET_GESTURE_END:
case ui::ET_GESTURE_SCROLL_BEGIN:
case ui::ET_GESTURE_TAP_CANCEL:
if (current_ink_drop_state == InkDropState::ACTIVATED)
return;
ink_drop_state = InkDropState::HIDDEN;
break;
default:
return;
}
if (ink_drop_state == InkDropState::HIDDEN &&
(current_ink_drop_state == InkDropState::ACTION_TRIGGERED ||
current_ink_drop_state == InkDropState::ALTERNATE_ACTION_TRIGGERED ||
current_ink_drop_state == InkDropState::DEACTIVATED ||
current_ink_drop_state == InkDropState::HIDDEN)) {
// These InkDropStates automatically transition to the HIDDEN state so we
// don't make an explicit call. Explicitly animating to HIDDEN in this
// case would prematurely pre-empt these animations.
return;
}
AnimateToState(ink_drop_state, event);
}
void InkDropEventHandler::OnMouseEvent(ui::MouseEvent* event) {
switch (event->type()) {
case ui::ET_MOUSE_ENTERED:
delegate_->GetInkDrop()->SetHovered(true);
break;
case ui::ET_MOUSE_EXITED:
delegate_->GetInkDrop()->SetHovered(false);
break;
case ui::ET_MOUSE_DRAGGED:
delegate_->GetInkDrop()->SetHovered(
host_view_->GetLocalBounds().Contains(event->location()));
break;
default:
break;
}
}
base::StringPiece InkDropEventHandler::GetLogContext() const {
return "InkDropEventHandler";
}
void InkDropEventHandler::OnViewVisibilityChanged(View* observed_view,
View* starting_view) {
DCHECK_EQ(host_view_, observed_view);
// A View is *actually* visible if its visible flag is set, all its ancestors'
// visible flags are set, it's in a Widget, and the Widget is
// visible. |View::IsDrawn()| captures the first two conditions.
const bool is_visible = host_view_->IsDrawn() && host_view_->GetWidget() &&
host_view_->GetWidget()->IsVisible();
if (!is_visible && delegate_->HasInkDrop()) {
delegate_->GetInkDrop()->AnimateToState(InkDropState::HIDDEN);
delegate_->GetInkDrop()->SetHovered(false);
}
}
void InkDropEventHandler::OnViewHierarchyChanged(
View* observed_view,
const ViewHierarchyChangedDetails& details) {
DCHECK_EQ(host_view_, observed_view);
// If we're being removed hide the ink-drop so if we're highlighted now the
// highlight won't be active if we're added back again.
if (!details.is_add && details.child == host_view_ &&
delegate_->HasInkDrop()) {
delegate_->GetInkDrop()->SnapToHidden();
delegate_->GetInkDrop()->SetHovered(false);
}
}
void InkDropEventHandler::OnViewBoundsChanged(View* observed_view) {
DCHECK_EQ(host_view_, observed_view);
if (delegate_->HasInkDrop())
delegate_->GetInkDrop()->HostSizeChanged(host_view_->size());
}
void InkDropEventHandler::OnViewFocused(View* observed_view) {
DCHECK_EQ(host_view_, observed_view);
delegate_->GetInkDrop()->SetFocused(true);
}
void InkDropEventHandler::OnViewBlurred(View* observed_view) {
DCHECK_EQ(host_view_, observed_view);
delegate_->GetInkDrop()->SetFocused(false);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_event_handler.cc | C++ | unknown | 6,533 |
// 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_ANIMATION_INK_DROP_EVENT_HANDLER_H_
#define UI_VIEWS_ANIMATION_INK_DROP_EVENT_HANDLER_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/strings/string_piece.h"
#include "ui/events/event_handler.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/views_export.h"
namespace ui {
class LocatedEvent;
class ScopedTargetHandler;
} // namespace ui
namespace views {
class InkDrop;
enum class InkDropState;
struct ViewHierarchyChangedDetails;
// This class handles ink-drop changes due to events on its host.
class VIEWS_EXPORT InkDropEventHandler : public ui::EventHandler,
public ViewObserver {
public:
// Delegate class that allows InkDropEventHandler to be used with InkDrops
// that are hosted in multiple ways.
class Delegate {
public:
// Gets the InkDrop (or stub) that should react to incoming events.
virtual InkDrop* GetInkDrop() = 0;
virtual bool HasInkDrop() const = 0;
// Returns true if gesture events should affect the InkDrop.
virtual bool SupportsGestureEvents() const = 0;
};
InkDropEventHandler(View* host_view, Delegate* delegate);
InkDropEventHandler(const InkDropEventHandler&) = delete;
InkDropEventHandler& operator=(const InkDropEventHandler&) = delete;
~InkDropEventHandler() override;
void AnimateToState(InkDropState state, const ui::LocatedEvent* event);
ui::LocatedEvent* GetLastRippleTriggeringEvent() const;
private:
// ui::EventHandler:
void OnGestureEvent(ui::GestureEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
base::StringPiece GetLogContext() const override;
// ViewObserver:
void OnViewVisibilityChanged(View* observed_view,
View* starting_view) override;
void OnViewHierarchyChanged(
View* observed_view,
const ViewHierarchyChangedDetails& details) override;
void OnViewBoundsChanged(View* observed_view) override;
void OnViewFocused(View* observed_view) override;
void OnViewBlurred(View* observed_view) override;
// Allows |this| to handle all GestureEvents on |host_view_|.
std::unique_ptr<ui::ScopedTargetHandler> target_handler_;
// The host view.
const raw_ptr<View> host_view_;
// Delegate used to get the InkDrop, etc.
const raw_ptr<Delegate> delegate_;
// The last user Event to trigger an InkDrop-ripple animation.
std::unique_ptr<ui::LocatedEvent> last_ripple_triggering_event_;
base::ScopedObservation<View, ViewObserver> observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_EVENT_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_event_handler.h | C++ | unknown | 2,835 |
// 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/animation/ink_drop_highlight.h"
#include <memory>
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/ink_drop_highlight_observer.h"
#include "ui/views/animation/ink_drop_painted_layer_delegates.h"
#include "ui/views/animation/ink_drop_util.h"
namespace views {
namespace {
// The opacity of the highlight when it is not visible.
constexpr float kHiddenOpacity = 0.0f;
} // namespace
std::string ToString(InkDropHighlight::AnimationType animation_type) {
switch (animation_type) {
case InkDropHighlight::AnimationType::kFadeIn:
return std::string("FADE_IN");
case InkDropHighlight::AnimationType::kFadeOut:
return std::string("FADE_OUT");
}
}
InkDropHighlight::InkDropHighlight(
const gfx::PointF& center_point,
std::unique_ptr<BasePaintedLayerDelegate> layer_delegate)
: center_point_(center_point),
layer_delegate_(std::move(layer_delegate)),
layer_(std::make_unique<ui::Layer>()) {
const gfx::RectF painted_bounds = layer_delegate_->GetPaintedBounds();
size_ = painted_bounds.size();
layer_->SetBounds(gfx::ToEnclosingRect(painted_bounds));
layer_->SetFillsBoundsOpaquely(false);
layer_->set_delegate(layer_delegate_.get());
layer_->SetVisible(false);
layer_->SetMasksToBounds(false);
layer_->SetName("InkDropHighlight:layer");
}
InkDropHighlight::InkDropHighlight(const gfx::SizeF& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color)
: InkDropHighlight(
center_point,
std::make_unique<RoundedRectangleLayerDelegate>(color,
size,
corner_radius)) {
layer_->SetOpacity(visible_opacity_);
}
InkDropHighlight::InkDropHighlight(const gfx::Size& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color)
: InkDropHighlight(gfx::SizeF(size), corner_radius, center_point, color) {}
InkDropHighlight::InkDropHighlight(const gfx::SizeF& size, SkColor base_color)
: size_(size), layer_(std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR)) {
layer_->SetColor(base_color);
layer_->SetBounds(gfx::Rect(gfx::ToRoundedSize(size)));
layer_->SetVisible(false);
layer_->SetMasksToBounds(false);
layer_->SetOpacity(visible_opacity_);
layer_->SetName("InkDropHighlight:solid_color_layer");
}
InkDropHighlight::~InkDropHighlight() {
// Explicitly aborting all the animations ensures all callbacks are invoked
// while this instance still exists.
animation_abort_handle_.reset();
}
bool InkDropHighlight::IsFadingInOrVisible() const {
return last_animation_initiated_was_fade_in_;
}
void InkDropHighlight::FadeIn(const base::TimeDelta& duration) {
layer_->SetOpacity(kHiddenOpacity);
layer_->SetVisible(true);
AnimateFade(AnimationType::kFadeIn, duration);
}
void InkDropHighlight::FadeOut(const base::TimeDelta& duration) {
AnimateFade(AnimationType::kFadeOut, duration);
}
test::InkDropHighlightTestApi* InkDropHighlight::GetTestApi() {
return nullptr;
}
void InkDropHighlight::AnimateFade(AnimationType animation_type,
const base::TimeDelta& duration) {
last_animation_initiated_was_fade_in_ =
animation_type == AnimationType::kFadeIn;
layer_->SetTransform(CalculateTransform());
const base::TimeDelta effective_duration =
gfx::Animation::ShouldRenderRichAnimation() ? duration
: base::TimeDelta();
const float opacity = animation_type == AnimationType::kFadeIn
? visible_opacity_
: kHiddenOpacity;
views::AnimationBuilder builder;
if (effective_duration.is_positive())
animation_abort_handle_ = builder.GetAbortHandle();
builder
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.OnStarted(base::BindOnce(&InkDropHighlight::AnimationStartedCallback,
base::Unretained(this), animation_type))
.OnEnded(base::BindOnce(&InkDropHighlight::AnimationEndedCallback,
base::Unretained(this), animation_type,
InkDropAnimationEndedReason::SUCCESS))
.OnAborted(base::BindOnce(&InkDropHighlight::AnimationEndedCallback,
base::Unretained(this), animation_type,
InkDropAnimationEndedReason::PRE_EMPTED))
.Once()
.SetDuration(effective_duration)
.SetOpacity(layer_.get(), opacity, gfx::Tween::EASE_IN_OUT);
}
gfx::Transform InkDropHighlight::CalculateTransform() const {
gfx::Transform transform;
// No transform needed for a solid color layer.
if (!layer_delegate_)
return transform;
transform.Translate(center_point_.x(), center_point_.y());
gfx::Vector2dF layer_offset = layer_delegate_->GetCenteringOffset();
transform.Translate(-layer_offset.x(), -layer_offset.y());
// Add subpixel correction to the transform.
transform.PostConcat(
GetTransformSubpixelCorrection(transform, layer_->device_scale_factor()));
return transform;
}
void InkDropHighlight::AnimationStartedCallback(AnimationType animation_type) {
if (observer_)
observer_->AnimationStarted(animation_type);
}
void InkDropHighlight::AnimationEndedCallback(
AnimationType animation_type,
InkDropAnimationEndedReason reason) {
// AnimationEndedCallback() may be invoked when this is being destroyed and
// |layer_| may be null.
if (animation_type == AnimationType::kFadeOut && layer_)
layer_->SetVisible(false);
if (observer_)
observer_->AnimationEnded(animation_type, reason);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_highlight.cc | C++ | unknown | 6,383 |
// 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_ANIMATION_INK_DROP_HIGHLIGHT_H_
#define UI_VIEWS_ANIMATION_INK_DROP_HIGHLIGHT_H_
#include <iosfwd>
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/animation_abort_handle.h"
#include "ui/views/animation/ink_drop_animation_ended_reason.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
} // namespace ui
namespace views {
namespace test {
class InkDropHighlightTestApi;
} // namespace test
class BasePaintedLayerDelegate;
class InkDropHighlightObserver;
// Manages fade in/out animations for a Layer that is used to provide visual
// feedback on ui::Views for highlight states (e.g. mouse hover, keyboard
// focus).
class VIEWS_EXPORT InkDropHighlight {
public:
enum class AnimationType { kFadeIn, kFadeOut };
// Creates a highlight with a specified painter.
InkDropHighlight(const gfx::PointF& center_point,
std::unique_ptr<BasePaintedLayerDelegate> layer_delegate);
// Creates a highlight that paints a partially transparent roundrect with
// color |color|.
InkDropHighlight(const gfx::SizeF& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color);
// Deprecated version of the above that takes a Size instead of SizeF.
// TODO(estade): remove. See crbug.com/706228
InkDropHighlight(const gfx::Size& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color);
// Creates a highlight that is drawn with a solid color layer. It's shape will
// be determined by the mask or clip applied to the parent layer. Note that
// this still uses the default highlight opacity. Users who supply a
// |base_color| with alpha will also want to call set_visible_opacity(1.f);.
InkDropHighlight(const gfx::SizeF& size, SkColor base_color);
InkDropHighlight(const InkDropHighlight&) = delete;
InkDropHighlight& operator=(const InkDropHighlight&) = delete;
virtual ~InkDropHighlight();
void set_observer(InkDropHighlightObserver* observer) {
observer_ = observer;
}
void set_visible_opacity(float visible_opacity) {
visible_opacity_ = visible_opacity;
}
// Returns true if the highlight animation is either in the process of fading
// in or is fully visible.
bool IsFadingInOrVisible() const;
// Fades in the highlight visual over the given |duration|.
void FadeIn(const base::TimeDelta& duration);
// Fades out the highlight visual over the given |duration|.
void FadeOut(const base::TimeDelta& duration);
// The root Layer that can be added in to a Layer tree.
ui::Layer* layer() { return layer_.get(); }
// Returns a test api to access internals of this. Default implmentations
// should return nullptr and test specific subclasses can override to return
// an instance.
virtual test::InkDropHighlightTestApi* GetTestApi();
private:
friend class test::InkDropHighlightTestApi;
// Animates a fade in/out as specified by |animation_type| over the given
// |duration|.
void AnimateFade(AnimationType animation_type,
const base::TimeDelta& duration);
// Calculates the Transform to apply to |layer_|.
gfx::Transform CalculateTransform() const;
// The callback that will be invoked when a fade in/out animation is started.
void AnimationStartedCallback(AnimationType animation_type);
// The callback that will be invoked when a fade in/out animation is complete.
void AnimationEndedCallback(AnimationType animation_type,
InkDropAnimationEndedReason reason);
// The size of the highlight shape when fully faded in.
gfx::SizeF size_;
// The center point of the highlight shape in the parent Layer's coordinate
// space.
gfx::PointF center_point_;
// The opacity for the fully visible state of the highlight.
float visible_opacity_ = 0.128f;
// True if the last animation to be initiated was a kFadeIn, and false
// otherwise.
bool last_animation_initiated_was_fade_in_ = false;
// The LayerDelegate that paints the highlight |layer_|. Null if |layer_| is a
// solid color layer.
std::unique_ptr<BasePaintedLayerDelegate> layer_delegate_;
// The visual highlight layer.
std::unique_ptr<ui::Layer> layer_;
std::unique_ptr<AnimationAbortHandle> animation_abort_handle_;
raw_ptr<InkDropHighlightObserver> observer_ = nullptr;
};
// Returns a human readable string for |animation_type|. Useful for logging.
VIEWS_EXPORT std::string ToString(
InkDropHighlight::AnimationType animation_type);
// This is declared here for use in gtest-based unit tests but is defined in
// the views_test_support target. Depend on that to use this in your unit test.
// This should not be used in production code - call ToString() instead.
void PrintTo(InkDropHighlight::AnimationType animation_type,
::std::ostream* os);
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_HIGHLIGHT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_highlight.h | C++ | unknown | 5,438 |
// 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_ANIMATION_INK_DROP_HIGHLIGHT_OBSERVER_H_
#define UI_VIEWS_ANIMATION_INK_DROP_HIGHLIGHT_OBSERVER_H_
#include "ui/views/animation/ink_drop_animation_ended_reason.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/views_export.h"
namespace views {
// Observer to attach to an InkDropHighlight animation.
class VIEWS_EXPORT InkDropHighlightObserver {
public:
InkDropHighlightObserver(const InkDropHighlightObserver&) = delete;
InkDropHighlightObserver& operator=(const InkDropHighlightObserver&) = delete;
// An animation for the given |animation_type| has started.
virtual void AnimationStarted(
InkDropHighlight::AnimationType animation_type) = 0;
// Notifies the observer that an animation for the given |animation_type| has
// finished and the reason for completion is given by |reason|. If |reason| is
// SUCCESS then the animation has progressed to its final frame however if
// |reason| is |PRE_EMPTED| then the animation was stopped before its final
// frame.
virtual void AnimationEnded(InkDropHighlight::AnimationType animation_type,
InkDropAnimationEndedReason reason) = 0;
protected:
InkDropHighlightObserver() = default;
virtual ~InkDropHighlightObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_HIGHLIGHT_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_highlight_observer.h | C++ | unknown | 1,516 |
// 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/animation/ink_drop_highlight.h"
#include <cmath>
#include <memory>
#include <utility>
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/test/ink_drop_highlight_test_api.h"
#include "ui/views/animation/test/test_ink_drop_highlight_observer.h"
namespace views::test {
class InkDropHighlightTest : public testing::Test {
public:
InkDropHighlightTest();
InkDropHighlightTest(const InkDropHighlightTest&) = delete;
InkDropHighlightTest& operator=(const InkDropHighlightTest&) = delete;
~InkDropHighlightTest() override;
protected:
InkDropHighlight* ink_drop_highlight() { return ink_drop_highlight_.get(); }
InkDropHighlightTestApi* test_api() { return test_api_.get(); }
// Observer of the test target.
TestInkDropHighlightObserver* observer() { return &observer_; }
// Initializes |ink_drop_highlight_| and attaches |test_api_| and |observer_|
// to the new instance.
void InitHighlight(std::unique_ptr<InkDropHighlight> new_highlight);
// Destroys the |ink_drop_highlight_| and the attached |test_api_|.
void DestroyHighlight();
private:
// The test target.
std::unique_ptr<InkDropHighlight> ink_drop_highlight_;
// Allows privileged access to the the |ink_drop_highlight_|.
std::unique_ptr<InkDropHighlightTestApi> test_api_;
// Observer of the test target.
TestInkDropHighlightObserver observer_;
std::unique_ptr<base::AutoReset<gfx::Animation::RichAnimationRenderMode>>
animation_mode_reset_;
};
InkDropHighlightTest::InkDropHighlightTest()
: animation_mode_reset_(gfx::AnimationTestApi::SetRichAnimationRenderMode(
gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED)) {
InitHighlight(std::make_unique<InkDropHighlight>(
gfx::Size(10, 10), 3, gfx::PointF(), SK_ColorBLACK));
}
InkDropHighlightTest::~InkDropHighlightTest() {
// Destory highlight to make sure it is destroyed before the observer.
DestroyHighlight();
}
void InkDropHighlightTest::InitHighlight(
std::unique_ptr<InkDropHighlight> new_highlight) {
ink_drop_highlight_ = std::move(new_highlight);
test_api_ =
std::make_unique<InkDropHighlightTestApi>(ink_drop_highlight_.get());
test_api()->SetDisableAnimationTimers(true);
ink_drop_highlight()->set_observer(&observer_);
}
void InkDropHighlightTest::DestroyHighlight() {
test_api_.reset();
ink_drop_highlight_.reset();
}
TEST_F(InkDropHighlightTest, InitialStateAfterConstruction) {
EXPECT_FALSE(ink_drop_highlight()->IsFadingInOrVisible());
}
TEST_F(InkDropHighlightTest, IsHighlightedStateTransitions) {
ink_drop_highlight()->FadeIn(base::Seconds(1));
EXPECT_TRUE(ink_drop_highlight()->IsFadingInOrVisible());
test_api()->CompleteAnimations();
EXPECT_TRUE(ink_drop_highlight()->IsFadingInOrVisible());
ink_drop_highlight()->FadeOut(base::Seconds(1));
EXPECT_FALSE(ink_drop_highlight()->IsFadingInOrVisible());
test_api()->CompleteAnimations();
EXPECT_FALSE(ink_drop_highlight()->IsFadingInOrVisible());
}
TEST_F(InkDropHighlightTest, VerifyObserversAreNotified) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_highlight()->FadeIn(base::Seconds(1));
EXPECT_EQ(1, observer()->last_animation_started_ordinal());
EXPECT_FALSE(observer()->AnimationHasEnded());
test_api()->CompleteAnimations();
EXPECT_TRUE(observer()->AnimationHasEnded());
EXPECT_EQ(2, observer()->last_animation_ended_ordinal());
}
TEST_F(InkDropHighlightTest,
VerifyObserversAreNotifiedWithCorrectAnimationType) {
ink_drop_highlight()->FadeIn(base::Seconds(1));
EXPECT_TRUE(observer()->AnimationHasStarted());
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeIn,
observer()->last_animation_started_context());
test_api()->CompleteAnimations();
EXPECT_TRUE(observer()->AnimationHasEnded());
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeIn,
observer()->last_animation_started_context());
ink_drop_highlight()->FadeOut(base::Seconds(1));
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeOut,
observer()->last_animation_started_context());
test_api()->CompleteAnimations();
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeOut,
observer()->last_animation_started_context());
}
TEST_F(InkDropHighlightTest, VerifyObserversAreNotifiedOfSuccessfulAnimations) {
ink_drop_highlight()->FadeIn(base::Seconds(1));
test_api()->CompleteAnimations();
EXPECT_EQ(2, observer()->last_animation_ended_ordinal());
EXPECT_EQ(InkDropAnimationEndedReason::SUCCESS,
observer()->last_animation_ended_reason());
}
TEST_F(InkDropHighlightTest, VerifyObserversAreNotifiedOfPreemptedAnimations) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_highlight()->FadeIn(base::Seconds(1));
ink_drop_highlight()->FadeOut(base::Seconds(1));
EXPECT_EQ(2, observer()->last_animation_ended_ordinal());
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeIn,
observer()->last_animation_ended_context());
EXPECT_EQ(InkDropAnimationEndedReason::PRE_EMPTED,
observer()->last_animation_ended_reason());
}
// Confirms there is no crash.
TEST_F(InkDropHighlightTest, NullObserverIsSafe) {
ink_drop_highlight()->set_observer(nullptr);
ink_drop_highlight()->FadeIn(base::Seconds(1));
test_api()->CompleteAnimations();
ink_drop_highlight()->FadeOut(base::Milliseconds(0));
test_api()->CompleteAnimations();
EXPECT_FALSE(ink_drop_highlight()->IsFadingInOrVisible());
}
// Verify animations are aborted during deletion and the
// InkDropHighlightObservers are notified.
TEST_F(InkDropHighlightTest, AnimationsAbortedDuringDeletion) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_highlight()->FadeIn(base::Seconds(1));
DestroyHighlight();
EXPECT_EQ(1, observer()->last_animation_started_ordinal());
EXPECT_EQ(2, observer()->last_animation_ended_ordinal());
EXPECT_EQ(InkDropHighlight::AnimationType::kFadeIn,
observer()->last_animation_ended_context());
EXPECT_EQ(InkDropAnimationEndedReason::PRE_EMPTED,
observer()->last_animation_ended_reason());
}
// Confirms a zero sized highlight doesn't crash.
TEST_F(InkDropHighlightTest, AnimatingAZeroSizeHighlight) {
InitHighlight(std::make_unique<InkDropHighlight>(
gfx::Size(0, 0), 3, gfx::PointF(), SK_ColorBLACK));
ink_drop_highlight()->FadeOut(base::Milliseconds(0));
}
TEST_F(InkDropHighlightTest, TransformIsPixelAligned) {
constexpr float kEpsilon = 0.001f;
constexpr gfx::Size kHighlightSize(10, 10);
InitHighlight(std::make_unique<InkDropHighlight>(
kHighlightSize, 3, gfx::PointF(3.5f, 3.5f), SK_ColorYELLOW));
for (auto dsf : {1.25, 1.33, 1.5, 1.6, 1.75, 1.8, 2.25}) {
SCOPED_TRACE(testing::Message()
<< std::endl
<< "Device Scale Factor: " << dsf << std::endl);
ink_drop_highlight()->layer()->OnDeviceScaleFactorChanged(dsf);
gfx::Transform transform = test_api()->CalculateTransform();
gfx::PointF transformed_layer_origin = transform.MapPoint(
gfx::PointF(ink_drop_highlight()->layer()->bounds().origin()));
// Apply device scale factor to get the final offset.
gfx::Transform dsf_transform;
dsf_transform.Scale(dsf, dsf);
transformed_layer_origin = dsf_transform.MapPoint(transformed_layer_origin);
EXPECT_NEAR(transformed_layer_origin.x(),
std::round(transformed_layer_origin.x()), kEpsilon);
EXPECT_NEAR(transformed_layer_origin.y(),
std::round(transformed_layer_origin.y()), kEpsilon);
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_highlight_unittest.cc | C++ | unknown | 8,410 |
// 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/animation/ink_drop_host.h"
#include <utility>
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_provider.h"
#include "ui/events/event.h"
#include "ui/events/scoped_target_handler.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/size_conversions.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_mask.h"
#include "ui/views/animation/ink_drop_stub.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/view_class_properties.h"
namespace views {
// static
constexpr gfx::Size InkDropHost::kDefaultSquareInkDropSize;
InkDropHost::InkDropHostEventHandlerDelegate::InkDropHostEventHandlerDelegate(
InkDropHost* ink_drop_host)
: ink_drop_host_(ink_drop_host) {}
bool InkDropHost::InkDropHostEventHandlerDelegate::HasInkDrop() const {
return ink_drop_host_->HasInkDrop();
}
InkDrop* InkDropHost::InkDropHostEventHandlerDelegate::GetInkDrop() {
return ink_drop_host_->GetInkDrop();
}
bool InkDropHost::InkDropHostEventHandlerDelegate::SupportsGestureEvents()
const {
return ink_drop_host_->ink_drop_mode_ == InkDropMode::ON;
}
InkDropHost::ViewLayerTransformObserver::ViewLayerTransformObserver(
InkDropHost* ink_drop_host,
View* host_view)
: ink_drop_host_(ink_drop_host) {
observation_.Observe(host_view);
}
InkDropHost::ViewLayerTransformObserver::~ViewLayerTransformObserver() =
default;
void InkDropHost::ViewLayerTransformObserver::OnViewLayerTransformed(
View* observed_view) {
// Notify the ink drop that we have transformed so it can adapt
// accordingly.
if (ink_drop_host_->HasInkDrop()) {
ink_drop_host_->GetInkDrop()->HostTransformChanged(
observed_view->GetTransform());
}
}
InkDropHost::InkDropHost(View* view)
: host_view_(view),
host_view_transform_observer_(this, view),
ink_drop_event_handler_delegate_(this),
ink_drop_event_handler_(view, &ink_drop_event_handler_delegate_) {}
InkDropHost::~InkDropHost() = default;
std::unique_ptr<InkDrop> InkDropHost::CreateInkDrop() {
if (create_ink_drop_callback_) {
return create_ink_drop_callback_.Run();
}
return InkDrop::CreateInkDropForFloodFillRipple(this);
}
void InkDropHost::SetCreateInkDropCallback(
base::RepeatingCallback<std::unique_ptr<InkDrop>()> callback) {
create_ink_drop_callback_ = std::move(callback);
}
std::unique_ptr<InkDropRipple> InkDropHost::CreateInkDropRipple() const {
if (create_ink_drop_ripple_callback_) {
return create_ink_drop_ripple_callback_.Run();
}
return std::make_unique<views::FloodFillInkDropRipple>(
InkDrop::Get(host_view_), host_view_->size(), gfx::Insets(),
GetInkDropCenterBasedOnLastEvent(), GetBaseColor(), GetVisibleOpacity());
}
void InkDropHost::SetCreateRippleCallback(
base::RepeatingCallback<std::unique_ptr<InkDropRipple>()> callback) {
create_ink_drop_ripple_callback_ = std::move(callback);
}
gfx::Point InkDropHost::GetInkDropCenterBasedOnLastEvent() const {
return GetEventHandler()->GetLastRippleTriggeringEvent()
? GetEventHandler()->GetLastRippleTriggeringEvent()->location()
: host_view_->GetMirroredRect(host_view_->GetContentsBounds())
.CenterPoint();
}
std::unique_ptr<InkDropHighlight> InkDropHost::CreateInkDropHighlight() const {
if (create_ink_drop_highlight_callback_) {
return create_ink_drop_highlight_callback_.Run();
}
auto highlight = std::make_unique<views::InkDropHighlight>(
host_view_->size(), 0,
gfx::RectF(host_view_->GetMirroredRect(host_view_->GetLocalBounds()))
.CenterPoint(),
GetBaseColor());
// TODO(pbos): Once |ink_drop_highlight_opacity_| is either always set or
// callers are using the default InkDropHighlight value then make this a
// constructor argument to InkDropHighlight.
if (ink_drop_highlight_opacity_) {
highlight->set_visible_opacity(*ink_drop_highlight_opacity_);
}
return highlight;
}
void InkDropHost::SetCreateHighlightCallback(
base::RepeatingCallback<std::unique_ptr<InkDropHighlight>()> callback) {
create_ink_drop_highlight_callback_ = std::move(callback);
}
std::unique_ptr<views::InkDropMask> InkDropHost::CreateInkDropMask() const {
if (create_ink_drop_mask_callback_) {
return create_ink_drop_mask_callback_.Run();
}
return std::make_unique<views::PathInkDropMask>(host_view_->size(),
GetHighlightPath(host_view_));
}
void InkDropHost::SetCreateMaskCallback(
base::RepeatingCallback<std::unique_ptr<InkDropMask>()> callback) {
create_ink_drop_mask_callback_ = std::move(callback);
}
SkColor InkDropHost::GetBaseColor() const {
if (absl::holds_alternative<ui::ColorId>(ink_drop_base_color_)) {
ui::ColorProvider* color_provider = host_view_->GetColorProvider();
CHECK(color_provider);
return color_provider->GetColor(
absl::get<ui::ColorId>(ink_drop_base_color_));
}
if (absl::holds_alternative<SkColor>(ink_drop_base_color_)) {
return absl::get<SkColor>(ink_drop_base_color_);
}
return absl::get<base::RepeatingCallback<SkColor()>>(ink_drop_base_color_)
.Run();
}
void InkDropHost::SetBaseColor(SkColor color) {
ink_drop_base_color_ = color;
}
void InkDropHost::SetBaseColorId(ui::ColorId color_id) {
ink_drop_base_color_ = color_id;
}
void InkDropHost::SetBaseColorCallback(
base::RepeatingCallback<SkColor()> callback) {
CHECK(callback);
ink_drop_base_color_ = std::move(callback);
}
void InkDropHost::SetMode(InkDropMode ink_drop_mode) {
ink_drop_mode_ = ink_drop_mode;
ink_drop_.reset();
}
InkDropHost::InkDropMode InkDropHost::GetMode() const {
return ink_drop_mode_;
}
void InkDropHost::SetLayerRegion(LayerRegion region) {
layer_region_ = region;
ink_drop_.reset();
}
LayerRegion InkDropHost::GetLayerRegion() const {
return layer_region_;
}
void InkDropHost::SetVisibleOpacity(float visible_opacity) {
if (visible_opacity == ink_drop_visible_opacity_) {
return;
}
ink_drop_visible_opacity_ = visible_opacity;
}
float InkDropHost::GetVisibleOpacity() const {
return ink_drop_visible_opacity_;
}
void InkDropHost::SetHighlightOpacity(absl::optional<float> opacity) {
if (opacity == ink_drop_highlight_opacity_) {
return;
}
ink_drop_highlight_opacity_ = opacity;
}
void InkDropHost::SetSmallCornerRadius(int small_radius) {
if (small_radius == ink_drop_small_corner_radius_) {
return;
}
ink_drop_small_corner_radius_ = small_radius;
}
int InkDropHost::GetSmallCornerRadius() const {
return ink_drop_small_corner_radius_;
}
void InkDropHost::SetLargeCornerRadius(int large_radius) {
if (large_radius == ink_drop_large_corner_radius_) {
return;
}
ink_drop_large_corner_radius_ = large_radius;
}
int InkDropHost::GetLargeCornerRadius() const {
return ink_drop_large_corner_radius_;
}
void InkDropHost::AnimateToState(InkDropState state,
const ui::LocatedEvent* event) {
GetEventHandler()->AnimateToState(state, event);
}
bool InkDropHost::HasInkDrop() const {
return !!ink_drop_;
}
InkDrop* InkDropHost::GetInkDrop() {
if (!ink_drop_) {
if (ink_drop_mode_ == InkDropMode::OFF) {
ink_drop_ = std::make_unique<InkDropStub>();
} else {
ink_drop_ = CreateInkDrop();
}
}
return ink_drop_.get();
}
bool InkDropHost::GetHighlighted() const {
return ink_drop_ && ink_drop_->IsHighlightFadingInOrVisible();
}
base::CallbackListSubscription InkDropHost::AddHighlightedChangedCallback(
base::RepeatingClosure callback) {
return highlighted_changed_callbacks_.Add(std::move(callback));
}
void InkDropHost::OnInkDropHighlightedChanged() {
highlighted_changed_callbacks_.Notify();
}
void InkDropHost::AddInkDropLayer(ui::Layer* ink_drop_layer) {
// If a clip is provided, use that as it is more performant than a mask.
if (!AddInkDropClip(ink_drop_layer)) {
InstallInkDropMask(ink_drop_layer);
}
host_view_->AddLayerToRegion(ink_drop_layer, layer_region_);
}
void InkDropHost::RemoveInkDropLayer(ui::Layer* ink_drop_layer) {
host_view_->RemoveLayerFromRegions(ink_drop_layer);
// Remove clipping.
ink_drop_layer->SetClipRect(gfx::Rect());
ink_drop_layer->SetRoundedCornerRadius(gfx::RoundedCornersF(0.f));
// Layers safely handle destroying a mask layer before the masked layer.
ink_drop_mask_.reset();
}
// static
gfx::Size InkDropHost::GetLargeSize(gfx::Size small_size) {
constexpr float kLargeInkDropScale = 1.333f;
return gfx::ScaleToCeiledSize(small_size, kLargeInkDropScale);
}
std::unique_ptr<InkDropRipple> InkDropHost::CreateSquareRipple(
const gfx::Point& center_point,
const gfx::Size& size) const {
auto ripple = std::make_unique<SquareInkDropRipple>(
InkDrop::Get(host_view_), GetLargeSize(size),
ink_drop_large_corner_radius_, size, ink_drop_small_corner_radius_,
center_point, GetBaseColor(), GetVisibleOpacity());
return ripple;
}
const InkDropEventHandler* InkDropHost::GetEventHandler() const {
return &ink_drop_event_handler_;
}
InkDropEventHandler* InkDropHost::GetEventHandler() {
return const_cast<InkDropEventHandler*>(
const_cast<const InkDropHost*>(this)->GetEventHandler());
}
bool InkDropHost::AddInkDropClip(ui::Layer* ink_drop_layer) {
absl::optional<gfx::RRectF> clipping_data =
HighlightPathGenerator::GetRoundRectForView(host_view_);
if (!clipping_data) {
return false;
}
ink_drop_layer->SetClipRect(gfx::ToEnclosingRect(clipping_data->rect()));
auto get_corner_radii =
[&clipping_data](gfx::RRectF::Corner corner) -> float {
return clipping_data.value().GetCornerRadii(corner).x();
};
gfx::RoundedCornersF rounded_corners;
rounded_corners.set_upper_left(
get_corner_radii(gfx::RRectF::Corner::kUpperLeft));
rounded_corners.set_upper_right(
get_corner_radii(gfx::RRectF::Corner::kUpperRight));
rounded_corners.set_lower_right(
get_corner_radii(gfx::RRectF::Corner::kLowerRight));
rounded_corners.set_lower_left(
get_corner_radii(gfx::RRectF::Corner::kLowerLeft));
ink_drop_layer->SetRoundedCornerRadius(rounded_corners);
ink_drop_layer->SetIsFastRoundedCorner(true);
return true;
}
void InkDropHost::InstallInkDropMask(ui::Layer* ink_drop_layer) {
ink_drop_mask_ = CreateInkDropMask();
DCHECK(ink_drop_mask_);
ink_drop_layer->SetMaskLayer(ink_drop_mask_->layer());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_host.cc | C++ | unknown | 10,978 |
// 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_ANIMATION_INK_DROP_HOST_H_
#define UI_VIEWS_ANIMATION_INK_DROP_HOST_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop_event_handler.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
namespace ui {
class Layer;
class LocatedEvent;
} // namespace ui
namespace views {
class InkDrop;
class InkDropHighlight;
class InkDropImpl;
class InkDropMask;
class InkDropRipple;
enum class InkDropState;
namespace test {
class InkDropHostTestApi;
} // namespace test
// TODO(crbug.com/931964): Rename this type and move this header. Also consider
// if InkDropHost should be what implements the InkDrop interface and have that
// be the public interface.
// The current division of labor is roughly as follows:
// * InkDropHost manages an InkDrop and is responsible for a lot of its
// configuration and creating the parts of the InkDrop.
// * InkDrop manages the parts of the ink-drop effect once it's up and running.
// * InkDropRipple is a ripple effect that usually triggers as a result of
// clicking or activating the button / similar which hosts this.
// * InkDropHighlight manages the hover/focus highlight layer.
// TODO(pbos): See if this can be the only externally visible surface for an
// ink-drop effect, and rename this InkDrop, or consolidate with InkDrop.
class VIEWS_EXPORT InkDropHost {
public:
// Used in SetMode() to specify whether the ink drop effect is enabled
// or not for the view. In case of having an ink drop, it also specifies
// whether the default event handler for the ink drop should be installed or
// the subclass will handle ink drop events itself.
enum class InkDropMode {
OFF,
ON,
ON_NO_GESTURE_HANDLER,
ON_NO_ANIMATE,
};
explicit InkDropHost(View* host);
InkDropHost(const InkDropHost&) = delete;
InkDropHost& operator=(const InkDropHost&) = delete;
virtual ~InkDropHost();
// Returns a configured InkDrop. To override default behavior call
// SetCreateInkDropCallback().
std::unique_ptr<InkDrop> CreateInkDrop();
// Replace CreateInkDrop() behavior.
void SetCreateInkDropCallback(
base::RepeatingCallback<std::unique_ptr<InkDrop>()> callback);
// Creates and returns the visual effect used for press. Used by InkDropImpl
// instances.
std::unique_ptr<InkDropRipple> CreateInkDropRipple() const;
// Replaces CreateInkDropRipple() behavior.
void SetCreateRippleCallback(
base::RepeatingCallback<std::unique_ptr<InkDropRipple>()> callback);
// Returns the point of the |last_ripple_triggering_event_| if it was a
// LocatedEvent, otherwise the center point of the local bounds is returned.
// This is nominally used by the InkDropRipple.
gfx::Point GetInkDropCenterBasedOnLastEvent() const;
// Creates and returns the visual effect used for hover and focus. Used by
// InkDropImpl instances. To override behavior call
// SetCreateHighlightCallback().
std::unique_ptr<InkDropHighlight> CreateInkDropHighlight() const;
// Replaces CreateInkDropHighlight() behavior.
void SetCreateHighlightCallback(
base::RepeatingCallback<std::unique_ptr<InkDropHighlight>()> callback);
// Callback replacement of CreateInkDropMask().
// TODO(pbos): Investigate removing this. It currently is only used by
// ToolbarButton.
void SetCreateMaskCallback(
base::RepeatingCallback<std::unique_ptr<InkDropMask>()> callback);
// Returns the base color for the ink drop.
SkColor GetBaseColor() const;
// Sets the base color of the ink drop. If `SetBaseColor` is called, the
// effect of previous calls to `SetBaseColorId` and `SetBaseColorCallback` is
// overwritten and vice versa.
// TODO(crbug.com/1341361): Replace SetBaseColor with SetBaseColorId.
void SetBaseColor(SkColor color);
void SetBaseColorId(ui::ColorId color_id);
// Callback version of `GetBaseColor`. If possible, prefer using
// `SetBaseColor` or `SetBaseColorId`.
void SetBaseColorCallback(base::RepeatingCallback<SkColor()> callback);
// Toggle to enable/disable an InkDrop on this View. Descendants can override
// CreateInkDropHighlight() and CreateInkDropRipple() to change the look/feel
// of the InkDrop.
//
// TODO(bruthig): Add an easier mechanism than overriding functions to allow
// subclasses/clients to specify the flavor of ink drop.
void SetMode(InkDropMode ink_drop_mode);
InkDropMode GetMode() const;
// Set whether the ink drop layers should be placed into the region above or
// below the view layer. The default is kBelow;
void SetLayerRegion(LayerRegion region);
LayerRegion GetLayerRegion() const;
void SetVisibleOpacity(float visible_opacity);
float GetVisibleOpacity() const;
void SetHighlightOpacity(absl::optional<float> opacity);
void SetSmallCornerRadius(int small_radius);
int GetSmallCornerRadius() const;
void SetLargeCornerRadius(int large_radius);
int GetLargeCornerRadius() const;
// Animates |ink_drop_| to the desired |ink_drop_state|. Caches |event| as the
// last_ripple_triggering_event().
//
// *** NOTE ***: |event| has been plumbed through on a best effort basis for
// the purposes of centering ink drop ripples on located Events. Thus nullptr
// has been used by clients who do not have an Event instance available to
// them.
void AnimateToState(InkDropState state, const ui::LocatedEvent* event);
// Returns true if an ink drop instance has been created.
bool HasInkDrop() const;
// Provides public access to |ink_drop_| so that factory methods can configure
// the inkdrop. Implements lazy initialization of |ink_drop_| so as to avoid
// virtual method calls during construction since subclasses should be able to
// call SetMode() during construction.
InkDrop* GetInkDrop();
// Returns whether the ink drop should be considered "highlighted" (in or
// animating into "highlight visible" steady state).
bool GetHighlighted() const;
base::CallbackListSubscription AddHighlightedChangedCallback(
base::RepeatingClosure callback);
// Should be called by InkDrop implementations when their highlight state
// changes, to trigger the corresponding property change notification here.
void OnInkDropHighlightedChanged();
// Methods called by InkDrop for attaching its layer.
// TODO(pbos): Investigate using direct calls on View::AddLayerToRegion.
void AddInkDropLayer(ui::Layer* ink_drop_layer);
void RemoveInkDropLayer(ui::Layer* ink_drop_layer);
// Size used by default for the SquareInkDropRipple.
static constexpr gfx::Size kDefaultSquareInkDropSize = gfx::Size(24, 24);
// Returns a large scaled size used by SquareInkDropRipple and Highlight.
static gfx::Size GetLargeSize(gfx::Size small_size);
// Creates a SquareInkDropRipple centered on |center_point|.
std::unique_ptr<InkDropRipple> CreateSquareRipple(
const gfx::Point& center_point,
const gfx::Size& size = kDefaultSquareInkDropSize) const;
View* host_view() { return host_view_; }
const View* host_view() const { return host_view_; }
InkDropMode ink_drop_mode() const { return ink_drop_mode_; }
private:
friend class test::InkDropHostTestApi;
class ViewLayerTransformObserver : public ViewObserver {
public:
ViewLayerTransformObserver(InkDropHost* ink_drop_host, View* host);
~ViewLayerTransformObserver() override;
void OnViewLayerTransformed(View* observed_view) override;
private:
base::ScopedObservation<View, ViewObserver> observation_{this};
const raw_ptr<InkDropHost> ink_drop_host_;
};
class InkDropHostEventHandlerDelegate : public InkDropEventHandler::Delegate {
public:
explicit InkDropHostEventHandlerDelegate(InkDropHost* host);
// InkDropEventHandler::Delegate:
InkDrop* GetInkDrop() override;
bool HasInkDrop() const override;
bool SupportsGestureEvents() const override;
private:
// The host.
const raw_ptr<InkDropHost> ink_drop_host_;
};
const InkDropEventHandler* GetEventHandler() const;
InkDropEventHandler* GetEventHandler();
// This generates a mask for the InkDrop.
std::unique_ptr<views::InkDropMask> CreateInkDropMask() const;
// Adds a clip rect on the root layer of the ink drop impl. This is a more
// performant alternative to using circles or rectangle mask layers. Returns
// true if a clip was added.
bool AddInkDropClip(ui::Layer* ink_drop_layer);
// Initializes and sets a mask on `ink_drop_layer`. This will not run if
// AddInkDropClip() succeeds in the default implementation of
// AddInkDropLayer().
void InstallInkDropMask(ui::Layer* ink_drop_layer);
const raw_ptr<View> host_view_;
// Defines what type of |ink_drop_| to create.
InkDropMode ink_drop_mode_ = views::InkDropHost::InkDropMode::OFF;
// Into which region should the ink drop layers be placed.
LayerRegion layer_region_ = LayerRegion::kBelow;
// Used to observe View and inform the InkDrop of host-transform changes.
ViewLayerTransformObserver host_view_transform_observer_;
// Should not be accessed directly. Use GetInkDrop() instead.
std::unique_ptr<InkDrop> ink_drop_;
// Intentionally declared after |ink_drop_| so that it doesn't access a
// destroyed |ink_drop_| during destruction.
InkDropHostEventHandlerDelegate ink_drop_event_handler_delegate_;
InkDropEventHandler ink_drop_event_handler_;
float ink_drop_visible_opacity_ = 0.175f;
// The color of the ripple and hover.
absl::variant<SkColor, ui::ColorId, base::RepeatingCallback<SkColor()>>
ink_drop_base_color_ = gfx::kPlaceholderColor;
// TODO(pbos): Audit call sites to make sure highlight opacity is either
// always set or using the default value. Then make this a non-optional float.
absl::optional<float> ink_drop_highlight_opacity_;
// Radii used for the SquareInkDropRipple.
int ink_drop_small_corner_radius_ = 2;
int ink_drop_large_corner_radius_ = 4;
std::unique_ptr<views::InkDropMask> ink_drop_mask_;
base::RepeatingCallback<std::unique_ptr<InkDrop>()> create_ink_drop_callback_;
base::RepeatingCallback<std::unique_ptr<InkDropRipple>()>
create_ink_drop_ripple_callback_;
base::RepeatingCallback<std::unique_ptr<InkDropHighlight>()>
create_ink_drop_highlight_callback_;
base::RepeatingCallback<std::unique_ptr<InkDropMask>()>
create_ink_drop_mask_callback_;
base::RepeatingClosureList highlighted_changed_callbacks_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_HOST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_host.h | C++ | unknown | 10,946 |
// 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/animation/ink_drop_host.h"
#include <memory>
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/mock_callback.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_handler.h"
#include "ui/events/event_utils.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop.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/ink_drop_impl_test_api.h"
#include "ui/views/animation/test/test_ink_drop.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/test/views_test_base.h"
namespace views::test {
using InkDropMode = InkDropHostTestApi::InkDropMode;
class TestViewWithInkDrop : public View {
public:
TestViewWithInkDrop() {
InkDrop::Install(this, std::make_unique<InkDropHost>(this));
InkDrop::Get(this)->SetCreateInkDropCallback(base::BindRepeating(
[](TestViewWithInkDrop* host) -> std::unique_ptr<InkDrop> {
auto ink_drop = std::make_unique<TestInkDrop>();
host->last_created_inkdrop_ = ink_drop.get();
return ink_drop;
},
this));
}
TestViewWithInkDrop(const TestViewWithInkDrop&) = delete;
TestViewWithInkDrop& operator=(const TestViewWithInkDrop&) = delete;
// Expose EventTarget::target_handler() for testing.
ui::EventHandler* GetTargetHandler() { return target_handler(); }
TestInkDrop* last_created_inkdrop() const { return last_created_inkdrop_; }
private:
raw_ptr<TestInkDrop> last_created_inkdrop_ = nullptr;
};
class InkDropHostTest : public testing::Test {
public:
InkDropHostTest();
InkDropHostTest(const InkDropHostTest&) = delete;
InkDropHostTest& operator=(const InkDropHostTest&) = delete;
~InkDropHostTest() override;
protected:
// Test target.
TestViewWithInkDrop host_view_;
// Provides internal access to |host_view_| test target.
InkDropHostTestApi test_api_;
std::unique_ptr<base::AutoReset<gfx::Animation::RichAnimationRenderMode>>
animation_mode_reset_;
void MouseEventTriggersInkDropHelper(InkDropMode ink_drop_mode);
};
InkDropHostTest::InkDropHostTest()
: test_api_(InkDrop::Get(&host_view_)),
animation_mode_reset_(gfx::AnimationTestApi::SetRichAnimationRenderMode(
gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED)) {}
InkDropHostTest::~InkDropHostTest() = default;
void InkDropHostTest::MouseEventTriggersInkDropHelper(
InkDropMode ink_drop_mode) {
test_api_.SetInkDropMode(ink_drop_mode);
host_view_.SetEnabled(true);
// Call InkDrop::Get(this)->GetInkDrop() to make sure the test
// CreateInkDrop() is created.
test_api_.GetInkDrop();
if (ink_drop_mode != views::InkDropHost::InkDropMode::OFF) {
EXPECT_FALSE(host_view_.last_created_inkdrop()->is_hovered());
} else {
EXPECT_EQ(host_view_.last_created_inkdrop(), nullptr);
}
ui::MouseEvent mouse_event(ui::ET_MOUSE_ENTERED, gfx::Point(0, 0),
gfx::Point(0, 0), ui::EventTimeForNow(),
ui::EF_IS_SYNTHESIZED, 0);
host_view_.GetTargetHandler()->OnEvent(&mouse_event);
if (ink_drop_mode != views::InkDropHost::InkDropMode::OFF) {
EXPECT_TRUE(host_view_.last_created_inkdrop()->is_hovered());
} else {
EXPECT_EQ(host_view_.last_created_inkdrop(), nullptr);
}
}
// Verifies the return value of GetInkDropCenterBasedOnLastEvent() for a null
// Event.
TEST_F(InkDropHostTest, GetInkDropCenterBasedOnLastEventForNullEvent) {
host_view_.SetSize(gfx::Size(20, 20));
test_api_.AnimateToState(InkDropState::ACTION_PENDING, nullptr);
EXPECT_EQ(gfx::Point(10, 10),
InkDrop::Get(&host_view_)->GetInkDropCenterBasedOnLastEvent());
}
// Verifies the return value of GetInkDropCenterBasedOnLastEvent() for a located
// Event.
TEST_F(InkDropHostTest, GetInkDropCenterBasedOnLastEventForLocatedEvent) {
host_view_.SetSize(gfx::Size(20, 20));
ui::MouseEvent located_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 6),
gfx::Point(5, 6), ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
test_api_.AnimateToState(InkDropState::ACTION_PENDING, &located_event);
EXPECT_EQ(gfx::Point(5, 6),
InkDrop::Get(&host_view_)->GetInkDropCenterBasedOnLastEvent());
}
TEST_F(InkDropHostTest, HasInkDrop) {
EXPECT_FALSE(test_api_.HasInkDrop());
test_api_.GetInkDrop();
EXPECT_TRUE(test_api_.HasInkDrop());
test_api_.SetInkDropMode(views::InkDropHost::InkDropMode::OFF);
EXPECT_FALSE(test_api_.HasInkDrop());
}
// Verifies that mouse events trigger ink drops when ink drop mode is ON.
TEST_F(InkDropHostTest, MouseEventsTriggerInkDropsWhenInkDropIsOn) {
MouseEventTriggersInkDropHelper(views::InkDropHost::InkDropMode::ON);
}
// Verifies that mouse events trigger ink drops when ink drop mode is
// ON_NO_GESTURE_HANDLER.
TEST_F(InkDropHostTest,
MouseEventsTriggerInkDropsWhenInkDropIsOnNoGestureHandler) {
MouseEventTriggersInkDropHelper(
views::InkDropHost::InkDropMode::ON_NO_GESTURE_HANDLER);
}
// Verifies that mouse events do not trigger ink drops when ink drop mode is
// OFF.
TEST_F(InkDropHostTest, MouseEventsDontTriggerInkDropsWhenInkDropIsOff) {
MouseEventTriggersInkDropHelper(views::InkDropHost::InkDropMode::OFF);
}
// Verifies that ink drops are not shown when the host is disabled.
TEST_F(InkDropHostTest, GestureEventsDontTriggerInkDropsWhenHostIsDisabled) {
test_api_.SetInkDropMode(views::InkDropHost::InkDropMode::ON);
host_view_.SetEnabled(false);
ui::GestureEvent gesture_event(
0.f, 0.f, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN));
host_view_.GetTargetHandler()->OnEvent(&gesture_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
}
// Verifies that ink drops are not triggered by gesture events when ink drop
// mode is ON_NO_GESTURE_EVENT or OFF.
TEST_F(InkDropHostTest,
GestureEventsDontTriggerInkDropsWhenInkDropModeIsNotOn) {
for (auto ink_drop_mode :
{views::InkDropHost::InkDropMode::ON_NO_GESTURE_HANDLER,
views::InkDropHost::InkDropMode::OFF}) {
test_api_.SetInkDropMode(ink_drop_mode);
ui::GestureEvent gesture_event(
0.f, 0.f, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN));
host_view_.GetTargetHandler()->OnEvent(&gesture_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
}
}
#if BUILDFLAG(IS_WIN)
TEST_F(InkDropHostTest, NoInkDropOnTouchOrGestureEvents) {
host_view_.SetSize(gfx::Size(20, 20));
test_api_.SetInkDropMode(
views::InkDropHost::InkDropMode::ON_NO_GESTURE_HANDLER);
// Ensure the target ink drop is in the expected state.
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
ui::TouchEvent touch_event(
ui::ET_TOUCH_PRESSED, gfx::Point(5, 6), ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 1));
test_api_.AnimateToState(InkDropState::ACTION_PENDING, &touch_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
test_api_.AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING,
&touch_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
ui::GestureEvent gesture_event(5.0f, 6.0f, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP));
test_api_.AnimateToState(InkDropState::ACTION_PENDING, &gesture_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
test_api_.AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING,
&gesture_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
}
TEST_F(InkDropHostTest, DismissInkDropOnTouchOrGestureEvents) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation()) {
return;
}
host_view_.SetSize(gfx::Size(20, 20));
test_api_.SetInkDropMode(
views::InkDropHost::InkDropMode::ON_NO_GESTURE_HANDLER);
// Ensure the target ink drop is in the expected state.
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::HIDDEN);
ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 6),
gfx::Point(5, 6), ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
test_api_.AnimateToState(InkDropState::ACTION_PENDING, &mouse_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::ACTION_PENDING);
ui::TouchEvent touch_event(
ui::ET_TOUCH_PRESSED, gfx::Point(5, 6), ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 1));
test_api_.AnimateToState(InkDropState::ACTION_TRIGGERED, &touch_event);
EXPECT_EQ(test_api_.GetInkDrop()->GetTargetInkDropState(),
InkDropState::ACTION_TRIGGERED);
}
#endif
// Verifies that calling OnInkDropHighlightedChanged() triggers a property
// changed notification for the highlighted property.
TEST_F(InkDropHostTest, HighlightedChangedFired) {
bool callback_called = false;
auto subscription =
InkDrop::Get(&host_view_)
->AddHighlightedChangedCallback(base::BindRepeating(
[](bool* called) { *called = true; }, &callback_called));
InkDrop::Get(&host_view_)->OnInkDropHighlightedChanged();
EXPECT_TRUE(callback_called);
}
// A very basic View that hosts an InkDrop.
class BasicTestViewWithInkDrop : public View {
public:
BasicTestViewWithInkDrop() {
InkDrop::Install(this, std::make_unique<InkDropHost>(this));
}
BasicTestViewWithInkDrop(const BasicTestViewWithInkDrop&) = delete;
BasicTestViewWithInkDrop& operator=(const BasicTestViewWithInkDrop&) = delete;
~BasicTestViewWithInkDrop() override = default;
};
// Tests the existence of layer clipping or layer masking when certain path
// generators are applied on an InkDropHost.
class InkDropHostClippingTest : public testing::Test {
public:
InkDropHostClippingTest() : host_view_test_api_(InkDrop::Get(&host_view_)) {
// Set up an InkDropHost. Clipping is based on the size of the view, so
// make sure the size is non empty.
host_view_test_api_.SetInkDropMode(views::InkDropHost::InkDropMode::ON);
host_view_.SetSize(gfx::Size(20, 20));
// The root layer of the ink drop is created the first time GetInkDrop is
// called and then kept alive until the host view is destroyed.
ink_drop_ =
static_cast<InkDropImpl*>(InkDrop::Get(&host_view_)->GetInkDrop());
ink_drop_test_api_ = std::make_unique<test::InkDropImplTestApi>(ink_drop_);
}
InkDropHostClippingTest(const InkDropHostClippingTest&) = delete;
InkDropHostClippingTest& operator=(const InkDropHostClippingTest&) = delete;
~InkDropHostClippingTest() override = default;
ui::Layer* GetRootLayer() { return ink_drop_test_api_->GetRootLayer(); }
protected:
// Test target.
BasicTestViewWithInkDrop host_view_;
// Provides internal access to |host_view_| test target.
InkDropHostTestApi host_view_test_api_;
raw_ptr<InkDropImpl> ink_drop_ = nullptr;
// Provides internal access to |host_view_|'s ink drop.
std::unique_ptr<test::InkDropImplTestApi> ink_drop_test_api_;
};
// Tests that by default (no highlight path generator applied), the root layer
// will be masked.
TEST_F(InkDropHostClippingTest, DefaultInkDropMasksRootLayer) {
ink_drop_->SetHovered(true);
EXPECT_TRUE(GetRootLayer()->layer_mask_layer());
EXPECT_TRUE(GetRootLayer()->clip_rect().IsEmpty());
}
// Tests that when adding a non empty highlight path generator, the root layer
// is clipped instead of masked.
TEST_F(InkDropHostClippingTest,
HighlightPathGeneratorClipsRootLayerWithoutMask) {
views::InstallRectHighlightPathGenerator(&host_view_);
ink_drop_->SetHovered(true);
EXPECT_FALSE(GetRootLayer()->layer_mask_layer());
EXPECT_FALSE(GetRootLayer()->clip_rect().IsEmpty());
}
// An empty highlight path generator is used for views who do not want their
// highlight or ripple constrained by their size. Test that the views' ink
// drop root layers have neither a clip or mask.
TEST_F(InkDropHostClippingTest,
EmptyHighlightPathGeneratorUsesNeitherMaskNorClipsRootLayer) {
views::InstallEmptyHighlightPathGenerator(&host_view_);
ink_drop_->SetHovered(true);
EXPECT_FALSE(GetRootLayer()->layer_mask_layer());
EXPECT_TRUE(GetRootLayer()->clip_rect().IsEmpty());
}
class InkDropInWidgetTest : public ViewsTestBase {
public:
InkDropInWidgetTest() = default;
InkDropInWidgetTest(const InkDropInWidgetTest&) = delete;
InkDropInWidgetTest& operator=(const InkDropInWidgetTest&) = delete;
~InkDropInWidgetTest() override = default;
protected:
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = CreateTestWidget();
view_ =
widget_->SetContentsView(std::make_unique<BasicTestViewWithInkDrop>());
}
void TearDown() override {
view_ = nullptr;
widget_.reset();
ViewsTestBase::TearDown();
}
InkDropHost& ink_drop() { return *InkDrop::Get(view_); }
const ui::ColorProvider& color_provider() {
return *widget_->GetColorProvider();
}
private:
std::unique_ptr<Widget> widget_;
raw_ptr<View> view_ = nullptr;
};
TEST_F(InkDropInWidgetTest, SetBaseColor) {
ink_drop().SetBaseColor(SK_ColorBLUE);
EXPECT_EQ(ink_drop().GetBaseColor(), SK_ColorBLUE);
}
TEST_F(InkDropInWidgetTest, SetBaseColorId) {
ink_drop().SetBaseColorId(ui::kColorSeparator);
EXPECT_EQ(ink_drop().GetBaseColor(),
color_provider().GetColor(ui::kColorSeparator));
ink_drop().SetBaseColor(SK_ColorBLUE);
EXPECT_EQ(ink_drop().GetBaseColor(), SK_ColorBLUE);
}
TEST_F(InkDropInWidgetTest, SetBaseColorCallback) {
base::MockRepeatingCallback<SkColor()> callback;
EXPECT_CALL(callback, Run).WillRepeatedly(testing::Return(SK_ColorCYAN));
ink_drop().SetBaseColorCallback(callback.Get());
EXPECT_EQ(ink_drop().GetBaseColor(), SK_ColorCYAN);
ink_drop().SetBaseColor(SK_ColorBLUE);
EXPECT_EQ(ink_drop().GetBaseColor(), SK_ColorBLUE);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_host_unittest.cc | C++ | unknown | 15,091 |
// 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/animation/ink_drop_impl.h"
#include <utility>
#include "base/auto_reset.h"
#include "base/functional/bind.h"
#include "base/timer/timer.h"
#include "ui/compositor/layer.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_util.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/style/platform_style.h"
namespace views {
namespace {
// The duration for the highlight state fade in/out animations when they are
// triggered by a hover changed event.
constexpr auto kHighlightFadeInOnHoverChangeDuration = base::Milliseconds(250);
constexpr auto kHighlightFadeOutOnHoverChangeDuration = base::Milliseconds(250);
// The duration for the highlight state fade in/out animations when they are
// triggered by a focus changed event.
constexpr auto kHighlightFadeInOnFocusChangeDuration = base::TimeDelta();
constexpr auto kHighlightFadeOutOnFocusChangeDuration = base::TimeDelta();
// The duration for showing/hiding the highlight when triggered by ripple
// visibility changes for the HIDE_ON_RIPPLE AutoHighlightMode.
constexpr auto kHighlightFadeInOnRippleHidingDuration = base::Milliseconds(250);
constexpr auto kHighlightFadeOutOnRippleShowingDuration =
base::Milliseconds(120);
// The duration for showing/hiding the highlight when triggered by ripple
// visibility changes for the SHOW_ON_RIPPLE AutoHighlightMode.
constexpr auto kHighlightFadeInOnRippleShowingDuration =
base::Milliseconds(250);
constexpr auto kHighlightFadeOutOnRippleHidingDuration =
base::Milliseconds(120);
// The amount of time that |highlight_| should delay after a ripple animation
// before fading in, for highlight due to mouse hover.
constexpr auto kHoverFadeInAfterRippleDelay = base::Milliseconds(1000);
// Returns true if an ink drop with the given |ink_drop_state| should
// automatically transition to the InkDropState::HIDDEN state.
bool ShouldAnimateToHidden(InkDropState ink_drop_state) {
switch (ink_drop_state) {
case views::InkDropState::ACTION_TRIGGERED:
case views::InkDropState::ALTERNATE_ACTION_TRIGGERED:
case views::InkDropState::DEACTIVATED:
return true;
default:
return false;
}
}
} // namespace
// HighlightState definition
InkDropImpl* InkDropImpl::HighlightState::GetInkDrop() {
return state_factory_->ink_drop();
}
// A HighlightState to be used during InkDropImpl destruction. All event
// handlers are no-ops so as to avoid triggering animations during tear down.
class InkDropImpl::DestroyingHighlightState
: public InkDropImpl::HighlightState {
public:
DestroyingHighlightState() : HighlightState(nullptr) {}
DestroyingHighlightState(const DestroyingHighlightState&) = delete;
DestroyingHighlightState& operator=(const DestroyingHighlightState&) = delete;
// InkDropImpl::HighlightState:
void Enter() override {}
void ShowOnHoverChanged() override {}
void OnHoverChanged() override {}
void ShowOnFocusChanged() override {}
void OnFocusChanged() override {}
void AnimationStarted(InkDropState ink_drop_state) override {}
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override {}
};
//
// AutoHighlightMode::NONE states
//
// Animates the highlight to hidden upon entering this state. Transitions to a
// visible state based on hover/focus changes.
class InkDropImpl::NoAutoHighlightHiddenState
: public InkDropImpl::HighlightState {
public:
NoAutoHighlightHiddenState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
NoAutoHighlightHiddenState(const NoAutoHighlightHiddenState&) = delete;
NoAutoHighlightHiddenState& operator=(const NoAutoHighlightHiddenState&) =
delete;
// InkDropImpl::HighlightState:
void Enter() override;
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
private:
// Handles all changes to the hover/focus status and transitions to a visible
// state if necessary.
void HandleHoverAndFocusChangeChanges(base::TimeDelta animation_duration);
// The fade out animation duration.
base::TimeDelta animation_duration_;
};
// Animates the highlight to visible upon entering this state. Transitions to a
// hidden state based on hover/focus changes.
class InkDropImpl::NoAutoHighlightVisibleState
: public InkDropImpl::HighlightState {
public:
NoAutoHighlightVisibleState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
NoAutoHighlightVisibleState(const NoAutoHighlightVisibleState&) = delete;
NoAutoHighlightVisibleState& operator=(const NoAutoHighlightVisibleState&) =
delete;
// InkDropImpl::HighlightState:
void Enter() override;
void Exit() override {}
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
private:
// Handles all changes to the hover/focus status and transitions to a hidden
// state if necessary.
void HandleHoverAndFocusChangeChanges(base::TimeDelta animation_duration);
// The fade in animation duration.
base::TimeDelta animation_duration_;
};
// NoAutoHighlightHiddenState definition
InkDropImpl::NoAutoHighlightHiddenState::NoAutoHighlightHiddenState(
HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::HighlightState(state_factory),
animation_duration_(animation_duration) {}
void InkDropImpl::NoAutoHighlightHiddenState::Enter() {
GetInkDrop()->SetHighlight(false, animation_duration_);
}
void InkDropImpl::NoAutoHighlightHiddenState::ShowOnHoverChanged() {
HandleHoverAndFocusChangeChanges(
GetInkDrop()->hover_highlight_fade_duration().value_or(
kHighlightFadeInOnHoverChangeDuration));
}
void InkDropImpl::NoAutoHighlightHiddenState::OnHoverChanged() {
HandleHoverAndFocusChangeChanges(
GetInkDrop()->hover_highlight_fade_duration().value_or(
kHighlightFadeInOnHoverChangeDuration));
}
void InkDropImpl::NoAutoHighlightHiddenState::ShowOnFocusChanged() {
HandleHoverAndFocusChangeChanges(kHighlightFadeInOnFocusChangeDuration);
}
void InkDropImpl::NoAutoHighlightHiddenState::OnFocusChanged() {
HandleHoverAndFocusChangeChanges(kHighlightFadeInOnFocusChangeDuration);
}
void InkDropImpl::NoAutoHighlightHiddenState::HandleHoverAndFocusChangeChanges(
base::TimeDelta animation_duration) {
if (GetInkDrop()->ShouldHighlight()) {
GetInkDrop()->SetHighlightState(
state_factory()->CreateVisibleState(animation_duration));
}
}
void InkDropImpl::NoAutoHighlightHiddenState::AnimationStarted(
InkDropState ink_drop_state) {}
void InkDropImpl::NoAutoHighlightHiddenState::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {}
// NoAutoHighlightVisibleState definition
InkDropImpl::NoAutoHighlightVisibleState::NoAutoHighlightVisibleState(
HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::HighlightState(state_factory),
animation_duration_(animation_duration) {}
void InkDropImpl::NoAutoHighlightVisibleState::Enter() {
GetInkDrop()->SetHighlight(true, animation_duration_);
}
void InkDropImpl::NoAutoHighlightVisibleState::ShowOnHoverChanged() {
HandleHoverAndFocusChangeChanges(
GetInkDrop()->hover_highlight_fade_duration().value_or(
kHighlightFadeOutOnHoverChangeDuration));
}
void InkDropImpl::NoAutoHighlightVisibleState::OnHoverChanged() {
HandleHoverAndFocusChangeChanges(
GetInkDrop()->hover_highlight_fade_duration().value_or(
kHighlightFadeOutOnHoverChangeDuration));
}
void InkDropImpl::NoAutoHighlightVisibleState::ShowOnFocusChanged() {
HandleHoverAndFocusChangeChanges(kHighlightFadeOutOnFocusChangeDuration);
}
void InkDropImpl::NoAutoHighlightVisibleState::OnFocusChanged() {
HandleHoverAndFocusChangeChanges(kHighlightFadeOutOnFocusChangeDuration);
}
void InkDropImpl::NoAutoHighlightVisibleState::HandleHoverAndFocusChangeChanges(
base::TimeDelta animation_duration) {
if (!GetInkDrop()->ShouldHighlight()) {
GetInkDrop()->SetHighlightState(
state_factory()->CreateHiddenState(animation_duration));
}
}
void InkDropImpl::NoAutoHighlightVisibleState::AnimationStarted(
InkDropState ink_drop_state) {}
void InkDropImpl::NoAutoHighlightVisibleState::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {}
//
// AutoHighlightMode::HIDE_ON_RIPPLE states
//
// Extends the base hidden state to re-show the highlight after the ripple
// becomes hidden.
class InkDropImpl::HideHighlightOnRippleHiddenState
: public InkDropImpl::NoAutoHighlightHiddenState {
public:
HideHighlightOnRippleHiddenState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
HideHighlightOnRippleHiddenState(const HideHighlightOnRippleHiddenState&) =
delete;
HideHighlightOnRippleHiddenState& operator=(
const HideHighlightOnRippleHiddenState&) = delete;
// InkDropImpl::NoAutoHighlightHiddenState:
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
private:
// Starts the |highlight_after_ripple_timer_|. This will stop the current
// |highlight_after_ripple_timer_| instance if it exists.
void StartHighlightAfterRippleTimer();
// Callback for when the |highlight_after_ripple_timer_| fires. Transitions to
// a visible state if the ink drop should be highlighted.
void HighlightAfterRippleTimerFired();
// The timer used to delay the highlight fade in after an ink drop ripple
// animation.
std::unique_ptr<base::OneShotTimer> highlight_after_ripple_timer_;
};
// Extends the base visible state to hide the highlight when the ripple becomes
// visible.
class InkDropImpl::HideHighlightOnRippleVisibleState
: public InkDropImpl::NoAutoHighlightVisibleState {
public:
HideHighlightOnRippleVisibleState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
HideHighlightOnRippleVisibleState(const HideHighlightOnRippleVisibleState&) =
delete;
HideHighlightOnRippleVisibleState& operator=(
const HideHighlightOnRippleVisibleState&) = delete;
// InkDropImpl::NoAutoHighlightVisibleState:
void AnimationStarted(InkDropState ink_drop_state) override;
};
// HideHighlightOnRippleHiddenState definition
InkDropImpl::HideHighlightOnRippleHiddenState::HideHighlightOnRippleHiddenState(
HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::NoAutoHighlightHiddenState(state_factory,
animation_duration),
highlight_after_ripple_timer_(nullptr) {}
void InkDropImpl::HideHighlightOnRippleHiddenState::ShowOnHoverChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightHiddenState::ShowOnHoverChanged();
}
void InkDropImpl::HideHighlightOnRippleHiddenState::OnHoverChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightHiddenState::OnHoverChanged();
}
void InkDropImpl::HideHighlightOnRippleHiddenState::ShowOnFocusChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightHiddenState::ShowOnFocusChanged();
}
void InkDropImpl::HideHighlightOnRippleHiddenState::OnFocusChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightHiddenState::OnFocusChanged();
}
void InkDropImpl::HideHighlightOnRippleHiddenState::AnimationStarted(
InkDropState ink_drop_state) {
if (ink_drop_state == views::InkDropState::DEACTIVATED &&
GetInkDrop()->ShouldHighlightBasedOnFocus()) {
// It's possible to get animation started events when destroying the
// |ink_drop_ripple_|.
// TODO(bruthig): Investigate if the animation framework can address this
// issue instead. See https://crbug.com/663335.
InkDropImpl* ink_drop = GetInkDrop();
HighlightStateFactory* highlight_state_factory = state_factory();
if (ink_drop->ink_drop_ripple_)
ink_drop->ink_drop_ripple_->SnapToHidden();
// |this| may be destroyed after SnapToHidden(), so be sure not to access
// |any members.
ink_drop->SetHighlightState(
highlight_state_factory->CreateVisibleState(base::TimeDelta()));
}
}
void InkDropImpl::HideHighlightOnRippleHiddenState::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {
if (ink_drop_state == InkDropState::HIDDEN) {
// Re-highlight, as necessary. For hover, there's a delay; for focus, jump
// straight into the animation.
if (GetInkDrop()->ShouldHighlightBasedOnFocus()) {
GetInkDrop()->SetHighlightState(
state_factory()->CreateVisibleState(base::TimeDelta()));
return;
} else {
StartHighlightAfterRippleTimer();
}
}
}
void InkDropImpl::HideHighlightOnRippleHiddenState::
StartHighlightAfterRippleTimer() {
highlight_after_ripple_timer_ = std::make_unique<base::OneShotTimer>();
highlight_after_ripple_timer_->Start(
FROM_HERE, kHoverFadeInAfterRippleDelay,
base::BindOnce(&InkDropImpl::HideHighlightOnRippleHiddenState::
HighlightAfterRippleTimerFired,
base::Unretained(this)));
}
void InkDropImpl::HideHighlightOnRippleHiddenState::
HighlightAfterRippleTimerFired() {
highlight_after_ripple_timer_.reset();
if (GetInkDrop()->GetTargetInkDropState() == InkDropState::HIDDEN &&
GetInkDrop()->ShouldHighlight()) {
GetInkDrop()->SetHighlightState(state_factory()->CreateVisibleState(
kHighlightFadeInOnRippleHidingDuration));
}
}
// HideHighlightOnRippleVisibleState definition
InkDropImpl::HideHighlightOnRippleVisibleState::
HideHighlightOnRippleVisibleState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::NoAutoHighlightVisibleState(state_factory,
animation_duration) {}
void InkDropImpl::HideHighlightOnRippleVisibleState::AnimationStarted(
InkDropState ink_drop_state) {
if (ink_drop_state != InkDropState::HIDDEN) {
GetInkDrop()->SetHighlightState(state_factory()->CreateHiddenState(
kHighlightFadeOutOnRippleShowingDuration));
}
}
//
// AutoHighlightMode::SHOW_ON_RIPPLE states
//
// Extends the base hidden state to show the highlight when the ripple becomes
// visible.
class InkDropImpl::ShowHighlightOnRippleHiddenState
: public InkDropImpl::NoAutoHighlightHiddenState {
public:
ShowHighlightOnRippleHiddenState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
ShowHighlightOnRippleHiddenState(const ShowHighlightOnRippleHiddenState&) =
delete;
ShowHighlightOnRippleHiddenState& operator=(
const ShowHighlightOnRippleHiddenState&) = delete;
// InkDropImpl::NoAutoHighlightHiddenState:
void AnimationStarted(InkDropState ink_drop_state) override;
};
// Extends the base visible state to hide the highlight when the ripple becomes
// hidden.
class InkDropImpl::ShowHighlightOnRippleVisibleState
: public InkDropImpl::NoAutoHighlightVisibleState {
public:
ShowHighlightOnRippleVisibleState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration);
ShowHighlightOnRippleVisibleState(const ShowHighlightOnRippleVisibleState&) =
delete;
ShowHighlightOnRippleVisibleState& operator=(
const ShowHighlightOnRippleVisibleState&) = delete;
// InkDropImpl::NoAutoHighlightVisibleState:
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
};
// ShowHighlightOnRippleHiddenState definition
InkDropImpl::ShowHighlightOnRippleHiddenState::ShowHighlightOnRippleHiddenState(
HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::NoAutoHighlightHiddenState(state_factory,
animation_duration) {}
void InkDropImpl::ShowHighlightOnRippleHiddenState::AnimationStarted(
InkDropState ink_drop_state) {
if (ink_drop_state != views::InkDropState::HIDDEN) {
GetInkDrop()->SetHighlightState(state_factory()->CreateVisibleState(
kHighlightFadeInOnRippleShowingDuration));
}
}
// ShowHighlightOnRippleVisibleState definition
InkDropImpl::ShowHighlightOnRippleVisibleState::
ShowHighlightOnRippleVisibleState(HighlightStateFactory* state_factory,
base::TimeDelta animation_duration)
: InkDropImpl::NoAutoHighlightVisibleState(state_factory,
animation_duration) {}
void InkDropImpl::ShowHighlightOnRippleVisibleState::ShowOnHoverChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightVisibleState::ShowOnHoverChanged();
}
void InkDropImpl::ShowHighlightOnRippleVisibleState::OnHoverChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightVisibleState::OnHoverChanged();
}
void InkDropImpl::ShowHighlightOnRippleVisibleState::ShowOnFocusChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightVisibleState::ShowOnFocusChanged();
}
void InkDropImpl::ShowHighlightOnRippleVisibleState::OnFocusChanged() {
if (GetInkDrop()->GetTargetInkDropState() != InkDropState::HIDDEN)
return;
NoAutoHighlightVisibleState::OnFocusChanged();
}
void InkDropImpl::ShowHighlightOnRippleVisibleState::AnimationStarted(
InkDropState ink_drop_state) {
if (ink_drop_state == InkDropState::HIDDEN &&
!GetInkDrop()->ShouldHighlight()) {
GetInkDrop()->SetHighlightState(state_factory()->CreateHiddenState(
kHighlightFadeOutOnRippleHidingDuration));
}
}
InkDropImpl::HighlightStateFactory::HighlightStateFactory(
InkDropImpl::AutoHighlightMode highlight_mode,
InkDropImpl* ink_drop)
: highlight_mode_(highlight_mode), ink_drop_(ink_drop) {}
std::unique_ptr<InkDropImpl::HighlightState>
InkDropImpl::HighlightStateFactory::CreateStartState() {
switch (highlight_mode_) {
case InkDropImpl::AutoHighlightMode::NONE:
return std::make_unique<NoAutoHighlightHiddenState>(this,
base::TimeDelta());
case InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE:
return std::make_unique<HideHighlightOnRippleHiddenState>(
this, base::TimeDelta());
case InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE:
return std::make_unique<ShowHighlightOnRippleHiddenState>(
this, base::TimeDelta());
}
NOTREACHED_NORETURN();
}
std::unique_ptr<InkDropImpl::HighlightState>
InkDropImpl::HighlightStateFactory::CreateHiddenState(
base::TimeDelta animation_duration) {
switch (highlight_mode_) {
case InkDropImpl::AutoHighlightMode::NONE:
return std::make_unique<NoAutoHighlightHiddenState>(this,
animation_duration);
case InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE:
return std::make_unique<HideHighlightOnRippleHiddenState>(
this, animation_duration);
case InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE:
return std::make_unique<ShowHighlightOnRippleHiddenState>(
this, animation_duration);
}
// Required for some compilers.
NOTREACHED_NORETURN();
}
std::unique_ptr<InkDropImpl::HighlightState>
InkDropImpl::HighlightStateFactory::CreateVisibleState(
base::TimeDelta animation_duration) {
switch (highlight_mode_) {
case InkDropImpl::AutoHighlightMode::NONE:
return std::make_unique<NoAutoHighlightVisibleState>(this,
animation_duration);
case InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE:
return std::make_unique<HideHighlightOnRippleVisibleState>(
this, animation_duration);
case InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE:
return std::make_unique<ShowHighlightOnRippleVisibleState>(
this, animation_duration);
}
// Required for some compilers.
NOTREACHED_NORETURN();
}
InkDropImpl::InkDropImpl(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
AutoHighlightMode auto_highlight_mode)
: ink_drop_host_(ink_drop_host),
highlight_state_factory_(auto_highlight_mode, this),
root_layer_(new ui::Layer(ui::LAYER_NOT_DRAWN)) {
root_layer_->SetBounds(gfx::Rect(host_size));
root_layer_->SetName("InkDropImpl:RootLayer");
SetHighlightState(highlight_state_factory_.CreateStartState());
}
InkDropImpl::~InkDropImpl() {
destroying_ = true;
// Setting a no-op state prevents animations from being triggered on a null
// |ink_drop_ripple_| as a side effect of the tear down.
SetHighlightState(std::make_unique<DestroyingHighlightState>());
// Explicitly destroy the InkDropRipple so that this still exists if
// views::InkDropRippleObserver methods are called on this.
DestroyInkDropRipple();
DestroyInkDropHighlight();
}
void InkDropImpl::HostSizeChanged(const gfx::Size& new_size) {
// |root_layer_| should fill the entire host because it affects the clipping
// when a mask layer is applied to it. This will not affect clipping if no
// mask layer is set.
root_layer_->SetBounds(gfx::Rect(new_size) +
root_layer_->bounds().OffsetFromOrigin());
const bool create_ink_drop_ripple = !!ink_drop_ripple_;
InkDropState state = GetTargetInkDropState();
if (ShouldAnimateToHidden(state))
state = views::InkDropState::HIDDEN;
DestroyInkDropRipple();
if (highlight_) {
bool visible = highlight_->IsFadingInOrVisible();
DestroyInkDropHighlight();
// Both the ripple and the highlight must have been destroyed before
// recreating either of them otherwise the mask will not get recreated.
CreateInkDropHighlight();
if (visible)
highlight_->FadeIn(base::TimeDelta());
}
if (create_ink_drop_ripple) {
CreateInkDropRipple();
ink_drop_ripple_->SnapToState(state);
}
}
void InkDropImpl::HostTransformChanged(const gfx::Transform& new_transform) {
// If the host has a transform applied, the root and its children layers
// should be affected too.
root_layer_->SetTransform(new_transform);
}
InkDropState InkDropImpl::GetTargetInkDropState() const {
if (!ink_drop_ripple_)
return InkDropState::HIDDEN;
return ink_drop_ripple_->target_ink_drop_state();
}
void InkDropImpl::AnimateToState(InkDropState ink_drop_state) {
// Never animate hidden -> hidden, since that will add layers which may never
// be needed. Other same-state transitions may restart animations.
if (ink_drop_state == InkDropState::HIDDEN &&
GetTargetInkDropState() == InkDropState::HIDDEN)
return;
DestroyHiddenTargetedAnimations();
if (!ink_drop_ripple_)
CreateInkDropRipple();
ink_drop_ripple_->AnimateToState(ink_drop_state);
}
void InkDropImpl::SetHoverHighlightFadeDuration(base::TimeDelta duration) {
hover_highlight_fade_duration_ = duration;
}
void InkDropImpl::UseDefaultHoverHighlightFadeDuration() {
hover_highlight_fade_duration_.reset();
}
void InkDropImpl::SnapToActivated() {
DestroyHiddenTargetedAnimations();
if (!ink_drop_ripple_)
CreateInkDropRipple();
ink_drop_ripple_->SnapToActivated();
}
void InkDropImpl::SnapToHidden() {
DestroyHiddenTargetedAnimations();
if (!ink_drop_ripple_)
return;
ink_drop_ripple_->SnapToHidden();
}
void InkDropImpl::SetHovered(bool is_hovered) {
is_hovered_ = is_hovered;
highlight_state_->OnHoverChanged();
}
void InkDropImpl::SetFocused(bool is_focused) {
is_focused_ = is_focused;
highlight_state_->OnFocusChanged();
}
bool InkDropImpl::IsHighlightFadingInOrVisible() const {
return highlight_ && highlight_->IsFadingInOrVisible();
}
void InkDropImpl::SetShowHighlightOnHover(bool show_highlight_on_hover) {
show_highlight_on_hover_ = show_highlight_on_hover;
highlight_state_->ShowOnHoverChanged();
}
void InkDropImpl::SetShowHighlightOnFocus(bool show_highlight_on_focus) {
show_highlight_on_focus_ = show_highlight_on_focus;
highlight_state_->ShowOnFocusChanged();
}
void InkDropImpl::DestroyHiddenTargetedAnimations() {
if (ink_drop_ripple_ &&
(ink_drop_ripple_->target_ink_drop_state() == InkDropState::HIDDEN ||
ShouldAnimateToHidden(ink_drop_ripple_->target_ink_drop_state()))) {
DestroyInkDropRipple();
}
}
void InkDropImpl::CreateInkDropRipple() {
DCHECK(!destroying_);
DestroyInkDropRipple();
ink_drop_ripple_ = ink_drop_host_->CreateInkDropRipple();
ink_drop_ripple_->set_observer(this);
root_layer_->Add(ink_drop_ripple_->GetRootLayer());
AddRootLayerToHostIfNeeded();
}
void InkDropImpl::DestroyInkDropRipple() {
if (!ink_drop_ripple_)
return;
// Ensures no observer callback happens from removing from |root_layer_|
// or destroying |ink_drop_ripple_|. Speculative fix for crashes in
// https://crbug.com/1088432 and https://crbug.com/1099844.
ink_drop_ripple_->set_observer(nullptr);
root_layer_->Remove(ink_drop_ripple_->GetRootLayer());
ink_drop_ripple_.reset();
RemoveRootLayerFromHostIfNeeded();
}
void InkDropImpl::CreateInkDropHighlight() {
DCHECK(!destroying_);
DestroyInkDropHighlight();
highlight_ = ink_drop_host_->CreateInkDropHighlight();
DCHECK(highlight_);
// If the platform provides HC colors, we need to show them fully on hover and
// press.
if (views::UsingPlatformHighContrastInkDrop(ink_drop_host_->host_view()))
highlight_->set_visible_opacity(1.0f);
highlight_->set_observer(this);
root_layer_->Add(highlight_->layer());
AddRootLayerToHostIfNeeded();
}
void InkDropImpl::DestroyInkDropHighlight() {
if (!highlight_)
return;
// Ensures no observer callback happens from removing from |root_layer_|
// or destroying |highlight_|. Speculative fix for crashes in
// https://crbug.com/1088432 and https://crbug.com/1099844.
highlight_->set_observer(nullptr);
root_layer_->Remove(highlight_->layer());
highlight_.reset();
RemoveRootLayerFromHostIfNeeded();
}
void InkDropImpl::AddRootLayerToHostIfNeeded() {
DCHECK(highlight_ || ink_drop_ripple_);
DCHECK(!root_layer_->children().empty());
if (!root_layer_added_to_host_) {
root_layer_added_to_host_ = true;
ink_drop_host_->AddInkDropLayer(root_layer_.get());
}
}
void InkDropImpl::RemoveRootLayerFromHostIfNeeded() {
if (root_layer_added_to_host_ && !highlight_ && !ink_drop_ripple_) {
root_layer_added_to_host_ = false;
ink_drop_host_->RemoveInkDropLayer(root_layer_.get());
}
}
// -----------------------------------------------------------------------------
// views::InkDropRippleObserver:
void InkDropImpl::AnimationStarted(InkDropState ink_drop_state) {
// AnimationStarted should only be called from |ink_drop_ripple_|.
DCHECK(ink_drop_ripple_);
highlight_state_->AnimationStarted(ink_drop_state);
NotifyInkDropAnimationStarted();
}
void InkDropImpl::AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {
highlight_state_->AnimationEnded(ink_drop_state, reason);
NotifyInkDropRippleAnimationEnded(ink_drop_state);
if (reason != InkDropAnimationEndedReason::SUCCESS)
return;
// |ink_drop_ripple_| might be null during destruction.
if (!ink_drop_ripple_)
return;
if (ShouldAnimateToHidden(ink_drop_state)) {
ink_drop_ripple_->AnimateToState(views::InkDropState::HIDDEN);
} else if (ink_drop_state == views::InkDropState::HIDDEN) {
// TODO(bruthig): Investigate whether creating and destroying
// InkDropRipples is expensive and consider creating an
// InkDropRipplePool. See www.crbug.com/522175.
DestroyInkDropRipple();
}
}
// -----------------------------------------------------------------------------
// views::InkDropHighlightObserver:
void InkDropImpl::AnimationStarted(
InkDropHighlight::AnimationType animation_type) {
NotifyInkDropAnimationStarted();
}
void InkDropImpl::AnimationEnded(InkDropHighlight::AnimationType animation_type,
InkDropAnimationEndedReason reason) {
if (animation_type == InkDropHighlight::AnimationType::kFadeOut &&
reason == InkDropAnimationEndedReason::SUCCESS) {
DestroyInkDropHighlight();
}
}
void InkDropImpl::SetHighlight(bool should_highlight,
base::TimeDelta animation_duration) {
if (IsHighlightFadingInOrVisible() == should_highlight)
return;
if (should_highlight) {
CreateInkDropHighlight();
highlight_->FadeIn(animation_duration);
} else {
highlight_->FadeOut(animation_duration);
}
ink_drop_host_->OnInkDropHighlightedChanged();
}
bool InkDropImpl::ShouldHighlight() const {
return ShouldHighlightBasedOnFocus() ||
(show_highlight_on_hover_ && is_hovered_);
}
bool InkDropImpl::ShouldHighlightBasedOnFocus() const {
return show_highlight_on_focus_ && is_focused_;
}
void InkDropImpl::SetHighlightState(
std::unique_ptr<HighlightState> highlight_state) {
ExitHighlightState();
highlight_state_ = std::move(highlight_state);
highlight_state_->Enter();
}
void InkDropImpl::ExitHighlightState() {
DCHECK(!exiting_highlight_state_) << "HighlightStates should not be changed "
"within a call to "
"HighlightState::Exit().";
if (highlight_state_) {
base::AutoReset<bool> exit_guard(&exiting_highlight_state_, true);
highlight_state_->Exit();
}
highlight_state_ = nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_impl.cc | C++ | unknown | 31,040 |
// 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_ANIMATION_INK_DROP_IMPL_H_
#define UI_VIEWS_ANIMATION_INK_DROP_IMPL_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight_observer.h"
#include "ui/views/animation/ink_drop_ripple_observer.h"
#include "ui/views/views_export.h"
namespace views {
namespace test {
class InkDropImplTestApi;
} // namespace test
class InkDropRipple;
class InkDropHost;
class InkDropHighlight;
// A functional implementation of an InkDrop.
class VIEWS_EXPORT InkDropImpl : public InkDrop,
public InkDropRippleObserver,
public InkDropHighlightObserver {
public:
// The different auto highlight behaviors.
enum class AutoHighlightMode {
// No auto-highlighting is done. The highlight will only be shown/hidden as
// per the hover/focus settings.
NONE,
// The highlight will be hidden when a ripple becomes visible. After the
// ripple is hidden the highlight will be made visible again if the
// hover/focus settings deem it should be.
HIDE_ON_RIPPLE,
// The highlight is made visible when the ripple becomes visible. After the
// ripple is hidden the highlight will be hidden again if the hover/focus
// settings deem it should be.
SHOW_ON_RIPPLE,
};
// Constructs an ink drop that will attach the ink drop to the given
// |ink_drop_host|. |host_size| is used to set the size of the ink drop layer.
//
// By default the highlight will be made visible while |this| is hovered but
// not focused.
InkDropImpl(InkDropHost* ink_drop_host,
const gfx::Size& host_size,
AutoHighlightMode auto_highlight_mode);
InkDropImpl(const InkDropImpl&) = delete;
InkDropImpl& operator=(const InkDropImpl&) = delete;
~InkDropImpl() override;
const absl::optional<base::TimeDelta>& hover_highlight_fade_duration() const {
return hover_highlight_fade_duration_;
}
// InkDrop:
void HostSizeChanged(const gfx::Size& new_size) override;
void HostTransformChanged(const gfx::Transform& new_transform) override;
InkDropState GetTargetInkDropState() const override;
void AnimateToState(InkDropState ink_drop_state) override;
void SetHoverHighlightFadeDuration(base::TimeDelta duration) override;
void UseDefaultHoverHighlightFadeDuration() override;
void SnapToActivated() override;
void SnapToHidden() override;
void SetHovered(bool is_hovered) override;
void SetFocused(bool is_focused) override;
bool IsHighlightFadingInOrVisible() const override;
void SetShowHighlightOnHover(bool show_highlight_on_hover) override;
void SetShowHighlightOnFocus(bool show_highlight_on_focus) override;
private:
friend class InkDropImplTest;
friend class test::InkDropImplTestApi;
// Forward declaration for use by the HighlightState class definition.
class HighlightStateFactory;
// Base HighlightState defines functions to handle all state changes that may
// affect the highlight state.
//
// Subclasses are expected to handle state changes and transition the
// InkDropImpl::highlight_state_ to new states as desired via the
// InkDropImpl::SetHighlightState() method.
//
// New states should be created via the HighlightStateFactory and not
// directly. This makes it possible for highlighting strategies to extend the
// behavior of existing states and re-use existing state behavior.
//
// Subclasses are also expected to trigger the appropriate highlight
// animations (e.g. fade in/out) via GetInkDrop()->SetHighlight(). Typically
// this is done in the Enter()/Exit() functions. Triggering animations
// anywhere else may be a sign that a new state should exist.
class HighlightState {
public:
HighlightState(const HighlightState&) = delete;
HighlightState& operator=(const HighlightState&) = delete;
virtual ~HighlightState() = default;
// Called when |this| becomes the current state. Allows subclasses to
// perform any work that should not be done in the constructor. It is ok for
// subclass implementations to trigger state changes from within Enter().
virtual void Enter() {}
// Called just before |this| is removed as the current state. Allows
// subclasses to perform any work that should not be done in the destructor
// but is required before exiting |this| state (e.g. releasing resources).
//
// Subclass implementations should NOT do any work that may trigger another
// state change since a state change is already in progress. They must also
// avoid triggering any animations since Exit() will be called during
// InkDropImpl destruction.
virtual void Exit() {}
// Input state change handlers.
// Called when the value of InkDropImpl::show_highlight_on_hover_ changes.
virtual void ShowOnHoverChanged() = 0;
// Called when the value of InkDropImpl::is_hovered_ changes.
virtual void OnHoverChanged() = 0;
// Called when the value of InkDropImpl::show_highlight_on_focus_ changes.
virtual void ShowOnFocusChanged() = 0;
// Called when the value of InkDropImpl::is_focused_ changes.
virtual void OnFocusChanged() = 0;
// Called when an ink drop ripple animation is started.
virtual void AnimationStarted(InkDropState ink_drop_state) = 0;
// Called when an ink drop ripple animation has ended.
virtual void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) = 0;
protected:
explicit HighlightState(HighlightStateFactory* state_factory)
: state_factory_(state_factory) {}
HighlightStateFactory* state_factory() { return state_factory_; }
// Returns the ink drop that has |this| as the current state.
InkDropImpl* GetInkDrop();
private:
// Used by |this| to create the new states to transition to.
const raw_ptr<HighlightStateFactory> state_factory_;
};
// Creates the different HighlightStates instances. A factory is used to make
// it easier for states to extend and re-use existing state logic.
class HighlightStateFactory {
public:
HighlightStateFactory(AutoHighlightMode highlight_mode,
InkDropImpl* ink_drop);
HighlightStateFactory(const HighlightStateFactory&) = delete;
HighlightStateFactory& operator=(const HighlightStateFactory&) = delete;
// Returns the initial state.
std::unique_ptr<HighlightState> CreateStartState();
std::unique_ptr<HighlightState> CreateHiddenState(
base::TimeDelta animation_duration);
std::unique_ptr<HighlightState> CreateVisibleState(
base::TimeDelta animation_duration);
InkDropImpl* ink_drop() { return ink_drop_; }
private:
// Defines which concrete state types to create.
AutoHighlightMode highlight_mode_;
// The ink drop to invoke highlight changes on.
raw_ptr<InkDropImpl> ink_drop_;
};
class DestroyingHighlightState;
// AutoHighlightMode::NONE
class NoAutoHighlightHiddenState;
class NoAutoHighlightVisibleState;
// AutoHighlightMode::HIDE_ON_RIPPLE
class HideHighlightOnRippleHiddenState;
class HideHighlightOnRippleVisibleState;
// AutoHighlightMode::SHOW_ON_RIPPLE states
class ShowHighlightOnRippleHiddenState;
class ShowHighlightOnRippleVisibleState;
// Destroys |ink_drop_ripple_| if it's targeted to the HIDDEN state.
void DestroyHiddenTargetedAnimations();
// Creates a new InkDropRipple and sets it to |ink_drop_ripple_|. If
// |ink_drop_ripple_| wasn't null then it will be destroyed using
// DestroyInkDropRipple().
void CreateInkDropRipple();
// Destroys the current |ink_drop_ripple_|.
void DestroyInkDropRipple();
// Creates a new InkDropHighlight and assigns it to |highlight_|. If
// |highlight_| wasn't null then it will be destroyed using
// DestroyInkDropHighlight().
void CreateInkDropHighlight();
// Destroys the current |highlight_|.
void DestroyInkDropHighlight();
// Adds the |root_layer_| to the |ink_drop_host_| if it hasn't already been
// added.
void AddRootLayerToHostIfNeeded();
// Removes the |root_layer_| from the |ink_drop_host_| if no ink drop ripple
// or highlight is active.
void RemoveRootLayerFromHostIfNeeded();
// views::InkDropRippleObserver:
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
// views::InkDropHighlightObserver:
void AnimationStarted(
InkDropHighlight::AnimationType animation_type) override;
void AnimationEnded(InkDropHighlight::AnimationType animation_type,
InkDropAnimationEndedReason reason) override;
// Enables or disables the highlight state based on |should_highlight| and if
// an animation is triggered it will be scheduled to have the given
// |animation_duration|.
void SetHighlight(bool should_highlight, base::TimeDelta animation_duration);
// Returns true if |this| the highlight should be visible based on the
// hover/focus status.
bool ShouldHighlight() const;
// Returns true if |this| the hilight should be visible based on the focus
// status.
bool ShouldHighlightBasedOnFocus() const;
// Updates the current |highlight_state_|. Calls Exit()/Enter() on the
// previous/new state to notify them of the transition.
//
// Uses ExitHighlightState() to exit the current state.
void SetHighlightState(std::unique_ptr<HighlightState> highlight_state);
// Exits the current |highlight_state_| and sets it to null. Ensures state
// transitions are not triggered during HighlightStatae::Exit() calls on debug
// builds.
void ExitHighlightState();
// The host of the ink drop. Used to create the ripples and highlights, and to
// add/remove the root layer to/from it.
const raw_ptr<InkDropHost> ink_drop_host_;
// Used by |this| to initialize the starting |highlight_state_| and by the
// current |highlight_state_| to create the next state.
HighlightStateFactory highlight_state_factory_;
// The root Layer that parents the InkDropRipple layers and the
// InkDropHighlight layers. The |root_layer_| is the one that is added and
// removed from the |ink_drop_host_|.
std::unique_ptr<ui::Layer> root_layer_;
// True when the |root_layer_| has been added to the |ink_drop_host_|.
bool root_layer_added_to_host_ = false;
// The current InkDropHighlight. Lazily created using
// CreateInkDropHighlight();
std::unique_ptr<InkDropHighlight> highlight_;
// True denotes the highlight should be shown when |this| is hovered.
bool show_highlight_on_hover_ = true;
// True denotes the highlight should be shown when |this| is focused.
bool show_highlight_on_focus_ = false;
// Tracks the logical hovered state of |this| as manipulated by the public
// SetHovered() function.
bool is_hovered_ = false;
// Tracks the logical focused state of |this| as manipulated by the public
// SetFocused() function.
bool is_focused_ = false;
// The current InkDropRipple. Created on demand using CreateInkDropRipple().
std::unique_ptr<InkDropRipple> ink_drop_ripple_;
// The current state object that handles all inputs that affect the visibility
// of the |highlight_|.
std::unique_ptr<HighlightState> highlight_state_;
// Overrides the default hover highlight fade durations when set.
absl::optional<base::TimeDelta> hover_highlight_fade_duration_;
// Used to ensure highlight state transitions are not triggered when exiting
// the current state.
bool exiting_highlight_state_ = false;
// Used to fail DCHECKS to catch unexpected behavior during tear down.
bool destroying_ = false;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_impl.h | C++ | unknown | 12,186 |
// 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 <memory>
#include "ui/views/animation/ink_drop_impl.h"
#include "base/functional/bind.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/gtest_util.h"
#include "base/test/test_simple_task_runner.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_impl_test_api.h"
#include "ui/views/animation/test/test_ink_drop_host.h"
#include "ui/views/test/views_test_base.h"
namespace views {
// NOTE: The InkDropImpl class is also tested by the InkDropFactoryTest tests.
class InkDropImplTest : public testing::Test {
public:
explicit InkDropImplTest(InkDropImpl::AutoHighlightMode auto_highlight_mode =
InkDropImpl::AutoHighlightMode::NONE);
InkDropImplTest(const InkDropImplTest&) = delete;
InkDropImplTest& operator=(const InkDropImplTest&) = delete;
~InkDropImplTest() override;
protected:
TestInkDropHost* ink_drop_host() { return &ink_drop_host_; }
const TestInkDropHost* ink_drop_host() const { return &ink_drop_host_; }
InkDropImpl* ink_drop() {
return static_cast<InkDropImpl*>(
InkDrop::Get(ink_drop_host())->GetInkDrop());
}
InkDropRipple* ink_drop_ripple() {
return ink_drop()->ink_drop_ripple_.get();
}
InkDropHighlight* ink_drop_highlight() {
return ink_drop()->highlight_.get();
}
test::InkDropImplTestApi* test_api() { return test_api_.get(); }
// Runs all the pending tasks in |task_runner_|. This can be used to progress
// timers. e.g. HideHighlightOnRippleHiddenState's
// |highlight_after_ripple_timer_|.
void RunPendingTasks();
// Returns true if the ink drop layers have been added to |ink_drop_host_|.
bool AreLayersAddedToHost() const;
// Destroys the |ink_drop_| and associated |test_api_|.
void DestroyInkDrop();
// Used to control the tasks scheduled by the InkDropImpl's Timer.
scoped_refptr<base::TestSimpleTaskRunner> task_runner_ =
base::MakeRefCounted<base::TestSimpleTaskRunner>();
// Required by base::Timer's.
std::unique_ptr<base::SingleThreadTaskRunner::CurrentDefaultHandle>
thread_task_runner_handle_ =
std::make_unique<base::SingleThreadTaskRunner::CurrentDefaultHandle>(
task_runner_);
private:
TestInkDropHost ink_drop_host_;
// Allows privileged access to the the |ink_drop_highlight_|.
std::unique_ptr<test::InkDropImplTestApi> test_api_;
std::unique_ptr<base::AutoReset<gfx::Animation::RichAnimationRenderMode>>
animation_mode_reset_ = gfx::AnimationTestApi::SetRichAnimationRenderMode(
gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED);
};
InkDropImplTest::InkDropImplTest(
InkDropImpl::AutoHighlightMode auto_highlight_mode)
: ink_drop_host_(auto_highlight_mode) {
InkDrop::Get(ink_drop_host())->SetMode(views::InkDropHost::InkDropMode::ON);
test_api_ = std::make_unique<test::InkDropImplTestApi>(ink_drop());
ink_drop_host()->set_disable_timers_for_test(true);
}
InkDropImplTest::~InkDropImplTest() = default;
void InkDropImplTest::RunPendingTasks() {
task_runner_->RunPendingTasks();
EXPECT_FALSE(task_runner_->HasPendingTask());
}
bool InkDropImplTest::AreLayersAddedToHost() const {
return ink_drop_host()->num_ink_drop_layers() >= 1;
}
void InkDropImplTest::DestroyInkDrop() {
test_api_.reset();
InkDrop::Get(ink_drop_host())->SetMode(views::InkDropHost::InkDropMode::OFF);
}
// AutoHighlightMode parameterized test fixture.
class InkDropImplAutoHighlightTest
: public InkDropImplTest,
public testing::WithParamInterface<
testing::tuple<InkDropImpl::AutoHighlightMode>> {
public:
InkDropImplAutoHighlightTest();
InkDropImplAutoHighlightTest(const InkDropImplAutoHighlightTest&) = delete;
InkDropImplAutoHighlightTest& operator=(const InkDropImplAutoHighlightTest&) =
delete;
~InkDropImplAutoHighlightTest() override;
};
InkDropImplAutoHighlightTest::InkDropImplAutoHighlightTest()
: InkDropImplTest(testing::get<0>(GetParam())) {}
InkDropImplAutoHighlightTest::~InkDropImplAutoHighlightTest() = default;
////////////////////////////////////////////////////////////////////////////////
//
// InkDropImpl tests
//
TEST_F(InkDropImplTest, ShouldHighlight) {
ink_drop()->SetShowHighlightOnHover(false);
ink_drop()->SetHovered(false);
ink_drop()->SetShowHighlightOnFocus(false);
ink_drop()->SetFocused(false);
EXPECT_FALSE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(true);
ink_drop()->SetHovered(false);
ink_drop()->SetShowHighlightOnFocus(false);
ink_drop()->SetFocused(false);
EXPECT_FALSE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(false);
ink_drop()->SetHovered(true);
ink_drop()->SetShowHighlightOnFocus(false);
ink_drop()->SetFocused(false);
EXPECT_FALSE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(false);
ink_drop()->SetHovered(false);
ink_drop()->SetShowHighlightOnFocus(true);
ink_drop()->SetFocused(false);
EXPECT_FALSE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(false);
ink_drop()->SetHovered(false);
ink_drop()->SetShowHighlightOnFocus(false);
ink_drop()->SetFocused(true);
EXPECT_FALSE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(true);
ink_drop()->SetHovered(true);
ink_drop()->SetShowHighlightOnFocus(false);
ink_drop()->SetFocused(false);
EXPECT_TRUE(test_api()->ShouldHighlight());
ink_drop()->SetShowHighlightOnHover(false);
ink_drop()->SetHovered(false);
ink_drop()->SetShowHighlightOnFocus(true);
ink_drop()->SetFocused(true);
EXPECT_TRUE(test_api()->ShouldHighlight());
test_api()->SetShouldHighlight(false);
EXPECT_FALSE(test_api()->ShouldHighlight());
test_api()->SetShouldHighlight(true);
EXPECT_TRUE(test_api()->ShouldHighlight());
}
TEST_F(InkDropImplTest,
VerifyInkDropLayersRemovedWhenPresentDuringDestruction) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
EXPECT_TRUE(AreLayersAddedToHost());
DestroyInkDrop();
EXPECT_FALSE(AreLayersAddedToHost());
}
// Test that (re-)hiding or un-hovering a hidden ink drop doesn't add layers.
TEST_F(InkDropImplTest, AlwaysHiddenInkDropHasNoLayers) {
EXPECT_FALSE(AreLayersAddedToHost());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
EXPECT_FALSE(AreLayersAddedToHost());
ink_drop()->SetHovered(false);
EXPECT_FALSE(AreLayersAddedToHost());
}
TEST_F(InkDropImplTest, LayersRemovedFromHostAfterHighlight) {
EXPECT_FALSE(AreLayersAddedToHost());
test_api()->SetShouldHighlight(true);
EXPECT_TRUE(AreLayersAddedToHost());
test_api()->CompleteAnimations();
test_api()->SetShouldHighlight(false);
test_api()->CompleteAnimations();
EXPECT_FALSE(AreLayersAddedToHost());
}
TEST_F(InkDropImplTest, LayersRemovedFromHostAfterInkDrop) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
EXPECT_FALSE(AreLayersAddedToHost());
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
EXPECT_TRUE(AreLayersAddedToHost());
test_api()->CompleteAnimations();
ink_drop()->AnimateToState(InkDropState::HIDDEN);
EXPECT_TRUE(AreLayersAddedToHost());
test_api()->CompleteAnimations();
EXPECT_FALSE(AreLayersAddedToHost());
}
TEST_F(InkDropImplTest, LayersArentRemovedWhenPreemptingFadeOut) {
EXPECT_FALSE(AreLayersAddedToHost());
test_api()->SetShouldHighlight(true);
EXPECT_TRUE(AreLayersAddedToHost());
test_api()->CompleteAnimations();
ink_drop()->SetHovered(false);
EXPECT_TRUE(AreLayersAddedToHost());
ink_drop()->SetHovered(true);
EXPECT_TRUE(AreLayersAddedToHost());
}
TEST_F(InkDropImplTest,
SettingHighlightStateDuringStateExitIsntAllowedDeathTest) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
test::InkDropImplTestApi::SetStateOnExitHighlightState::Install(
test_api()->state_factory());
EXPECT_DCHECK_DEATH(
test::InkDropImplTestApi::AccessFactoryOnExitHighlightState::Install(
test_api()->state_factory()));
// Need to set the |highlight_state_| directly because the
// SetStateOnExitHighlightState will recursively try to set it during tear
// down and cause a stack overflow.
test_api()->SetHighlightState(nullptr);
}
// Verifies there are no use after free errors.
TEST_F(InkDropImplTest,
TearingDownHighlightStateThatAccessesTheStateFactoryIsSafe) {
test::InkDropImplTestApi::AccessFactoryOnExitHighlightState::Install(
test_api()->state_factory());
test::InkDropImplTestApi::AccessFactoryOnExitHighlightState::Install(
test_api()->state_factory());
}
// Tests that if during destruction, a ripple animation is successfully ended,
// no crash happens (see https://crbug.com/663579).
TEST_F(InkDropImplTest, SuccessfulAnimationEndedDuringDestruction) {
// Start a ripple animation with non-zero duration.
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
{
// Start another ripple animation with zero duration that would be queued
// until the previous one is finished/aborted.
ui::ScopedAnimationDurationScaleMode duration_mode(
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
ink_drop()->AnimateToState(InkDropState::ACTION_TRIGGERED);
}
// Abort the first animation, so that the queued animation is started (and
// finished immediately since it has zero duration). No crash should happen.
DestroyInkDrop();
}
// Make sure the InkDropRipple and InkDropHighlight get recreated when the host
// size changes (https:://crbug.com/899104).
TEST_F(InkDropImplTest, RippleAndHighlightRecreatedOnSizeChange) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTIVATED);
EXPECT_EQ(1, ink_drop_host()->num_ink_drop_ripples_created());
EXPECT_EQ(1, ink_drop_host()->num_ink_drop_highlights_created());
EXPECT_EQ(ink_drop_host()->last_ink_drop_ripple(), ink_drop_ripple());
EXPECT_EQ(ink_drop_host()->last_ink_drop_highlight(), ink_drop_highlight());
const gfx::Rect bounds(5, 6, 7, 8);
ink_drop_host()->SetBoundsRect(bounds);
EXPECT_EQ(2, ink_drop_host()->num_ink_drop_ripples_created());
EXPECT_EQ(2, ink_drop_host()->num_ink_drop_highlights_created());
EXPECT_EQ(ink_drop_host()->last_ink_drop_ripple(), ink_drop_ripple());
EXPECT_EQ(ink_drop_host()->last_ink_drop_highlight(), ink_drop_highlight());
EXPECT_EQ(bounds.size(), ink_drop_ripple()->GetRootLayer()->size());
EXPECT_EQ(bounds.size(), ink_drop_highlight()->layer()->size());
}
// Verifies that the host's GetHighlighted() method reflects the ink drop's
// highlight state, and when the state changes the ink drop notifies the host.
TEST_F(InkDropImplTest, HostTracksHighlightState) {
bool callback_called = false;
auto subscription =
InkDrop::Get(ink_drop_host())
->AddHighlightedChangedCallback(base::BindRepeating(
[](bool* called) { *called = true; }, &callback_called));
EXPECT_FALSE(InkDrop::Get(ink_drop_host())->GetHighlighted());
test_api()->SetShouldHighlight(true);
EXPECT_TRUE(callback_called);
EXPECT_TRUE(InkDrop::Get(ink_drop_host())->GetHighlighted());
callback_called = false;
test_api()->SetShouldHighlight(false);
EXPECT_TRUE(callback_called);
EXPECT_FALSE(InkDrop::Get(ink_drop_host())->GetHighlighted());
}
////////////////////////////////////////////////////////////////////////////////
//
// Common AutoHighlightMode tests
//
using InkDropImplCommonAutoHighlightTest = InkDropImplAutoHighlightTest;
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(
All,
InkDropImplCommonAutoHighlightTest,
testing::Values(InkDropImpl::AutoHighlightMode::NONE,
InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE,
InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE));
// Verifies InkDropImplTestApi::SetShouldHighlight() works as expected.
TEST_P(InkDropImplCommonAutoHighlightTest,
ShouldHighlightCausesHighlightToBeVisible) {
test_api()->SetShouldHighlight(true);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
test_api()->SetShouldHighlight(false);
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplCommonAutoHighlightTest,
HighlightVisibilityForFocusAndHoverStates) {
ink_drop()->SetShowHighlightOnHover(true);
ink_drop()->SetShowHighlightOnFocus(true);
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetFocused(true);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetHovered(false);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetHovered(true);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetFocused(false);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetHovered(false);
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
////////////////////////////////////////////////////////////////////////////////
//
// InkDropImpl::AutoHighlightMode::NONE specific tests
//
using InkDropImplNoAutoHighlightTest = InkDropImplAutoHighlightTest;
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(All,
InkDropImplNoAutoHighlightTest,
testing::Values(InkDropImpl::AutoHighlightMode::NONE));
TEST_P(InkDropImplNoAutoHighlightTest, VisibleHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplNoAutoHighlightTest, HiddenHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(false);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
////////////////////////////////////////////////////////////////////////////////
//
// InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE specific tests
//
using InkDropImplHideAutoHighlightTest = InkDropImplAutoHighlightTest;
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(
All,
InkDropImplHideAutoHighlightTest,
testing::Values(InkDropImpl::AutoHighlightMode::HIDE_ON_RIPPLE));
TEST_P(InkDropImplHideAutoHighlightTest,
VisibleHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
RunPendingTasks();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest,
HiddenHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(false);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
RunPendingTasks();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest, HighlightIsHiddenOnSnapToActivated) {
test_api()->SetShouldHighlight(true);
ink_drop()->SnapToActivated();
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
RunPendingTasks();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest,
HighlightDoesntFadeInAfterAnimationIfHighlightNotSet) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_TRIGGERED);
test_api()->CompleteAnimations();
test_api()->SetShouldHighlight(false);
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
RunPendingTasks();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest,
HighlightFadesInAfterAnimationIfHovered) {
ink_drop()->SetShowHighlightOnHover(true);
ink_drop()->SetHovered(true);
ink_drop()->AnimateToState(InkDropState::ACTION_TRIGGERED);
test_api()->CompleteAnimations();
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
EXPECT_TRUE(task_runner_->HasPendingTask());
RunPendingTasks();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest,
HighlightSnapsInAfterAnimationWhenHostIsFocused) {
ink_drop()->SetShowHighlightOnFocus(true);
ink_drop()->SetFocused(true);
ink_drop()->AnimateToState(InkDropState::ACTION_TRIGGERED);
test_api()->CompleteAnimations();
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_FALSE(task_runner_->HasPendingTask());
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplHideAutoHighlightTest, DeactivatedAnimatesWhenNotFocused) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
test_api()->SetShouldHighlight(false);
ink_drop()->AnimateToState(InkDropState::ACTIVATED);
test_api()->CompleteAnimations();
ink_drop()->AnimateToState(InkDropState::DEACTIVATED);
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
EXPECT_TRUE(test_api()->HasActiveAnimations());
}
TEST_P(InkDropImplHideAutoHighlightTest,
DeactivatedAnimationSkippedWhenFocused) {
ink_drop()->SetShowHighlightOnFocus(true);
ink_drop()->SetFocused(true);
ink_drop()->AnimateToState(InkDropState::ACTIVATED);
test_api()->CompleteAnimations();
ink_drop()->AnimateToState(InkDropState::DEACTIVATED);
EXPECT_TRUE(AreLayersAddedToHost());
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
EXPECT_EQ(InkDropState::HIDDEN, ink_drop()->GetTargetInkDropState());
}
TEST_P(InkDropImplHideAutoHighlightTest,
FocusAndHoverChangesDontShowHighlightWhenRippleIsVisible) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetHovered(false);
ink_drop()->SetFocused(false);
ink_drop()->SetHovered(true);
ink_drop()->SetFocused(true);
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
EXPECT_TRUE(test_api()->ShouldHighlight());
}
// Verifies there is no crash when animations are started during the destruction
// of the InkDropRipple. See https://crbug.com/663335.
TEST_P(InkDropImplHideAutoHighlightTest, NoCrashDuringRippleTearDown) {
ink_drop()->SetShowHighlightOnFocus(true);
ink_drop()->SetFocused(true);
ink_drop()->AnimateToState(InkDropState::ACTIVATED);
ink_drop()->AnimateToState(InkDropState::DEACTIVATED);
ink_drop()->AnimateToState(InkDropState::DEACTIVATED);
DestroyInkDrop();
}
////////////////////////////////////////////////////////////////////////////////
//
// InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE specific tests
//
using InkDropImplShowAutoHighlightTest = InkDropImplAutoHighlightTest;
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(
All,
InkDropImplShowAutoHighlightTest,
testing::Values(InkDropImpl::AutoHighlightMode::SHOW_ON_RIPPLE));
TEST_P(InkDropImplShowAutoHighlightTest,
VisibleHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplShowAutoHighlightTest,
HiddenHighlightDuringRippleAnimations) {
test_api()->SetShouldHighlight(false);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->AnimateToState(InkDropState::HIDDEN);
test_api()->CompleteAnimations();
EXPECT_FALSE(test_api()->IsHighlightFadingInOrVisible());
}
TEST_P(InkDropImplShowAutoHighlightTest,
FocusAndHoverChangesDontHideHighlightWhenRippleIsVisible) {
test_api()->SetShouldHighlight(true);
ink_drop()->AnimateToState(InkDropState::ACTION_PENDING);
test_api()->CompleteAnimations();
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
ink_drop()->SetHovered(false);
ink_drop()->SetFocused(false);
EXPECT_TRUE(test_api()->IsHighlightFadingInOrVisible());
EXPECT_FALSE(test_api()->ShouldHighlight());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_impl_unittest.cc | C++ | unknown | 22,164 |
// 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/animation/ink_drop_mask.h"
#include "cc/paint/paint_flags.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/gfx/canvas.h"
namespace views {
InkDropMask::InkDropMask(const gfx::Size& layer_size)
: layer_(ui::LAYER_TEXTURED) {
layer_.set_delegate(this);
layer_.SetBounds(gfx::Rect(layer_size));
layer_.SetFillsBoundsOpaquely(false);
layer_.SetName("InkDropMaskLayer");
}
InkDropMask::~InkDropMask() {
layer_.set_delegate(nullptr);
}
void InkDropMask::OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {}
PathInkDropMask::PathInkDropMask(const gfx::Size& layer_size,
const SkPath& path)
: InkDropMask(layer_size), path_(path) {}
void PathInkDropMask::OnPaintLayer(const ui::PaintContext& context) {
cc::PaintFlags flags;
flags.setAlphaf(1.0f);
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setAntiAlias(true);
ui::PaintRecorder recorder(context, layer()->size());
recorder.canvas()->DrawPath(path_, flags);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_mask.cc | C++ | unknown | 1,260 |
// 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_ANIMATION_INK_DROP_MASK_H_
#define UI_VIEWS_ANIMATION_INK_DROP_MASK_H_
#include "base/gtest_prod_util.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/views/views_export.h"
class SkPath;
namespace views {
// Base class for different ink drop masks. It is responsible for creating the
// ui::Layer that can be set as the mask layer for ink drop layer. Note that the
// mask's layer size (passed in the constructor) should always match size of the
// layer it is masking.
class VIEWS_EXPORT InkDropMask : public ui::LayerDelegate {
public:
InkDropMask(const InkDropMask&) = delete;
InkDropMask& operator=(const InkDropMask&) = delete;
~InkDropMask() override;
ui::Layer* layer() { return &layer_; }
protected:
explicit InkDropMask(const gfx::Size& layer_size);
private:
// ui::LayerDelegate:
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
ui::Layer layer_;
};
// An ink-drop mask that paints a specified path.
class VIEWS_EXPORT PathInkDropMask : public InkDropMask {
public:
PathInkDropMask(const gfx::Size& layer_size, const SkPath& path);
PathInkDropMask(const PathInkDropMask&) = delete;
PathInkDropMask& operator=(const PathInkDropMask&) = delete;
private:
FRIEND_TEST_ALL_PREFIXES(InkDropMaskTest, PathInkDropMaskPaintsTriangle);
// InkDropMask:
void OnPaintLayer(const ui::PaintContext& context) override;
SkPath path_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_MASK_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_mask.h | C++ | unknown | 1,742 |
// 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/animation/ink_drop_mask.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "cc/paint/display_item_list.h"
#include "cc/paint/paint_op_buffer_iterator.h"
#include "cc/paint/paint_record.h"
#include "cc/test/paint_op_matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "ui/compositor/paint_context.h"
namespace views {
using ::cc::PaintOpIs;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::ExplainMatchResult;
using ::testing::ResultOf;
using ::testing::UnorderedElementsAreArray;
MATCHER_P(PointsAre, expected, "") {
int expected_size = expected.size();
if (arg.countPoints() != expected_size) {
*result_listener << "Expected path to have " << expected_size
<< " points, but had " << arg.countPoints() << ".";
return false;
}
std::vector<SkPoint> actual(expected_size);
if (arg.getPoints(&actual.front(), expected_size) != expected_size) {
*result_listener << "Failed extracting " << expected.size()
<< " points from path.";
return false;
}
return ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
result_listener);
}
TEST(InkDropMaskTest, PathInkDropMaskPaintsTriangle) {
gfx::Size layer_size(10, 10);
SkPath path;
std::vector<SkPoint> points = {SkPoint::Make(3, 3), SkPoint::Make(5, 6),
SkPoint::Make(8, 1)};
path.moveTo(points[0].x(), points[0].y());
path.lineTo(points[1].x(), points[1].y());
path.lineTo(points[2].x(), points[2].y());
path.close();
PathInkDropMask mask(layer_size, path);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
mask.OnPaintLayer(
ui::PaintContext(list.get(), 1.f, gfx::Rect(layer_size), false));
EXPECT_EQ(1u, list->num_paint_ops()) << list->ToString();
cc::PaintRecord record = list->FinalizeAndReleaseAsRecord();
EXPECT_THAT(
record,
ElementsAre(AllOf(
PaintOpIs<cc::DrawRecordOp>(),
ResultOf(
[](const cc::PaintOp& op) {
return static_cast<const cc::DrawRecordOp&>(op).record;
},
ElementsAre(AllOf(
PaintOpIs<cc::DrawPathOp>(),
ResultOf(
[](const cc::PaintOp& op) {
return static_cast<const cc::DrawPathOp&>(op).path;
},
PointsAre(points))))))));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_mask_unittest.cc | C++ | unknown | 2,740 |
// 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_ANIMATION_INK_DROP_OBSERVER_H_
#define UI_VIEWS_ANIMATION_INK_DROP_OBSERVER_H_
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace views {
// Observer to attach to an InkDrop.
class VIEWS_EXPORT InkDropObserver {
public:
InkDropObserver(const InkDropObserver&) = delete;
InkDropObserver& operator=(const InkDropObserver&) = delete;
// Called when the animation of the current InkDrop has started. This
// includes the ripple or highlight animation. Note: this is not guaranteed to
// be notified, as the notification is dependent on the subclass
// implementation.
virtual void InkDropAnimationStarted() = 0;
// Called when the animation to the provided ink drop state has ended (both if
// the animation ended successfully, and if the animation was aborted).
// Includes ripple animation only.
// NOTE: this is not guaranteed to be notified, as the notification is
// dependent on the subclass implementation.
// |ink_drop_state| - The state to which the ink drop ripple was animating.
virtual void InkDropRippleAnimationEnded(InkDropState ink_drop_state) = 0;
protected:
InkDropObserver() = default;
virtual ~InkDropObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_observer.h | C++ | unknown | 1,459 |
// 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/animation/ink_drop_painted_layer_delegates.h"
#include <vector>
#include "cc/paint/paint_canvas.h"
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkDrawLooper.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/skia_paint_util.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
//
// BasePaintedLayerDelegate
//
BasePaintedLayerDelegate::BasePaintedLayerDelegate(SkColor color)
: color_(color) {}
BasePaintedLayerDelegate::~BasePaintedLayerDelegate() = default;
gfx::Vector2dF BasePaintedLayerDelegate::GetCenteringOffset() const {
return gfx::RectF(GetPaintedBounds()).CenterPoint().OffsetFromOrigin();
}
void BasePaintedLayerDelegate::OnDeviceScaleFactorChanged(
float old_device_scale_factor,
float new_device_scale_factor) {}
////////////////////////////////////////////////////////////////////////////////
//
// CircleLayerDelegate
//
CircleLayerDelegate::CircleLayerDelegate(SkColor color, int radius)
: BasePaintedLayerDelegate(color), radius_(radius) {}
CircleLayerDelegate::~CircleLayerDelegate() = default;
gfx::RectF CircleLayerDelegate::GetPaintedBounds() const {
const int diameter = radius_ * 2;
return gfx::RectF(0, 0, diameter, diameter);
}
void CircleLayerDelegate::OnPaintLayer(const ui::PaintContext& context) {
cc::PaintFlags flags;
flags.setColor(color());
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
ui::PaintRecorder recorder(context,
gfx::ToEnclosingRect(GetPaintedBounds()).size());
gfx::Canvas* canvas = recorder.canvas();
canvas->DrawCircle(GetPaintedBounds().CenterPoint(), radius_, flags);
}
////////////////////////////////////////////////////////////////////////////////
//
// RectangleLayerDelegate
//
RectangleLayerDelegate::RectangleLayerDelegate(SkColor color, gfx::SizeF size)
: BasePaintedLayerDelegate(color), size_(size) {}
RectangleLayerDelegate::~RectangleLayerDelegate() = default;
gfx::RectF RectangleLayerDelegate::GetPaintedBounds() const {
return gfx::RectF(size_);
}
void RectangleLayerDelegate::OnPaintLayer(const ui::PaintContext& context) {
cc::PaintFlags flags;
flags.setColor(color());
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
ui::PaintRecorder recorder(context, gfx::ToCeiledSize(size_));
gfx::Canvas* canvas = recorder.canvas();
canvas->DrawRect(GetPaintedBounds(), flags);
}
////////////////////////////////////////////////////////////////////////////////
//
// RoundedRectangleLayerDelegate
//
RoundedRectangleLayerDelegate::RoundedRectangleLayerDelegate(
SkColor color,
const gfx::SizeF& size,
int corner_radius)
: BasePaintedLayerDelegate(color),
size_(size),
corner_radius_(corner_radius) {}
RoundedRectangleLayerDelegate::~RoundedRectangleLayerDelegate() = default;
gfx::RectF RoundedRectangleLayerDelegate::GetPaintedBounds() const {
return gfx::RectF(size_);
}
void RoundedRectangleLayerDelegate::OnPaintLayer(
const ui::PaintContext& context) {
cc::PaintFlags flags;
flags.setColor(color());
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
ui::PaintRecorder recorder(context, gfx::ToCeiledSize(size_));
const float dsf = recorder.canvas()->UndoDeviceScaleFactor();
gfx::RectF rect = GetPaintedBounds();
rect.Scale(dsf);
recorder.canvas()->DrawRoundRect(gfx::ToEnclosingRect(rect),
dsf * corner_radius_, flags);
}
////////////////////////////////////////////////////////////////////////////////
//
// BorderShadowLayerDelegate
//
BorderShadowLayerDelegate::BorderShadowLayerDelegate(
const std::vector<gfx::ShadowValue>& shadows,
const gfx::Rect& shadowed_area_bounds,
SkColor fill_color,
int corner_radius)
: BasePaintedLayerDelegate(gfx::kPlaceholderColor),
shadows_(shadows),
bounds_(shadowed_area_bounds),
fill_color_(fill_color),
corner_radius_(corner_radius) {}
BorderShadowLayerDelegate::~BorderShadowLayerDelegate() = default;
gfx::RectF BorderShadowLayerDelegate::GetPaintedBounds() const {
gfx::Rect total_rect(bounds_);
total_rect.Inset(gfx::ShadowValue::GetMargin(shadows_));
return gfx::RectF(total_rect);
}
gfx::Vector2dF BorderShadowLayerDelegate::GetCenteringOffset() const {
return gfx::RectF(bounds_).CenterPoint().OffsetFromOrigin();
}
void BorderShadowLayerDelegate::OnPaintLayer(const ui::PaintContext& context) {
cc::PaintFlags flags;
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setAntiAlias(true);
flags.setColor(fill_color_);
gfx::RectF rrect_bounds =
gfx::RectF(bounds_) - GetPaintedBounds().OffsetFromOrigin();
SkRRect r_rect = SkRRect::MakeRectXY(gfx::RectFToSkRect(rrect_bounds),
corner_radius_, corner_radius_);
// First the fill color.
ui::PaintRecorder recorder(context,
gfx::ToCeiledSize(GetPaintedBounds().size()));
recorder.canvas()->sk_canvas()->drawRRect(r_rect, flags);
// Now the shadow.
flags.setLooper(gfx::CreateShadowDrawLooper(shadows_));
recorder.canvas()->sk_canvas()->clipRRect(r_rect, SkClipOp::kDifference,
true);
recorder.canvas()->sk_canvas()->drawRRect(r_rect, flags);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_painted_layer_delegates.cc | C++ | unknown | 5,987 |
// 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_ANIMATION_INK_DROP_PAINTED_LAYER_DELEGATES_H_
#define UI_VIEWS_ANIMATION_INK_DROP_PAINTED_LAYER_DELEGATES_H_
#include <vector>
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/shadow_value.h"
#include "ui/views/views_export.h"
namespace views {
// Base ui::LayerDelegate stub that can be extended to paint shapes of a
// specific color.
class VIEWS_EXPORT BasePaintedLayerDelegate : public ui::LayerDelegate {
public:
BasePaintedLayerDelegate(const BasePaintedLayerDelegate&) = delete;
BasePaintedLayerDelegate& operator=(const BasePaintedLayerDelegate&) = delete;
~BasePaintedLayerDelegate() override;
// Defines the bounds of the layer that the delegate will paint into.
virtual gfx::RectF GetPaintedBounds() const = 0;
// Defines how to place the layer by providing an offset from the origin of
// the parent to the visual center of the layer.
virtual gfx::Vector2dF GetCenteringOffset() const;
// ui::LayerDelegate:
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
SkColor color() const { return color_; }
void set_color(SkColor color) { color_ = color; }
protected:
explicit BasePaintedLayerDelegate(SkColor color);
private:
// The color to paint.
SkColor color_;
};
// A BasePaintedLayerDelegate that paints a circle of a specified color and
// radius.
class VIEWS_EXPORT CircleLayerDelegate : public BasePaintedLayerDelegate {
public:
CircleLayerDelegate(SkColor color, int radius);
CircleLayerDelegate(const CircleLayerDelegate&) = delete;
CircleLayerDelegate& operator=(const CircleLayerDelegate&) = delete;
~CircleLayerDelegate() override;
int radius() const { return radius_; }
// BasePaintedLayerDelegate:
gfx::RectF GetPaintedBounds() const override;
void OnPaintLayer(const ui::PaintContext& context) override;
private:
// The radius of the circle.
int radius_;
};
// A BasePaintedLayerDelegate that paints a rectangle of a specified color and
// size.
class VIEWS_EXPORT RectangleLayerDelegate : public BasePaintedLayerDelegate {
public:
RectangleLayerDelegate(SkColor color, gfx::SizeF size);
RectangleLayerDelegate(const RectangleLayerDelegate&) = delete;
RectangleLayerDelegate& operator=(const RectangleLayerDelegate&) = delete;
~RectangleLayerDelegate() override;
const gfx::SizeF& size() const { return size_; }
// BasePaintedLayerDelegate:
gfx::RectF GetPaintedBounds() const override;
void OnPaintLayer(const ui::PaintContext& context) override;
private:
// The size of the rectangle.
gfx::SizeF size_;
};
// A BasePaintedLayerDelegate that paints a rounded rectangle of a specified
// color, size and corner radius.
class VIEWS_EXPORT RoundedRectangleLayerDelegate
: public BasePaintedLayerDelegate {
public:
RoundedRectangleLayerDelegate(SkColor color,
const gfx::SizeF& size,
int corner_radius);
RoundedRectangleLayerDelegate(const RoundedRectangleLayerDelegate&) = delete;
RoundedRectangleLayerDelegate& operator=(
const RoundedRectangleLayerDelegate&) = delete;
~RoundedRectangleLayerDelegate() override;
const gfx::SizeF& size() const { return size_; }
// BasePaintedLayerDelegate:
gfx::RectF GetPaintedBounds() const override;
void OnPaintLayer(const ui::PaintContext& context) override;
private:
// The size of the rectangle.
gfx::SizeF size_;
// The radius of the corners.
int corner_radius_;
};
// A BasePaintedLayerDelegate that paints a shadow around the outside of a
// specified roundrect, and also fills the round rect.
class VIEWS_EXPORT BorderShadowLayerDelegate : public BasePaintedLayerDelegate {
public:
BorderShadowLayerDelegate(const std::vector<gfx::ShadowValue>& shadows,
const gfx::Rect& shadowed_area_bounds,
SkColor fill_color,
int corner_radius);
BorderShadowLayerDelegate(const BorderShadowLayerDelegate&) = delete;
BorderShadowLayerDelegate& operator=(const BorderShadowLayerDelegate&) =
delete;
~BorderShadowLayerDelegate() override;
// BasePaintedLayerDelegate:
gfx::RectF GetPaintedBounds() const override;
gfx::Vector2dF GetCenteringOffset() const override;
void OnPaintLayer(const ui::PaintContext& context) override;
private:
gfx::Rect GetTotalRect() const;
const std::vector<gfx::ShadowValue> shadows_;
// The bounds of the shadowed area.
const gfx::Rect bounds_;
const SkColor fill_color_;
const int corner_radius_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_PAINTED_LAYER_DELEGATES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_painted_layer_delegates.h | C++ | unknown | 5,029 |
// 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/animation/ink_drop_ripple.h"
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "ui/base/ui_base_switches.h"
#include "ui/compositor/callback_layer_animation_observer.h"
#include "ui/compositor/layer.h"
namespace views {
const float InkDropRipple::kHiddenOpacity = 0.f;
InkDropRipple::InkDropRipple(InkDropHost* ink_drop_host)
: ink_drop_host_(ink_drop_host) {}
InkDropRipple::~InkDropRipple() = default;
void InkDropRipple::AnimateToState(InkDropState ink_drop_state) {
// Does not return early if |target_ink_drop_state_| == |ink_drop_state| for
// two reasons.
// 1. The attached observers must be notified of all animations started and
// ended.
// 2. Not all state transitions is are valid, especially no-op transitions,
// and these invalid transitions will be logged as warnings in
// AnimateStateChange().
animation_observer_ = CreateAnimationObserver(ink_drop_state);
InkDropState old_ink_drop_state = target_ink_drop_state_;
// Assign to |target_ink_drop_state_| before calling AnimateStateChange() so
// that any observers notified as a side effect of the AnimateStateChange()
// will get the target InkDropState when calling GetInkDropState().
target_ink_drop_state_ = ink_drop_state;
if (old_ink_drop_state == InkDropState::HIDDEN &&
target_ink_drop_state_ != InkDropState::HIDDEN) {
GetRootLayer()->SetVisible(true);
}
AnimateStateChange(old_ink_drop_state, target_ink_drop_state_);
animation_observer_->SetActive();
// |this| may be deleted! |animation_observer_| might synchronously call
// AnimationEndedCallback which can delete |this|.
}
void InkDropRipple::SnapToState(InkDropState ink_drop_state) {
AbortAllAnimations();
if (ink_drop_state == InkDropState::ACTIVATED)
GetRootLayer()->SetVisible(true);
else if (ink_drop_state == InkDropState::HIDDEN)
SetStateToHidden();
target_ink_drop_state_ = ink_drop_state;
animation_observer_ = CreateAnimationObserver(ink_drop_state);
animation_observer_->SetActive();
// |this| may be deleted! |animation_observer_| might synchronously call
// AnimationEndedCallback which can delete |this|.
}
void InkDropRipple::SnapToActivated() {
SnapToState(InkDropState::ACTIVATED);
}
bool InkDropRipple::IsVisible() {
return GetRootLayer()->visible();
}
void InkDropRipple::SnapToHidden() {
SnapToState(InkDropState::HIDDEN);
}
test::InkDropRippleTestApi* InkDropRipple::GetTestApi() {
return nullptr;
}
ui::LayerAnimationObserver* InkDropRipple::GetLayerAnimationObserver() {
return animation_observer_.get();
}
InkDropHost* InkDropRipple::GetInkDropHost() const {
return ink_drop_host_.get();
}
void InkDropRipple::AnimationStartedCallback(
InkDropState ink_drop_state,
const ui::CallbackLayerAnimationObserver& observer) {
if (observer_)
observer_->AnimationStarted(ink_drop_state);
}
bool InkDropRipple::AnimationEndedCallback(
InkDropState ink_drop_state,
const ui::CallbackLayerAnimationObserver& observer) {
if (ink_drop_state == InkDropState::HIDDEN)
SetStateToHidden();
if (observer_)
observer_->AnimationEnded(ink_drop_state,
observer.aborted_count()
? InkDropAnimationEndedReason::PRE_EMPTED
: InkDropAnimationEndedReason::SUCCESS);
// |this| may be deleted!
return false;
}
std::unique_ptr<ui::CallbackLayerAnimationObserver>
InkDropRipple::CreateAnimationObserver(InkDropState ink_drop_state) {
return std::make_unique<ui::CallbackLayerAnimationObserver>(
base::BindRepeating(&InkDropRipple::AnimationStartedCallback,
base::Unretained(this), ink_drop_state),
base::BindRepeating(&InkDropRipple::AnimationEndedCallback,
base::Unretained(this), ink_drop_state));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_ripple.cc | C++ | unknown | 4,094 |
// 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_ANIMATION_INK_DROP_RIPPLE_H_
#define UI_VIEWS_ANIMATION_INK_DROP_RIPPLE_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop_ripple_observer.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace ui {
class CallbackLayerAnimationObserver;
class Layer;
class LayerAnimationObserver;
} // namespace ui
namespace views {
class InkDropHost;
namespace test {
class InkDropRippleTestApi;
} // namespace test
// Simple base class for animations that provide visual feedback for View state.
// Manages the attached InkDropRippleObservers.
//
// TODO(bruthig): Document the ink drop ripple on chromium.org and add a link to
// the doc here.
class VIEWS_EXPORT InkDropRipple {
public:
// The opacity of the ink drop when it is not visible.
static const float kHiddenOpacity;
explicit InkDropRipple(InkDropHost* ink_drop_host);
InkDropRipple(const InkDropRipple&) = delete;
InkDropRipple& operator=(const InkDropRipple&) = delete;
virtual ~InkDropRipple();
// In the event that an animation is in progress for ink drop state 's1' and
// an animation to a new state 's2' is triggered, then
// AnimationEnded(s1, PRE_EMPTED) will be called before
// AnimationStarted(s2).
void set_observer(InkDropRippleObserver* observer) { observer_ = observer; }
// Animates from the current InkDropState to the new |ink_drop_state|.
//
// NOTE: GetTargetInkDropState() should return the new |ink_drop_state| value
// to any observers being notified as a result of the call.
void AnimateToState(InkDropState ink_drop_state);
// Snaps from the current InkDropState to the new |ink_drop_state|.
void SnapToState(InkDropState ink_drop_state);
InkDropState target_ink_drop_state() const { return target_ink_drop_state_; }
// Immediately aborts all in-progress animations and hides the ink drop.
//
// NOTE: This will NOT raise Animation(Started|Ended) events for the state
// transition to HIDDEN!
void SnapToHidden();
// Immediately snaps the ink drop to the ACTIVATED target state. All pending
// animations are aborted. Events will be raised for the pending animations
// as well as the transition to the ACTIVATED state.
virtual void SnapToActivated();
// The root Layer that can be added in to a Layer tree.
virtual ui::Layer* GetRootLayer() = 0;
// Returns true when the ripple is visible. This is different from checking if
// the ink_drop_state() == HIDDEN because the ripple may be visible while it
// animates to the target HIDDEN state.
bool IsVisible();
// Returns a test api to access internals of this. Default implmentations
// should return nullptr and test specific subclasses can override to return
// an instance.
virtual test::InkDropRippleTestApi* GetTestApi();
protected:
// Animates the ripple from the |old_ink_drop_state| to the
// |new_ink_drop_state|. |observer| is added to all LayerAnimationSequence's
// used if not null.
virtual void AnimateStateChange(InkDropState old_ink_drop_state,
InkDropState new_ink_drop_state) = 0;
// Updates the transforms, opacity, and visibility to a HIDDEN state.
virtual void SetStateToHidden() = 0;
virtual void AbortAllAnimations() = 0;
// Get the current observer. CreateAnimationObserver must have already been
// called.
ui::LayerAnimationObserver* GetLayerAnimationObserver();
// Get the InkDropHost associated this ripple.
InkDropHost* GetInkDropHost() const;
private:
// The Callback invoked when all of the animation sequences for the specific
// |ink_drop_state| animation have started. |observer| is the
// ui::CallbackLayerAnimationObserver which is notifying the callback.
void AnimationStartedCallback(
InkDropState ink_drop_state,
const ui::CallbackLayerAnimationObserver& observer);
// The Callback invoked when all of the animation sequences for the specific
// |ink_drop_state| animation have finished. |observer| is the
// ui::CallbackLayerAnimationObserver which is notifying the callback.
bool AnimationEndedCallback(
InkDropState ink_drop_state,
const ui::CallbackLayerAnimationObserver& observer);
// Creates a new animation observer bound to AnimationStartedCallback() and
// AnimationEndedCallback().
std::unique_ptr<ui::CallbackLayerAnimationObserver> CreateAnimationObserver(
InkDropState ink_drop_state);
// The target InkDropState.
InkDropState target_ink_drop_state_ = InkDropState::HIDDEN;
raw_ptr<InkDropRippleObserver> observer_ = nullptr;
std::unique_ptr<ui::CallbackLayerAnimationObserver> animation_observer_;
// Reference to the host on which this ripple resides.
raw_ptr<InkDropHost> ink_drop_host_ = nullptr;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_RIPPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_ripple.h | C++ | unknown | 5,096 |
// 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_ANIMATION_INK_DROP_RIPPLE_OBSERVER_H_
#define UI_VIEWS_ANIMATION_INK_DROP_RIPPLE_OBSERVER_H_
#include "ui/views/animation/ink_drop_animation_ended_reason.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace views {
// Observer to attach to an InkDropRipple.
class VIEWS_EXPORT InkDropRippleObserver {
public:
InkDropRippleObserver(const InkDropRippleObserver&) = delete;
InkDropRippleObserver& operator=(const InkDropRippleObserver&) = delete;
// An animation for the given |ink_drop_state| has started.
virtual void AnimationStarted(InkDropState ink_drop_state) = 0;
// Notifies the observer that an animation for the given |ink_drop_state| has
// finished and the reason for completion is given by |reason|. If |reason| is
// SUCCESS then the animation has progressed to its final frame however if
// |reason| is |PRE_EMPTED| then the animation was stopped before its final
// frame.
virtual void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) = 0;
protected:
InkDropRippleObserver() = default;
virtual ~InkDropRippleObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_RIPPLE_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_ripple_observer.h | C++ | unknown | 1,424 |
// 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/animation/ink_drop_ripple.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop_ripple_observer.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/animation/test/flood_fill_ink_drop_ripple_test_api.h"
#include "ui/views/animation/test/ink_drop_ripple_test_api.h"
#include "ui/views/animation/test/square_ink_drop_ripple_test_api.h"
#include "ui/views/animation/test/test_ink_drop_ripple_observer.h"
namespace views::test {
const float kVisibleOpacity = 0.175f;
// Represents all the derivatives of the InkDropRipple class. To be used with
// the InkDropRippleTest fixture to test all derviatives.
enum InkDropRippleTestTypes {
SQUARE_INK_DROP_RIPPLE,
FLOOD_FILL_INK_DROP_RIPPLE
};
// Test fixture for all InkDropRipple class derivatives.
//
// To add a new derivative:
// 1. Add a value to the InkDropRippleTestTypes enum.
// 2. Implement set up and tear down code for the new enum value in
// InkDropRippleTest() and
// ~InkDropRippleTest().
// 3. Add the new enum value to the INSTANTIATE_TEST_SUITE_P) Values list.
class InkDropRippleTest
: public testing::TestWithParam<InkDropRippleTestTypes> {
public:
InkDropRippleTest();
InkDropRippleTest(const InkDropRippleTest&) = delete;
InkDropRippleTest& operator=(const InkDropRippleTest&) = delete;
~InkDropRippleTest() override;
protected:
TestInkDropRippleObserver observer_;
std::unique_ptr<InkDropRipple> ink_drop_ripple_;
std::unique_ptr<InkDropRippleTestApi> test_api_;
std::unique_ptr<base::AutoReset<gfx::Animation::RichAnimationRenderMode>>
animation_mode_reset_;
};
InkDropRippleTest::InkDropRippleTest()
: animation_mode_reset_(gfx::AnimationTestApi::SetRichAnimationRenderMode(
gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED)) {
switch (GetParam()) {
case SQUARE_INK_DROP_RIPPLE: {
SquareInkDropRipple* square_ink_drop_ripple = new SquareInkDropRipple(
nullptr, gfx::Size(10, 10), 2, gfx::Size(8, 8), 1, gfx::Point(),
SK_ColorBLACK, kVisibleOpacity);
ink_drop_ripple_.reset(square_ink_drop_ripple);
test_api_ =
std::make_unique<SquareInkDropRippleTestApi>(square_ink_drop_ripple);
break;
}
case FLOOD_FILL_INK_DROP_RIPPLE: {
FloodFillInkDropRipple* flood_fill_ink_drop_ripple =
new FloodFillInkDropRipple(nullptr, gfx::Size(10, 10), gfx::Point(),
SK_ColorBLACK, kVisibleOpacity);
ink_drop_ripple_.reset(flood_fill_ink_drop_ripple);
test_api_ = std::make_unique<FloodFillInkDropRippleTestApi>(
flood_fill_ink_drop_ripple);
break;
}
}
ink_drop_ripple_->set_observer(&observer_);
observer_.set_ink_drop_ripple(ink_drop_ripple_.get());
test_api_->SetDisableAnimationTimers(true);
}
InkDropRippleTest::~InkDropRippleTest() = default;
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(All,
InkDropRippleTest,
testing::Values(SQUARE_INK_DROP_RIPPLE,
FLOOD_FILL_INK_DROP_RIPPLE));
TEST_P(InkDropRippleTest, InitialStateAfterConstruction) {
EXPECT_EQ(views::InkDropState::HIDDEN,
ink_drop_ripple_->target_ink_drop_state());
}
// Verify no animations are used when animating from HIDDEN to HIDDEN.
TEST_P(InkDropRippleTest, AnimateToHiddenFromInvisibleState) {
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_ripple_->target_ink_drop_state());
ink_drop_ripple_->AnimateToState(InkDropState::HIDDEN);
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
EXPECT_FALSE(ink_drop_ripple_->IsVisible());
}
TEST_P(InkDropRippleTest, AnimateToHiddenFromVisibleState) {
ink_drop_ripple_->AnimateToState(InkDropState::ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_NE(InkDropState::HIDDEN, ink_drop_ripple_->target_ink_drop_state());
ink_drop_ripple_->AnimateToState(InkDropState::HIDDEN);
test_api_->CompleteAnimations();
EXPECT_EQ(3, observer_.last_animation_started_ordinal());
EXPECT_EQ(4, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, ActionPendingOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(kVisibleOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, QuickActionOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_TRIGGERED);
test_api_->CompleteAnimations();
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, SlowActionPendingOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(
views::InkDropState::ALTERNATE_ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(kVisibleOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, SlowActionOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(
views::InkDropState::ALTERNATE_ACTION_PENDING);
ink_drop_ripple_->AnimateToState(
views::InkDropState::ALTERNATE_ACTION_TRIGGERED);
test_api_->CompleteAnimations();
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, ActivatedOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTIVATED);
test_api_->CompleteAnimations();
EXPECT_EQ(kVisibleOpacity, test_api_->GetCurrentOpacity());
}
TEST_P(InkDropRippleTest, DeactivatedOpacity) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTIVATED);
ink_drop_ripple_->AnimateToState(views::InkDropState::DEACTIVATED);
test_api_->CompleteAnimations();
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
}
// Verify animations are aborted during deletion and the
// InkDropRippleObservers are notified.
TEST_P(InkDropRippleTest, AnimationsAbortedDuringDeletion) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
ink_drop_ripple_.reset();
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(views::InkDropState::ACTION_PENDING,
observer_.last_animation_ended_context());
EXPECT_EQ(InkDropAnimationEndedReason::PRE_EMPTED,
observer_.last_animation_ended_reason());
}
TEST_P(InkDropRippleTest, VerifyObserversAreNotified) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_ripple_->AnimateToState(InkDropState::ACTION_PENDING);
EXPECT_TRUE(test_api_->HasActiveAnimations());
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_TRUE(observer_.AnimationHasNotEnded());
EXPECT_EQ(InkDropState::ACTION_PENDING,
observer_.last_animation_started_context());
test_api_->CompleteAnimations();
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropState::ACTION_PENDING,
observer_.last_animation_ended_context());
}
TEST_P(InkDropRippleTest, VerifyObserversAreNotifiedOfSuccessfulAnimations) {
ink_drop_ripple_->AnimateToState(InkDropState::ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropAnimationEndedReason::SUCCESS,
observer_.last_animation_ended_reason());
}
TEST_P(InkDropRippleTest, VerifyObserversAreNotifiedOfPreemptedAnimations) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_ripple_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING);
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropAnimationEndedReason::PRE_EMPTED,
observer_.last_animation_ended_reason());
}
TEST_P(InkDropRippleTest, InkDropStatesPersistWhenCallingAnimateToState) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTIVATED);
EXPECT_EQ(views::InkDropState::ACTIVATED,
ink_drop_ripple_->target_ink_drop_state());
}
TEST_P(InkDropRippleTest, SnapToHiddenWithoutActiveAnimations) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_NE(InkDropState::HIDDEN, ink_drop_ripple_->target_ink_drop_state());
ink_drop_ripple_->SnapToHidden();
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_EQ(views::InkDropState::HIDDEN,
ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(3, observer_.last_animation_started_ordinal());
EXPECT_EQ(4, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
EXPECT_FALSE(ink_drop_ripple_->IsVisible());
}
// Verifies all active animations are aborted and the InkDropState is set to
// HIDDEN after invoking SnapToHidden().
TEST_P(InkDropRippleTest, SnapToHiddenWithActiveAnimations) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
EXPECT_TRUE(test_api_->HasActiveAnimations());
EXPECT_NE(InkDropState::HIDDEN, ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
ink_drop_ripple_->SnapToHidden();
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_EQ(views::InkDropState::HIDDEN,
ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropState::ACTION_PENDING,
observer_.last_animation_ended_context());
EXPECT_EQ(InkDropAnimationEndedReason::PRE_EMPTED,
observer_.last_animation_ended_reason());
EXPECT_EQ(InkDropRipple::kHiddenOpacity, test_api_->GetCurrentOpacity());
EXPECT_FALSE(ink_drop_ripple_->IsVisible());
}
TEST_P(InkDropRippleTest, SnapToActivatedWithoutActiveAnimations) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
test_api_->CompleteAnimations();
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
EXPECT_EQ(2, observer_.last_animation_ended_ordinal());
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_NE(InkDropState::ACTIVATED, ink_drop_ripple_->target_ink_drop_state());
ink_drop_ripple_->SnapToActivated();
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_EQ(views::InkDropState::ACTIVATED,
ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(3, observer_.last_animation_started_ordinal());
EXPECT_EQ(4, observer_.last_animation_ended_ordinal());
EXPECT_EQ(kVisibleOpacity, test_api_->GetCurrentOpacity());
EXPECT_TRUE(ink_drop_ripple_->IsVisible());
}
// Verifies all active animations are aborted and the InkDropState is set to
// ACTIVATED after invoking SnapToActivated().
TEST_P(InkDropRippleTest, SnapToActivatedWithActiveAnimations) {
// TODO(bruthig): Re-enable! For some reason these tests fail on some win
// trunk builds. See crbug.com/731811.
if (!gfx::Animation::ShouldRenderRichAnimation())
return;
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
EXPECT_TRUE(test_api_->HasActiveAnimations());
EXPECT_NE(InkDropState::ACTIVATED, ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(1, observer_.last_animation_started_ordinal());
ink_drop_ripple_->SnapToActivated();
EXPECT_FALSE(test_api_->HasActiveAnimations());
EXPECT_EQ(views::InkDropState::ACTIVATED,
ink_drop_ripple_->target_ink_drop_state());
EXPECT_EQ(3, observer_.last_animation_started_ordinal());
EXPECT_EQ(4, observer_.last_animation_ended_ordinal());
EXPECT_EQ(InkDropState::ACTIVATED, observer_.last_animation_ended_context());
EXPECT_EQ(InkDropAnimationEndedReason::SUCCESS,
observer_.last_animation_ended_reason());
EXPECT_EQ(kVisibleOpacity, test_api_->GetCurrentOpacity());
EXPECT_TRUE(ink_drop_ripple_->IsVisible());
}
TEST_P(InkDropRippleTest, AnimateToVisibleFromHidden) {
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_ripple_->target_ink_drop_state());
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
EXPECT_TRUE(ink_drop_ripple_->IsVisible());
}
// Verifies that the value of InkDropRipple::target_ink_drop_state() returns
// the most recent value passed to AnimateToState() when notifying observers
// that an animation has started within the AnimateToState() function call.
TEST_P(InkDropRippleTest, TargetInkDropStateOnAnimationStarted) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
EXPECT_TRUE(observer_.AnimationHasStarted());
EXPECT_EQ(views::InkDropState::ACTION_PENDING,
observer_.target_state_at_last_animation_started());
// Animation would end if rich_animation_rendering_mode is disabled.
if (gfx::Animation::ShouldRenderRichAnimation())
EXPECT_FALSE(observer_.AnimationHasEnded());
ink_drop_ripple_->AnimateToState(views::InkDropState::HIDDEN);
EXPECT_TRUE(observer_.AnimationHasStarted());
EXPECT_EQ(views::InkDropState::HIDDEN,
observer_.target_state_at_last_animation_started());
}
// Verifies that the value of InkDropRipple::target_ink_drop_state() returns
// the most recent value passed to AnimateToState() when notifying observers
// that an animation has ended within the AnimateToState() function call.
TEST_P(InkDropRippleTest, TargetInkDropStateOnAnimationEnded) {
ink_drop_ripple_->AnimateToState(views::InkDropState::ACTION_PENDING);
// Animation would end if rich_animation_rendering_mode is disabled.
if (gfx::Animation::ShouldRenderRichAnimation())
EXPECT_FALSE(observer_.AnimationHasEnded());
ink_drop_ripple_->AnimateToState(views::InkDropState::HIDDEN);
test_api_->CompleteAnimations();
EXPECT_TRUE(observer_.AnimationHasEnded());
EXPECT_EQ(views::InkDropState::HIDDEN,
observer_.target_state_at_last_animation_ended());
}
// Verifies that when an we ink drop transitions from ACTION_PENDING to
// ACTIVATED state, animation observers are called in order.
TEST_P(InkDropRippleTest, RipplePendingToActivatedObserverOrder) {
ink_drop_ripple_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_ripple_->AnimateToState(InkDropState::ACTIVATED);
test_api_->CompleteAnimations();
EXPECT_TRUE(observer_.AnimationStartedContextsMatch(
{InkDropState::ACTION_PENDING, InkDropState::ACTIVATED}));
EXPECT_TRUE(observer_.AnimationEndedContextsMatch(
{InkDropState::ACTION_PENDING, InkDropState::ACTIVATED}));
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_ripple_unittest.cc | C++ | unknown | 16,457 |
// 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/animation/ink_drop_state.h"
#include <ostream>
#include <string>
#include "base/notreached.h"
namespace views {
std::string ToString(InkDropState state) {
switch (state) {
case InkDropState::HIDDEN:
return std::string("HIDDEN");
case InkDropState::ACTION_PENDING:
return std::string("ACTION_PENDING");
case InkDropState::ACTION_TRIGGERED:
return std::string("ACTION_TRIGGERED");
case InkDropState::ALTERNATE_ACTION_PENDING:
return std::string("ALTERNATE_ACTION_PENDING");
case InkDropState::ALTERNATE_ACTION_TRIGGERED:
return std::string("ALTERNATE_ACTION_TRIGGERED");
case InkDropState::ACTIVATED:
return std::string("ACTIVATED");
case InkDropState::DEACTIVATED:
return std::string("DEACTIVATED");
}
NOTREACHED_NORETURN();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_state.cc | C++ | unknown | 992 |
// 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_ANIMATION_INK_DROP_STATE_H_
#define UI_VIEWS_ANIMATION_INK_DROP_STATE_H_
#include <iosfwd>
#include <string>
#include "ui/views/views_export.h"
namespace views {
// The different states that the ink drop animation can be animated to.
enum class InkDropState {
// The ink drop is not visible.
HIDDEN,
// The view is being interacted with but the action to be triggered has not
// yet been determined, e.g. a mouse button down.
ACTION_PENDING,
// The quick action for the view has been triggered, e.g. a tap gesture or a
// mouse click on a button.
ACTION_TRIGGERED,
// A view is being interacted with and the pending action will be a secondary
// action, e.g. a long press.
ALTERNATE_ACTION_PENDING,
// The alternate action for the view has been triggered, e.g. a long press
// release to bring up a menu.
ALTERNATE_ACTION_TRIGGERED,
// An active state for a view that is not currently being interacted with.
// e.g. a pressed button that is showing a menu.
ACTIVATED,
// A previously active state has been toggled to inactive, e.g. a drop down
// menu is closed.
DEACTIVATED,
};
// Returns a human readable string for |state|. Useful for logging.
VIEWS_EXPORT std::string ToString(InkDropState state);
// This is declared here for use in gtest-based unit tests but is defined in
// the views_test_support target. Depend on that to use this in your unit test.
// This should not be used in production code - call ToString() instead.
void PrintTo(InkDropState ink_drop_state, ::std::ostream* os);
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_STATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_state.h | C++ | unknown | 1,775 |
// 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/animation/ink_drop_stub.h"
namespace views {
InkDropStub::InkDropStub() = default;
InkDropStub::~InkDropStub() = default;
void InkDropStub::HostSizeChanged(const gfx::Size& new_size) {}
void InkDropStub::HostTransformChanged(const gfx::Transform& new_transform) {}
InkDropState InkDropStub::GetTargetInkDropState() const {
return InkDropState::HIDDEN;
}
void InkDropStub::AnimateToState(InkDropState state) {}
void InkDropStub::SetHoverHighlightFadeDuration(base::TimeDelta duration) {}
void InkDropStub::UseDefaultHoverHighlightFadeDuration() {}
void InkDropStub::SnapToActivated() {}
void InkDropStub::SnapToHidden() {}
void InkDropStub::SetHovered(bool is_hovered) {}
void InkDropStub::SetFocused(bool is_hovered) {}
bool InkDropStub::IsHighlightFadingInOrVisible() const {
return false;
}
void InkDropStub::SetShowHighlightOnHover(bool show_highlight_on_hover) {}
void InkDropStub::SetShowHighlightOnFocus(bool show_highlight_on_focus) {}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_stub.cc | C++ | unknown | 1,149 |
// 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_ANIMATION_INK_DROP_STUB_H_
#define UI_VIEWS_ANIMATION_INK_DROP_STUB_H_
#include "ui/views/animation/ink_drop.h"
#include "ui/views/views_export.h"
namespace views {
// A stub implementation of an InkDrop that can be used when no visuals should
// be shown. e.g. material design is enabled.
class VIEWS_EXPORT InkDropStub : public InkDrop {
public:
InkDropStub();
InkDropStub(const InkDropStub&) = delete;
InkDropStub& operator=(const InkDropStub&) = delete;
~InkDropStub() override;
// InkDrop:
void HostSizeChanged(const gfx::Size& new_size) override;
void HostTransformChanged(const gfx::Transform& new_transform) override;
InkDropState GetTargetInkDropState() const override;
void AnimateToState(InkDropState state) override;
void SetHoverHighlightFadeDuration(base::TimeDelta duration) override;
void UseDefaultHoverHighlightFadeDuration() override;
void SnapToActivated() override;
void SnapToHidden() override;
void SetHovered(bool is_hovered) override;
void SetFocused(bool is_hovered) override;
bool IsHighlightFadingInOrVisible() const override;
void SetShowHighlightOnHover(bool show_highlight_on_hover) override;
void SetShowHighlightOnFocus(bool show_highlight_on_focus) override;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_STUB_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_stub.h | C++ | unknown | 1,471 |
// 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 <memory>
#include "base/task/single_thread_task_runner.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/timer/timer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.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_state.h"
#include "ui/views/animation/ink_drop_stub.h"
#include "ui/views/animation/test/test_ink_drop_host.h"
namespace views::test {
// Enumeration of all the different InkDrop types.
enum InkDropType { INK_DROP_STUB, INK_DROP_IMPL };
class InkDropTest : public testing::TestWithParam<testing::tuple<InkDropType>> {
public:
InkDropTest();
InkDropTest(const InkDropTest&) = delete;
InkDropTest& operator=(const InkDropTest&) = delete;
~InkDropTest() override;
protected:
// A dummy InkDropHost required to create an InkDrop.
TestInkDropHost test_ink_drop_host_;
// The InkDrop returned by the InkDropFactory test target.
std::unique_ptr<InkDrop> ink_drop_;
private:
// Extracts and returns the InkDropType from the test parameters.
InkDropType GetInkDropType() const;
std::unique_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_;
// Required by base::Timer's.
std::unique_ptr<base::SingleThreadTaskRunner::CurrentDefaultHandle>
thread_task_runner_current_default_handle_;
};
InkDropTest::InkDropTest() : ink_drop_(nullptr) {
zero_duration_mode_ = std::make_unique<ui::ScopedAnimationDurationScaleMode>(
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
switch (GetInkDropType()) {
case INK_DROP_STUB:
ink_drop_ = std::make_unique<InkDropStub>();
break;
case INK_DROP_IMPL:
ink_drop_ = std::make_unique<InkDropImpl>(
InkDrop::Get(&test_ink_drop_host_), gfx::Size(),
InkDropImpl::AutoHighlightMode::NONE);
// The Timer's used by the InkDropImpl class require a
// base::SingleThreadTaskRunner::CurrentDefaultHandle instance.
scoped_refptr<base::TestMockTimeTaskRunner> task_runner(
new base::TestMockTimeTaskRunner);
thread_task_runner_current_default_handle_ =
std::make_unique<base::SingleThreadTaskRunner::CurrentDefaultHandle>(
task_runner);
break;
}
}
InkDropTest::~InkDropTest() = default;
InkDropType InkDropTest::GetInkDropType() const {
return testing::get<0>(GetParam());
}
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_SUITE_P(All,
InkDropTest,
testing::Values(INK_DROP_STUB, INK_DROP_IMPL));
TEST_P(InkDropTest,
VerifyInkDropLayersRemovedAfterDestructionWhenRippleIsActive) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_.reset();
EXPECT_EQ(0, test_ink_drop_host_.num_ink_drop_layers());
}
TEST_P(InkDropTest, StateIsHiddenInitially) {
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, TypicalQuickAction) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ACTION_TRIGGERED);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, CancelQuickAction) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::HIDDEN);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, TypicalSlowAction) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ALTERNATE_ACTION_TRIGGERED);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, CancelSlowAction) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::HIDDEN);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, TypicalQuickActivated) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ACTIVATED);
ink_drop_->AnimateToState(InkDropState::DEACTIVATED);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
TEST_P(InkDropTest, TypicalSlowActivated) {
ink_drop_->AnimateToState(InkDropState::ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ALTERNATE_ACTION_PENDING);
ink_drop_->AnimateToState(InkDropState::ACTIVATED);
ink_drop_->AnimateToState(InkDropState::DEACTIVATED);
EXPECT_EQ(InkDropState::HIDDEN, ink_drop_->GetTargetInkDropState());
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_unittest.cc | C++ | unknown | 4,997 |
// 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/animation/ink_drop_util.h"
#include <cmath>
#include "base/check_op.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/view.h"
#include "ui/views/views_features.h"
namespace views {
gfx::Transform GetTransformSubpixelCorrection(const gfx::Transform& transform,
float device_scale_factor) {
gfx::PointF origin = transform.MapPoint(gfx::PointF());
const gfx::Vector2dF offset_in_dip = origin.OffsetFromOrigin();
// Scale the origin to screen space
origin.Scale(device_scale_factor);
// Compute the rounded offset in screen space and finally unscale it back to
// DIP space.
gfx::Vector2dF aligned_offset_in_dip = origin.OffsetFromOrigin();
aligned_offset_in_dip.set_x(std::round(aligned_offset_in_dip.x()));
aligned_offset_in_dip.set_y(std::round(aligned_offset_in_dip.y()));
aligned_offset_in_dip.InvScale(device_scale_factor);
// Compute the subpixel offset correction and apply it to the transform.
gfx::Transform subpixel_correction;
subpixel_correction.Translate(aligned_offset_in_dip - offset_in_dip);
#if DCHECK_IS_ON()
const float kEpsilon = 0.0001f;
gfx::Transform transform_corrected(transform);
transform_corrected.PostConcat(subpixel_correction);
gfx::Point3F offset = transform_corrected.MapPoint(gfx::Point3F());
offset.Scale(device_scale_factor);
if (!std::isnan(offset.x()))
DCHECK_LT(std::abs(std::round(offset.x()) - offset.x()), kEpsilon);
if (!std::isnan(offset.y()))
DCHECK_LT(std::abs(std::round(offset.y()) - offset.y()), kEpsilon);
#endif
return subpixel_correction;
}
bool UsingPlatformHighContrastInkDrop(const View* view) {
return view->GetWidget() &&
view->GetNativeTheme()->GetDefaultSystemColorScheme() ==
ui::NativeTheme::ColorScheme::kPlatformHighContrast &&
base::FeatureList::IsEnabled(
features::kEnablePlatformHighContrastInkDrop);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_util.cc | C++ | unknown | 2,236 |
// 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_ANIMATION_INK_DROP_UTIL_H_
#define UI_VIEWS_ANIMATION_INK_DROP_UTIL_H_
#include "ui/views/views_export.h"
namespace gfx {
class Transform;
} // namespace gfx
namespace views {
class View;
// A layer |transform| may add an offset to its layer relative to the parent
// layer. This offset does not take into consideration the subpixel positioning.
// A subpixel correction needs to be applied to make sure the layers are pixel
// aligned after the transform is applied. Use this function to compute the
// subpixel correction transform.
VIEWS_EXPORT gfx::Transform GetTransformSubpixelCorrection(
const gfx::Transform& transform,
float device_scale_factor);
VIEWS_EXPORT bool UsingPlatformHighContrastInkDrop(const View* view);
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/ink_drop_util.h | C++ | unknown | 972 |
// 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/animation/scroll_animator.h"
#include <algorithm>
#include <cmath>
#include "base/check.h"
#include "ui/gfx/animation/slide_animation.h"
namespace {
constexpr float kDefaultAcceleration = -1500.0f; // in pixels per second^2
// Assumes that d0 == 0.0f
float GetPosition(float v0, float a, float t) {
float max_t = -v0 / a;
if (t > max_t)
t = max_t;
return t * (v0 + 0.5f * a * t);
}
float GetDelta(float v0, float a, float t1, float t2) {
return GetPosition(v0, a, t2) - GetPosition(v0, a, t1);
}
} // namespace
namespace views {
ScrollAnimator::ScrollAnimator(ScrollDelegate* delegate)
: delegate_(delegate), acceleration_(kDefaultAcceleration) {
DCHECK(delegate);
}
ScrollAnimator::~ScrollAnimator() {
Stop();
}
void ScrollAnimator::Start(float velocity_x, float velocity_y) {
if (acceleration_ >= 0.0f)
acceleration_ = kDefaultAcceleration;
float v = std::max(fabs(velocity_x), fabs(velocity_y));
last_t_ = 0.0f;
velocity_x_ = velocity_x * velocity_multiplier_;
velocity_y_ = velocity_y * velocity_multiplier_;
duration_ = -v / acceleration_; // in seconds
animation_ = std::make_unique<gfx::SlideAnimation>(this);
animation_->SetSlideDuration(base::Seconds(duration_));
animation_->Show();
}
void ScrollAnimator::Stop() {
velocity_x_ = velocity_y_ = last_t_ = duration_ = 0.0f;
animation_.reset();
}
void ScrollAnimator::AnimationEnded(const gfx::Animation* animation) {
Stop();
delegate_->OnFlingScrollEnded();
}
void ScrollAnimator::AnimationProgressed(const gfx::Animation* animation) {
float t = static_cast<float>(animation->GetCurrentValue()) * duration_;
float a_x = velocity_x_ > 0 ? acceleration_ : -acceleration_;
float a_y = velocity_y_ > 0 ? acceleration_ : -acceleration_;
float dx = GetDelta(velocity_x_, a_x, last_t_, t);
float dy = GetDelta(velocity_y_, a_y, last_t_, t);
last_t_ = t;
delegate_->OnScroll(dx, dy);
}
void ScrollAnimator::AnimationCanceled(const gfx::Animation* animation) {
Stop();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/scroll_animator.cc | C++ | unknown | 2,188 |
// 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_ANIMATION_SCROLL_ANIMATOR_H_
#define UI_VIEWS_ANIMATION_SCROLL_ANIMATOR_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/animation/animation_delegate.h"
#include "ui/views/views_export.h"
namespace gfx {
class SlideAnimation;
}
namespace views {
class VIEWS_EXPORT ScrollDelegate {
public:
// Returns true if the content was actually scrolled, false otherwise.
virtual bool OnScroll(float dx, float dy) = 0;
// Called when the contents scrolled by the fling event ended.
virtual void OnFlingScrollEnded() {}
protected:
~ScrollDelegate() = default;
};
class VIEWS_EXPORT ScrollAnimator : public gfx::AnimationDelegate {
public:
// The ScrollAnimator does not own the delegate. Uses default acceleration.
explicit ScrollAnimator(ScrollDelegate* delegate);
ScrollAnimator(const ScrollAnimator&) = delete;
ScrollAnimator& operator=(const ScrollAnimator&) = delete;
~ScrollAnimator() override;
// Use this if you would prefer different acceleration than the default.
void set_acceleration(float acceleration) { acceleration_ = acceleration; }
// Use this if you would prefer different velocity than the default.
void set_velocity_multiplier(float velocity_multiplier) {
velocity_multiplier_ = velocity_multiplier;
}
void Start(float velocity_x, float velocity_y);
void Stop();
bool is_scrolling() const { return !!animation_.get(); }
private:
// Implementation of gfx::AnimationDelegate.
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
raw_ptr<ScrollDelegate> delegate_;
float velocity_x_{0.f};
float velocity_y_{0.f};
float velocity_multiplier_{1.f};
float last_t_{0.f};
float duration_{0.f};
float acceleration_;
std::unique_ptr<gfx::SlideAnimation> animation_;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_SCROLL_ANIMATOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/scroll_animator.h | C++ | unknown | 2,153 |
// 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/animation/slide_out_controller.h"
#include <algorithm>
#include "base/functional/bind.h"
#include "base/task/single_thread_task_runner.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/slide_out_controller_delegate.h"
namespace views {
namespace {
constexpr base::TimeDelta kSwipeRestoreDuration = base::Milliseconds(150);
constexpr int kSwipeOutTotalDurationMs = 150;
gfx::Tween::Type kSwipeTweenType = gfx::Tween::EASE_IN;
// When we have a swipe control, we will close the target if it is slid more
// than this amount plus the width of the swipe control.
constexpr int kSwipeCloseMargin = 64;
} // anonymous namespace
SlideOutController::SlideOutController(ui::EventTarget* target,
SlideOutControllerDelegate* delegate)
: target_handling_(target, this), delegate_(delegate) {}
SlideOutController::~SlideOutController() = default;
void SlideOutController::CaptureControlOpenState() {
if (!has_swipe_control_)
return;
if ((mode_ == SlideMode::kFull || mode_ == SlideMode::kPartial) &&
fabs(gesture_amount_) >= swipe_control_width_) {
control_open_state_ = gesture_amount_ < 0
? SwipeControlOpenState::kOpenOnRight
: SwipeControlOpenState::kOpenOnLeft;
} else {
control_open_state_ = SwipeControlOpenState::kClosed;
}
}
void SlideOutController::OnGestureEvent(ui::GestureEvent* event) {
ui::Layer* layer = delegate_->GetSlideOutLayer();
int width = layer->bounds().width();
float scroll_amount_for_closing_notification =
has_swipe_control_ ? swipe_control_width_ + kSwipeCloseMargin
: width * 0.5;
if (event->type() == ui::ET_SCROLL_FLING_START) {
// The threshold for the fling velocity is computed empirically.
// The unit is in pixels/second.
const float kFlingThresholdForClose = 800.f;
if (mode_ == SlideMode::kFull &&
fabsf(event->details().velocity_x()) > kFlingThresholdForClose) {
SlideOutAndClose(event->details().velocity_x());
event->StopPropagation();
return;
}
CaptureControlOpenState();
RestoreVisualState();
return;
}
if (!event->IsScrollGestureEvent())
return;
if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN) {
switch (control_open_state_) {
case SwipeControlOpenState::kClosed:
gesture_amount_ = 0.f;
break;
case SwipeControlOpenState::kOpenOnRight:
gesture_amount_ = -swipe_control_width_;
break;
case SwipeControlOpenState::kOpenOnLeft:
gesture_amount_ = swipe_control_width_;
break;
default:
NOTREACHED_NORETURN();
}
delegate_->OnSlideStarted();
} else if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
// The scroll-update events include the incremental scroll amount.
gesture_amount_ += event->details().scroll_x();
float scroll_amount;
float opacity;
switch (mode_) {
case SlideMode::kFull:
scroll_amount = gesture_amount_;
opacity = 1.f - std::min(fabsf(scroll_amount) / width, 1.f);
break;
case SlideMode::kNone:
scroll_amount = 0.f;
opacity = 1.f;
break;
case SlideMode::kPartial:
if (gesture_amount_ >= 0) {
scroll_amount = std::min(0.5f * gesture_amount_,
scroll_amount_for_closing_notification);
} else {
scroll_amount =
std::max(0.5f * gesture_amount_,
-1.f * scroll_amount_for_closing_notification);
}
opacity = 1.f;
break;
}
SetOpacityIfNecessary(opacity);
gfx::Transform transform;
transform.Translate(scroll_amount, 0.0);
layer->SetTransform(transform);
delegate_->OnSlideChanged(true);
} else if (event->type() == ui::ET_GESTURE_SCROLL_END) {
float scrolled_ratio = fabsf(gesture_amount_) / width;
if (mode_ == SlideMode::kFull &&
scrolled_ratio >= scroll_amount_for_closing_notification / width) {
SlideOutAndClose(gesture_amount_);
event->StopPropagation();
return;
}
CaptureControlOpenState();
RestoreVisualState();
}
event->SetHandled();
}
void SlideOutController::RestoreVisualState() {
// Restore the layer state.
gfx::Transform transform;
switch (control_open_state_) {
case SwipeControlOpenState::kClosed:
gesture_amount_ = 0.f;
break;
case SwipeControlOpenState::kOpenOnRight:
gesture_amount_ = -swipe_control_width_;
transform.Translate(-swipe_control_width_, 0);
break;
case SwipeControlOpenState::kOpenOnLeft:
gesture_amount_ = swipe_control_width_;
transform.Translate(swipe_control_width_, 0);
break;
}
SetOpacityIfNecessary(1.f);
SetTransformWithAnimationIfNecessary(transform, kSwipeRestoreDuration);
}
void SlideOutController::SlideOutAndClose(int direction) {
ui::Layer* layer = delegate_->GetSlideOutLayer();
gfx::Transform transform;
int width = layer->bounds().width();
transform.Translate(direction < 0 ? -width : width, 0.0);
int swipe_out_duration = kSwipeOutTotalDurationMs * opacity_;
SetOpacityIfNecessary(0.f);
SetTransformWithAnimationIfNecessary(transform,
base::Milliseconds(swipe_out_duration));
}
void SlideOutController::SetOpacityIfNecessary(float opacity) {
if (update_opacity_)
delegate_->GetSlideOutLayer()->SetOpacity(opacity);
opacity_ = opacity;
}
void SlideOutController::SetTransformWithAnimationIfNecessary(
const gfx::Transform& transform,
base::TimeDelta animation_duration) {
ui::Layer* layer = delegate_->GetSlideOutLayer();
if (layer->transform() != transform) {
// Notify slide changed with inprogress=true, since the element will slide
// with animation. OnSlideChanged(false) will be called after animation.
delegate_->OnSlideChanged(true);
// An animation starts. OnAnimationsCompleted will be called just
// after the animation finishes.
AnimationBuilder()
.OnEnded(base::BindOnce(&SlideOutController::OnAnimationsCompleted,
weak_ptr_factory_.GetWeakPtr()))
.Once()
.SetDuration(animation_duration)
.SetTransform(layer, transform, kSwipeTweenType);
} else {
// Notify slide changed after the animation finishes.
// The argument in_progress is true if the target view is back at the
// origin or has been gone. False if the target is visible but not at
// the origin. False if the target is visible but not at
// the origin.
const bool in_progress = !layer->transform().IsIdentity();
delegate_->OnSlideChanged(in_progress);
}
}
void SlideOutController::OnAnimationsCompleted() {
// Here the situation is either of:
// 1) Notification is slided out and is about to be removed
// => |in_progress| is false, calling OnSlideOut
// 2) Notification is at the origin => |in_progress| is false
// 3) Notification is snapped to the swipe control => |in_progress| is true
const bool is_completely_slid_out = (opacity_ == 0);
const bool in_progress =
!delegate_->GetSlideOutLayer()->transform().IsIdentity() &&
!is_completely_slid_out;
delegate_->OnSlideChanged(in_progress);
if (!is_completely_slid_out)
return;
// Call SlideOutControllerDelegate::OnSlideOut() if this animation came from
// SlideOutAndClose().
// OnImplicitAnimationsCompleted is called from BeginMainFrame, so we should
// delay operation that might result in deletion of LayerTreeHost.
// https://crbug.com/895883
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&SlideOutController::OnSlideOut,
weak_ptr_factory_.GetWeakPtr()));
}
void SlideOutController::OnSlideOut() {
delegate_->OnSlideOut();
}
void SlideOutController::SetSwipeControlWidth(int swipe_control_width) {
swipe_control_width_ = swipe_control_width;
has_swipe_control_ = (swipe_control_width != 0);
}
void SlideOutController::CloseSwipeControl() {
if (!has_swipe_control_)
return;
gesture_amount_ = 0;
CaptureControlOpenState();
RestoreVisualState();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/slide_out_controller.cc | C++ | unknown | 8,589 |
// 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_ANIMATION_SLIDE_OUT_CONTROLLER_H_
#define UI_VIEWS_ANIMATION_SLIDE_OUT_CONTROLLER_H_
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/events/scoped_target_handler.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace views {
class SlideOutControllerDelegate;
// This class contains logic to control sliding out of a layer in response to
// swipes, i.e. gesture scroll events.
class VIEWS_EXPORT SlideOutController : public ui::EventHandler {
public:
// Indicates how much the target layer is allowed to slide. See
// |OnGestureEvent()| for details.
enum class SlideMode {
kFull, // Fully allow sliding until it's swiped out.
kPartial, // Partially allow sliding until the slide amount reaches the
// swipe-out threshold.
kNone, // Don't allow sliding at all.
};
SlideOutController(ui::EventTarget* target,
SlideOutControllerDelegate* delegate);
SlideOutController(const SlideOutController&) = delete;
SlideOutController& operator=(const SlideOutController&) = delete;
~SlideOutController() override;
void set_update_opacity(bool update_opacity) {
update_opacity_ = update_opacity;
}
void set_slide_mode(SlideMode mode) {
// TODO(yoshiki): Close the slide when the slide mode sets to NO_SLIDE.
mode_ = mode;
}
float gesture_amount() const { return gesture_amount_; }
SlideMode mode() const { return mode_; }
// ui::EventHandler
void OnGestureEvent(ui::GestureEvent* event) override;
// Enables the swipe control with specifying the width of buttons. Buttons
// will appear behind the view as user slides it partially and it's kept open
// after the gesture.
void SetSwipeControlWidth(int swipe_control_width);
float GetGestureAmount() const { return gesture_amount_; }
// Moves slide back to the center position to closes the swipe control.
// Effective only when swipe control is enabled by |SetSwipeControlWidth()|.
void CloseSwipeControl();
// Slides the view out and closes it after the animation. The sign of
// |direction| indicates which way the slide occurs.
void SlideOutAndClose(int direction);
private:
// Positions where the slided view stays after the touch released.
enum class SwipeControlOpenState { kClosed, kOpenOnLeft, kOpenOnRight };
// Restores the transform and opacity of the view.
void RestoreVisualState();
// Decides which position the slide should go back after touch is released.
void CaptureControlOpenState();
// Sets the opacity of the slide out layer if |update_opacity_| is true.
void SetOpacityIfNecessary(float opacity);
// Sets the transform matrix and performs animation if the matrix is changed.
void SetTransformWithAnimationIfNecessary(const gfx::Transform& transform,
base::TimeDelta animation_duration);
// Called asynchronously after the slide out animation completes to inform the
// delegate.
void OnSlideOut();
void OnAnimationsCompleted();
ui::ScopedTargetHandler target_handling_;
// Unowned and outlives this object.
raw_ptr<SlideOutControllerDelegate> delegate_;
// Cumulative scroll amount since the beginning of current slide gesture.
// Includes the initial shift when swipe control was open at gesture start.
float gesture_amount_ = 0.f;
// Whether or not this view can be slided and/or swiped out.
SlideMode mode_ = SlideMode::kFull;
// Whether the swipe control is enabled. See |SetSwipeControlWidth()|.
// Effective only when |mode_| is FULL or PARTIAL.
bool has_swipe_control_ = false;
// The horizontal position offset to for swipe control.
// See |SetSwipeControlWidth()|.
int swipe_control_width_ = 0;
// The position where the slided view stays after the touch released.
// Changed only when |mode_| is FULL or PARTIAL and |has_swipe_control_| is
// true.
SwipeControlOpenState control_open_state_ = SwipeControlOpenState::kClosed;
// If false, it doesn't update the opacity.
bool update_opacity_ = true;
// Last opacity set by SetOpacityIfNecessary.
float opacity_ = 1.0;
base::WeakPtrFactory<SlideOutController> weak_ptr_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_SLIDE_OUT_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/slide_out_controller.h | C++ | unknown | 4,466 |
// 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_ANIMATION_SLIDE_OUT_CONTROLLER_DELEGATE_H_
#define UI_VIEWS_ANIMATION_SLIDE_OUT_CONTROLLER_DELEGATE_H_
#include "ui/views/views_export.h"
namespace ui {
class Layer;
} // namespace ui
namespace views {
class VIEWS_EXPORT SlideOutControllerDelegate {
public:
// Returns the layer for slide operations.
virtual ui::Layer* GetSlideOutLayer() = 0;
// Called when a manual slide starts.
virtual void OnSlideStarted() {}
// Called when a manual slide updates or ends. The argument is true if the
// slide starts or in progress, false if it ends.
virtual void OnSlideChanged(bool in_progress) = 0;
// Called when user intends to close the View by sliding it out.
virtual void OnSlideOut() = 0;
protected:
virtual ~SlideOutControllerDelegate() = default;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_SLIDE_OUT_CONTROLLER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/slide_out_controller_delegate.h | C++ | unknown | 1,029 |
// 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/animation/slide_out_controller.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/compositor/layer.h"
#include "ui/views/animation/slide_out_controller_delegate.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
namespace views {
namespace {
constexpr int kSwipeControlWidth = 30; // px
constexpr int kTargetWidth = 200; // px
} // namespace
class TestSlideOutControllerDelegate : public SlideOutControllerDelegate {
public:
explicit TestSlideOutControllerDelegate(View* target) : target_(target) {}
~TestSlideOutControllerDelegate() override = default;
ui::Layer* GetSlideOutLayer() override { return target_->layer(); }
void OnSlideStarted() override { ++slide_started_count_; }
void OnSlideChanged(bool in_progress) override {
slide_changed_last_value_ = in_progress;
++slide_changed_count_;
}
bool IsOnSlideChangedCalled() const { return (slide_changed_count_ > 0); }
void OnSlideOut() override { ++slide_out_count_; }
void reset() {
slide_started_count_ = 0;
slide_changed_count_ = 0;
slide_out_count_ = 0;
slide_changed_last_value_ = absl::nullopt;
}
absl::optional<bool> slide_changed_last_value_;
int slide_started_count_ = 0;
int slide_changed_count_ = 0;
int slide_out_count_ = 0;
private:
const raw_ptr<View> target_;
};
class SlideOutControllerTest : public ViewsTestBase {
public:
SlideOutControllerTest() = default;
~SlideOutControllerTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
widget_->Init(std::move(params));
View* root = widget_->GetRootView();
View* target_ = new View();
target_->SetPaintToLayer(ui::LAYER_TEXTURED);
target_->SetSize(gfx::Size(kTargetWidth, 50));
root->AddChildView(target_);
widget_->Show();
delegate_ = std::make_unique<TestSlideOutControllerDelegate>(target_);
slide_out_controller_ =
std::make_unique<SlideOutController>(target_, delegate_.get());
}
void TearDown() override {
slide_out_controller_.reset();
delegate_.reset();
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
SlideOutController* slide_out_controller() {
return slide_out_controller_.get();
}
TestSlideOutControllerDelegate* delegate() { return delegate_.get(); }
void PostSequentialGestureEvent(const ui::GestureEventDetails& details) {
// Set the timestamp ahead one microsecond.
sequential_event_timestamp_ += base::Microseconds(1);
ui::GestureEvent gesture_event(
0, 0, ui::EF_NONE, base::TimeTicks() + sequential_event_timestamp_,
details);
slide_out_controller()->OnGestureEvent(&gesture_event);
}
void PostSequentialSwipeEvent(int swipe_amount) {
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, swipe_amount, 0));
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
}
private:
std::unique_ptr<Widget> widget_;
std::unique_ptr<SlideOutController> slide_out_controller_;
std::unique_ptr<TestSlideOutControllerDelegate> delegate_;
base::TimeDelta sequential_event_timestamp_;
};
TEST_F(SlideOutControllerTest, OnGestureEventAndDelegate) {
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
TEST_F(SlideOutControllerTest, SlideOutAndClose) {
// Place a finger on notification.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_EQ(0, delegate()->slide_changed_count_);
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Move the finger horizontally by 101 px. (101 px is more than half of the
// target width 200 px)
PostSequentialGestureEvent(ui::GestureEventDetails(
ui::ET_GESTURE_SCROLL_UPDATE, kTargetWidth / 2 + 1, 0));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Release the finger.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
// The target has been scrolled out and the current location is moved by the
// width (200px).
EXPECT_EQ(kTargetWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure a deferred OnSlideOut handler is called.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(1, delegate()->slide_out_count_);
}
TEST_F(SlideOutControllerTest, SlideLittleAmountAndNotClose) {
// Place a finger on notification.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Move the finger horizontally by 99 px. (99 px is less than half of the
// target width 200 px)
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 99, 0));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Release the finger.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
// The target has been moved back to the origin.
EXPECT_EQ(0.f,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred SlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
class SwipeControlTest
: public SlideOutControllerTest,
public testing::WithParamInterface<SlideOutController::SlideMode> {
public:
SwipeControlTest() = default;
SwipeControlTest(const SwipeControlTest&) = delete;
SwipeControlTest& operator=(const SwipeControlTest&) = delete;
~SwipeControlTest() override = default;
void SetUp() override {
SlideOutControllerTest::SetUp();
slide_out_controller()->set_slide_mode(GetParam());
}
};
INSTANTIATE_TEST_SUITE_P(
All,
SwipeControlTest,
::testing::Values(SlideOutController::SlideMode::kFull,
SlideOutController::SlideMode::kPartial));
TEST_P(SwipeControlTest, SetSwipeControlWidth_SwipeLessThanControlWidth) {
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Place a finger on notification.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Move the finger horizontally by 29 px. (29 px is less than the swipe
// control width).
PostSequentialGestureEvent(ui::GestureEventDetails(
ui::ET_GESTURE_SCROLL_UPDATE, kSwipeControlWidth - 1, 0));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Release the finger.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
// The target has been moved back to the origin.
EXPECT_EQ(0.f,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred SlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SwipeControlWidth_SwipeMoreThanControlWidth) {
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Place a finger on notification.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Move the finger horizontally by 31 px. (31 px is more than the swipe
// control width).
PostSequentialGestureEvent(ui::GestureEventDetails(
ui::ET_GESTURE_SCROLL_UPDATE, kSwipeControlWidth + 1, 0));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Release the finger.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, delegate()->slide_started_count_);
// Slide is in progress.
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
// Swipe amount is the swipe control width.
EXPECT_EQ(kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred SlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SetSwipeControlWidth_SwipeOut) {
const bool swipe_out_supported =
slide_out_controller()->mode() == SlideOutController::SlideMode::kFull;
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Place a finger on notification.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Move the finger horizontally by 101 px. (101 px is more than the half of
// the target width).
PostSequentialGestureEvent(ui::GestureEventDetails(
ui::ET_GESTURE_SCROLL_UPDATE, kTargetWidth / 2 + 1, 0));
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
delegate()->reset();
// Release the finger.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
// ... and it is automatically slided out if |swipe_out_supported|.
EXPECT_EQ(0, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(delegate()->slide_changed_last_value_.value(),
!swipe_out_supported);
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(swipe_out_supported ? kTargetWidth : kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure a deferred SlideOut handler is called once.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(swipe_out_supported ? 1 : 0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SwipeControlWidth_SnapAndSwipeOut) {
const bool swipe_out_supported =
slide_out_controller()->mode() == SlideOutController::SlideMode::kFull;
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Snap to the swipe control.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
PostSequentialGestureEvent(ui::GestureEventDetails(
ui::ET_GESTURE_SCROLL_UPDATE, kSwipeControlWidth, 0));
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Swipe horizontally by 70 px.
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 70, 0));
PostSequentialGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
// ... and it is automatically slided out if if |swipe_out_supported|.
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(delegate()->slide_changed_last_value_.value(),
!swipe_out_supported);
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(swipe_out_supported ? kTargetWidth : kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure a deferred OnSlideOut handler is called.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(swipe_out_supported ? 1 : 0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SwipeControlWidth_SnapAndSnapToControl) {
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Snap to the swipe control.
PostSequentialSwipeEvent(kSwipeControlWidth + 10);
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Swipe horizontally by 40 px for the same direction.
PostSequentialSwipeEvent(40);
// Snap automatically back to the swipe control.
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred OnSlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SwipeControlWidth_SnapAndBackToOrigin) {
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Snap to the swipe control.
PostSequentialSwipeEvent(kSwipeControlWidth + 20);
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_TRUE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(kSwipeControlWidth,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Swipe to the reversed direction by -1 px.
PostSequentialSwipeEvent(-1);
// Snap automatically back to the origin.
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(0,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred OnSlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
TEST_P(SwipeControlTest, SwipeControlWidth_NotSnapAndBackToOrigin) {
// Set the width of swipe control.
slide_out_controller()->SetSwipeControlWidth(kSwipeControlWidth);
// Swipe partially but it's not enough to snap to the swipe control. So it is
// back to the origin
PostSequentialSwipeEvent(kSwipeControlWidth - 1);
EXPECT_EQ(1, delegate()->slide_started_count_);
EXPECT_TRUE(delegate()->IsOnSlideChangedCalled());
EXPECT_FALSE(delegate()->slide_changed_last_value_.value());
EXPECT_EQ(0, delegate()->slide_out_count_);
EXPECT_EQ(0,
delegate()->GetSlideOutLayer()->transform().To2dTranslation().x());
delegate()->reset();
// Ensure no deferred OnSlideOut handler.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(delegate()->IsOnSlideChangedCalled());
EXPECT_EQ(0, delegate()->slide_out_count_);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/slide_out_controller_unittest.cc | C++ | unknown | 18,862 |
// 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/animation/square_ink_drop_ripple.h"
#include <algorithm>
#include <utility>
#include "base/functional/bind.h"
#include "base/logging.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/transform_util.h"
#include "ui/gfx/geometry/vector3d_f.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/animation_sequence_block.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_painted_layer_delegates.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/view.h"
namespace views {
namespace {
// The minimum scale factor to use when scaling rectangle layers. Smaller values
// were causing visual anomalies.
constexpr float kMinimumRectScale = 0.0001f;
// The minimum scale factor to use when scaling circle layers. Smaller values
// were causing visual anomalies.
constexpr float kMinimumCircleScale = 0.001f;
// All the sub animations that are used to animate each of the InkDropStates.
// These are used to get time durations with
// GetAnimationDuration(InkDropSubAnimations). Note that in general a sub
// animation defines the duration for either a transformation animation or an
// opacity animation but there are some exceptions where an entire InkDropState
// animation consists of only 1 sub animation and it defines the duration for
// both the transformation and opacity animations.
enum InkDropSubAnimations {
// HIDDEN sub animations.
// The HIDDEN sub animation that is fading out to a hidden opacity.
HIDDEN_FADE_OUT,
// The HIDDEN sub animation that transforms the shape to a |small_size_|
// circle.
HIDDEN_TRANSFORM,
// ACTION_PENDING sub animations.
// The ACTION_PENDING sub animation that fades in to the visible opacity.
ACTION_PENDING_FADE_IN,
// The ACTION_PENDING sub animation that transforms the shape to a
// |large_size_| circle.
ACTION_PENDING_TRANSFORM,
// ACTION_TRIGGERED sub animations.
// The ACTION_TRIGGERED sub animation that is fading out to a hidden opacity.
ACTION_TRIGGERED_FADE_OUT,
// The ACTION_TRIGGERED sub animation that transforms the shape to a
// |large_size_|
// circle.
ACTION_TRIGGERED_TRANSFORM,
// ALTERNATE_ACTION_PENDING sub animations.
// The ALTERNATE_ACTION_PENDING animation has only one sub animation which
// animates
// to a |small_size_| rounded rectangle at visible opacity.
ALTERNATE_ACTION_PENDING,
// ALTERNATE_ACTION_TRIGGERED sub animations.
// The ALTERNATE_ACTION_TRIGGERED sub animation that is fading out to a hidden
// opacity.
ALTERNATE_ACTION_TRIGGERED_FADE_OUT,
// The ALTERNATE_ACTION_TRIGGERED sub animation that transforms the shape to a
// |large_size_|
// rounded rectangle.
ALTERNATE_ACTION_TRIGGERED_TRANSFORM,
// ACTIVATED sub animations.
// The ACTIVATED sub animation that transforms the shape to a |large_size_|
// circle. This is used when the ink drop is in a HIDDEN state prior to
// animating to the ACTIVATED state.
ACTIVATED_CIRCLE_TRANSFORM,
// The ACTIVATED sub animation that transforms the shape to a |small_size_|
// rounded rectangle.
ACTIVATED_RECT_TRANSFORM,
// DEACTIVATED sub animations.
// The DEACTIVATED sub animation that is fading out to a hidden opacity.
DEACTIVATED_FADE_OUT,
// The DEACTIVATED sub animation that transforms the shape to a |large_size_|
// rounded rectangle.
DEACTIVATED_TRANSFORM,
};
// The scale factor used to burst the ACTION_TRIGGERED bubble as it fades out.
constexpr float kQuickActionBurstScale = 1.3f;
// Returns the InkDropState sub animation duration for the given |state|.
base::TimeDelta GetAnimationDuration(InkDropHost* ink_drop_host,
InkDropSubAnimations state) {
if (!PlatformStyle::kUseRipples ||
!gfx::Animation::ShouldRenderRichAnimation() ||
(ink_drop_host &&
ink_drop_host->GetMode() == InkDropHost::InkDropMode::ON_NO_ANIMATE)) {
return base::TimeDelta();
}
// Duration constants for InkDropStateSubAnimations. See the
// InkDropStateSubAnimations enum documentation for more info.
constexpr base::TimeDelta kAnimationDuration[] = {
base::Milliseconds(150), // HIDDEN_FADE_OUT
base::Milliseconds(200), // HIDDEN_TRANSFORM
base::TimeDelta(), // ACTION_PENDING_FADE_IN
base::Milliseconds(160), // ACTION_PENDING_TRANSFORM
base::Milliseconds(150), // ACTION_TRIGGERED_FADE_OUT
base::Milliseconds(160), // ACTION_TRIGGERED_TRANSFORM
base::Milliseconds(200), // ALTERNATE_ACTION_PENDING
base::Milliseconds(150), // ALTERNAT..._TRIGGERED_FADE_OUT
base::Milliseconds(200), // ALTERNA..._TRIGGERED_TRANSFORM
base::Milliseconds(200), // ACTIVATED_CIRCLE_TRANSFORM
base::Milliseconds(160), // ACTIVATED_RECT_TRANSFORM
base::Milliseconds(150), // DEACTIVATED_FADE_OUT
base::Milliseconds(200), // DEACTIVATED_TRANSFORM
};
return kAnimationDuration[state];
}
} // namespace
SquareInkDropRipple::SquareInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& large_size,
int large_corner_radius,
const gfx::Size& small_size,
int small_corner_radius,
const gfx::Point& center_point,
SkColor color,
float visible_opacity)
: InkDropRipple(ink_drop_host),
visible_opacity_(visible_opacity),
large_size_(large_size),
large_corner_radius_(large_corner_radius),
small_size_(small_size),
small_corner_radius_(small_corner_radius),
center_point_(center_point),
circle_layer_delegate_(new CircleLayerDelegate(
color,
std::min(large_size_.width(), large_size_.height()) / 2)),
rect_layer_delegate_(
new RectangleLayerDelegate(color, gfx::SizeF(large_size_))),
root_layer_(ui::LAYER_NOT_DRAWN) {
root_layer_.SetName("SquareInkDropRipple:ROOT_LAYER");
for (int i = 0; i < PAINTED_SHAPE_COUNT; ++i)
AddPaintLayer(static_cast<PaintedShape>(i));
root_layer_.SetMasksToBounds(false);
root_layer_.SetBounds(gfx::Rect(large_size_));
root_callback_subscription_ =
root_layer_.GetAnimator()->AddSequenceScheduledCallback(
base::BindRepeating(
&SquareInkDropRipple::OnLayerAnimationSequenceScheduled,
base::Unretained(this)));
SetStateToHidden();
}
SquareInkDropRipple::~SquareInkDropRipple() {
// Explicitly aborting all the animations ensures all callbacks are invoked
// while this instance still exists.
AbortAllAnimations();
}
void SquareInkDropRipple::SnapToActivated() {
InkDropRipple::SnapToActivated();
SetOpacity(visible_opacity_);
InkDropTransforms transforms;
GetActivatedTargetTransforms(&transforms);
SetTransforms(transforms);
}
ui::Layer* SquareInkDropRipple::GetRootLayer() {
return &root_layer_;
}
float SquareInkDropRipple::GetCurrentOpacity() const {
return root_layer_.opacity();
}
std::string SquareInkDropRipple::ToLayerName(PaintedShape painted_shape) {
switch (painted_shape) {
case TOP_LEFT_CIRCLE:
return "TOP_LEFT_CIRCLE";
case TOP_RIGHT_CIRCLE:
return "TOP_RIGHT_CIRCLE";
case BOTTOM_RIGHT_CIRCLE:
return "BOTTOM_RIGHT_CIRCLE";
case BOTTOM_LEFT_CIRCLE:
return "BOTTOM_LEFT_CIRCLE";
case HORIZONTAL_RECT:
return "HORIZONTAL_RECT";
case VERTICAL_RECT:
return "VERTICAL_RECT";
case PAINTED_SHAPE_COUNT:
NOTREACHED_NORETURN()
<< "The PAINTED_SHAPE_COUNT value should never be used.";
}
return "UNKNOWN";
}
void SquareInkDropRipple::AnimateStateChange(InkDropState old_ink_drop_state,
InkDropState new_ink_drop_state) {
InkDropTransforms transforms;
AnimationBuilder builder;
InkDropHost* host = GetInkDropHost();
builder
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once();
auto animate_to_transforms =
[this](AnimationSequenceBlock& sequence,
const InkDropTransforms& transforms,
gfx::Tween::Type tween) -> AnimationSequenceBlock& {
for (int i = 0; i < PAINTED_SHAPE_COUNT; ++i)
sequence.SetTransform(painted_layers_[i].get(), transforms[i], tween);
return sequence;
};
auto pending_animation =
[this, &animate_to_transforms, host](
AnimationSequenceBlock& sequence,
const InkDropTransforms& transforms) -> AnimationSequenceBlock& {
auto& new_sequence =
sequence.SetDuration(GetAnimationDuration(host, ACTION_PENDING_FADE_IN))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN)
.Then()
.SetDuration(GetAnimationDuration(host, ACTION_PENDING_TRANSFORM))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN);
animate_to_transforms(new_sequence, transforms, gfx::Tween::EASE_IN_OUT);
return new_sequence;
};
switch (new_ink_drop_state) {
case InkDropState::HIDDEN:
if (!IsVisible()) {
SetStateToHidden();
break;
} else {
CalculateCircleTransforms(small_size_, &transforms);
auto& sequence =
builder.GetCurrentSequence()
.SetDuration(GetAnimationDuration(host, HIDDEN_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity,
gfx::Tween::EASE_IN_OUT)
.At(base::TimeDelta())
.SetDuration(GetAnimationDuration(host, HIDDEN_TRANSFORM));
animate_to_transforms(sequence, transforms, gfx::Tween::EASE_IN_OUT);
}
break;
case InkDropState::ACTION_PENDING: {
if (old_ink_drop_state == new_ink_drop_state)
return;
DLOG_IF(WARNING, InkDropState::HIDDEN != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
CalculateCircleTransforms(large_size_, &transforms);
pending_animation(builder.GetCurrentSequence(), transforms);
break;
}
case InkDropState::ACTION_TRIGGERED: {
DLOG_IF(WARNING, old_ink_drop_state != InkDropState::HIDDEN &&
old_ink_drop_state != InkDropState::ACTION_PENDING)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
gfx::Size s = ScaleToRoundedSize(large_size_, kQuickActionBurstScale);
CalculateCircleTransforms(s, &transforms);
if (old_ink_drop_state == InkDropState::HIDDEN) {
pending_animation(builder.GetCurrentSequence(), transforms).Then();
} else {
builder.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
}
builder.GetCurrentSequence()
.SetDuration(GetAnimationDuration(host, ACTION_TRIGGERED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT)
.Offset(base::TimeDelta())
.SetDuration(GetAnimationDuration(host, ACTION_TRIGGERED_TRANSFORM));
animate_to_transforms(builder.GetCurrentSequence(), transforms,
gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::ALTERNATE_ACTION_PENDING: {
DLOG_IF(WARNING, InkDropState::ACTION_PENDING != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
CalculateRectTransforms(small_size_, small_corner_radius_, &transforms);
animate_to_transforms(
builder.GetCurrentSequence()
.SetDuration(GetAnimationDuration(host, ALTERNATE_ACTION_PENDING))
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN),
transforms, gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::ALTERNATE_ACTION_TRIGGERED: {
DLOG_IF(WARNING,
InkDropState::ALTERNATE_ACTION_PENDING != old_ink_drop_state)
<< "Invalid InkDropState transition. old_ink_drop_state="
<< ToString(old_ink_drop_state)
<< " new_ink_drop_state=" << ToString(new_ink_drop_state);
base::TimeDelta visible_duration =
GetAnimationDuration(host, ALTERNATE_ACTION_TRIGGERED_TRANSFORM) -
GetAnimationDuration(host, ALTERNATE_ACTION_TRIGGERED_FADE_OUT);
CalculateRectTransforms(large_size_, large_corner_radius_, &transforms);
builder.GetCurrentSequence()
.SetDuration(visible_duration)
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT)
.Then()
.SetDuration(
GetAnimationDuration(host, ALTERNATE_ACTION_TRIGGERED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT)
.At(base::TimeDelta())
.SetDuration(
GetAnimationDuration(host, ALTERNATE_ACTION_TRIGGERED_TRANSFORM));
animate_to_transforms(builder.GetCurrentSequence(), transforms,
gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::ACTIVATED: {
// Animate the opacity so that it cancels any opacity animations already
// in progress.
builder.GetCurrentSequence()
.SetDuration(base::TimeDelta())
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT)
.Then();
if (old_ink_drop_state == InkDropState::HIDDEN) {
CalculateCircleTransforms(large_size_, &transforms);
animate_to_transforms(
builder.GetCurrentSequence().SetDuration(
GetAnimationDuration(host, ACTIVATED_CIRCLE_TRANSFORM)),
transforms, gfx::Tween::EASE_IN_OUT)
.Then();
} else if (old_ink_drop_state == InkDropState::ACTION_PENDING) {
builder.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
}
GetActivatedTargetTransforms(&transforms);
animate_to_transforms(
builder.GetCurrentSequence().SetDuration(
GetAnimationDuration(host, ACTIVATED_RECT_TRANSFORM)),
transforms, gfx::Tween::EASE_IN_OUT);
break;
}
case InkDropState::DEACTIVATED: {
base::TimeDelta visible_duration =
GetAnimationDuration(host, DEACTIVATED_TRANSFORM) -
GetAnimationDuration(host, DEACTIVATED_FADE_OUT);
GetDeactivatedTargetTransforms(&transforms);
builder.GetCurrentSequence()
.SetDuration(visible_duration)
.SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT)
.Then()
.SetDuration(GetAnimationDuration(host, DEACTIVATED_FADE_OUT))
.SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT)
.At(base::TimeDelta());
animate_to_transforms(
builder.GetCurrentSequence().SetDuration(
GetAnimationDuration(host, DEACTIVATED_TRANSFORM)),
transforms, gfx::Tween::EASE_IN_OUT);
break;
}
}
}
void SquareInkDropRipple::SetStateToHidden() {
InkDropTransforms transforms;
// Use non-zero size to avoid visual anomalies.
CalculateCircleTransforms(gfx::Size(1, 1), &transforms);
SetTransforms(transforms);
root_layer_.SetOpacity(InkDropRipple::kHiddenOpacity);
root_layer_.SetVisible(false);
}
void SquareInkDropRipple::AbortAllAnimations() {
root_layer_.GetAnimator()->AbortAllAnimations();
for (auto& painted_layer : painted_layers_)
painted_layer->GetAnimator()->AbortAllAnimations();
}
void SquareInkDropRipple::SetTransforms(const InkDropTransforms transforms) {
for (int i = 0; i < PAINTED_SHAPE_COUNT; ++i)
painted_layers_[i]->SetTransform(transforms[i]);
}
void SquareInkDropRipple::SetOpacity(float opacity) {
root_layer_.SetOpacity(opacity);
}
void SquareInkDropRipple::CalculateCircleTransforms(
const gfx::Size& size,
InkDropTransforms* transforms_out) const {
CalculateRectTransforms(size, std::min(size.width(), size.height()) / 2.0f,
transforms_out);
}
void SquareInkDropRipple::CalculateRectTransforms(
const gfx::Size& desired_size,
float corner_radius,
InkDropTransforms* transforms_out) const {
DCHECK_GE(desired_size.width() / 2.0f, corner_radius)
<< "The circle's diameter should not be greater than the total width.";
DCHECK_GE(desired_size.height() / 2.0f, corner_radius)
<< "The circle's diameter should not be greater than the total height.";
gfx::SizeF size(desired_size);
// This function can be called before the layer's been added to a view,
// either at construction time or in tests.
if (root_layer_.GetCompositor()) {
// Modify |desired_size| so that the ripple aligns to pixel bounds.
const float dsf = root_layer_.GetCompositor()->device_scale_factor();
gfx::RectF ripple_bounds((gfx::PointF(center_point_)), gfx::SizeF());
ripple_bounds.Inset(-gfx::InsetsF::VH(desired_size.height() / 2.0f,
desired_size.width() / 2.0f));
ripple_bounds.Scale(dsf);
ripple_bounds = gfx::RectF(gfx::ToEnclosingRect(ripple_bounds));
ripple_bounds.InvScale(dsf);
size = ripple_bounds.size();
}
// The shapes are drawn such that their center points are not at the origin.
// Thus we use the CalculateCircleTransform() and CalculateRectTransform()
// methods to calculate the complex Transforms.
const float circle_scale = std::max(
kMinimumCircleScale,
corner_radius / static_cast<float>(circle_layer_delegate_->radius()));
const float circle_target_x_offset = size.width() / 2.0f - corner_radius;
const float circle_target_y_offset = size.height() / 2.0f - corner_radius;
(*transforms_out)[TOP_LEFT_CIRCLE] = CalculateCircleTransform(
circle_scale, -circle_target_x_offset, -circle_target_y_offset);
(*transforms_out)[TOP_RIGHT_CIRCLE] = CalculateCircleTransform(
circle_scale, circle_target_x_offset, -circle_target_y_offset);
(*transforms_out)[BOTTOM_RIGHT_CIRCLE] = CalculateCircleTransform(
circle_scale, circle_target_x_offset, circle_target_y_offset);
(*transforms_out)[BOTTOM_LEFT_CIRCLE] = CalculateCircleTransform(
circle_scale, -circle_target_x_offset, circle_target_y_offset);
const float rect_delegate_width = rect_layer_delegate_->size().width();
const float rect_delegate_height = rect_layer_delegate_->size().height();
(*transforms_out)[HORIZONTAL_RECT] = CalculateRectTransform(
std::max(kMinimumRectScale, size.width() / rect_delegate_width),
std::max(kMinimumRectScale,
(size.height() - 2.0f * corner_radius) / rect_delegate_height));
(*transforms_out)[VERTICAL_RECT] = CalculateRectTransform(
std::max(kMinimumRectScale,
(size.width() - 2.0f * corner_radius) / rect_delegate_width),
std::max(kMinimumRectScale, size.height() / rect_delegate_height));
}
gfx::Transform SquareInkDropRipple::CalculateCircleTransform(
float scale,
float target_center_x,
float target_center_y) const {
gfx::Transform transform;
// Offset for the center point of the ripple.
transform.Translate(center_point_.x(), center_point_.y());
// Move circle to target.
transform.Translate(target_center_x, target_center_y);
transform.Scale(scale, scale);
// Align center point of the painted circle.
const gfx::Vector2dF circle_center_offset =
circle_layer_delegate_->GetCenteringOffset();
transform.Translate(-circle_center_offset.x(), -circle_center_offset.y());
return transform;
}
gfx::Transform SquareInkDropRipple::CalculateRectTransform(
float x_scale,
float y_scale) const {
gfx::Transform transform;
transform.Translate(center_point_.x(), center_point_.y());
transform.Scale(x_scale, y_scale);
const gfx::Vector2dF rect_center_offset =
rect_layer_delegate_->GetCenteringOffset();
transform.Translate(-rect_center_offset.x(), -rect_center_offset.y());
return transform;
}
void SquareInkDropRipple::GetCurrentTransforms(
InkDropTransforms* transforms_out) const {
for (int i = 0; i < PAINTED_SHAPE_COUNT; ++i)
(*transforms_out)[i] = painted_layers_[i]->transform();
}
void SquareInkDropRipple::GetActivatedTargetTransforms(
InkDropTransforms* transforms_out) const {
switch (activated_shape_) {
case ActivatedShape::kCircle:
CalculateCircleTransforms(small_size_, transforms_out);
break;
case ActivatedShape::kRoundedRect:
CalculateRectTransforms(small_size_, small_corner_radius_,
transforms_out);
break;
}
}
void SquareInkDropRipple::GetDeactivatedTargetTransforms(
InkDropTransforms* transforms_out) const {
switch (activated_shape_) {
case ActivatedShape::kCircle:
CalculateCircleTransforms(large_size_, transforms_out);
break;
case ActivatedShape::kRoundedRect:
CalculateRectTransforms(large_size_, small_corner_radius_,
transforms_out);
break;
}
}
void SquareInkDropRipple::AddPaintLayer(PaintedShape painted_shape) {
ui::LayerDelegate* delegate = nullptr;
switch (painted_shape) {
case TOP_LEFT_CIRCLE:
case TOP_RIGHT_CIRCLE:
case BOTTOM_RIGHT_CIRCLE:
case BOTTOM_LEFT_CIRCLE:
delegate = circle_layer_delegate_.get();
break;
case HORIZONTAL_RECT:
case VERTICAL_RECT:
delegate = rect_layer_delegate_.get();
break;
case PAINTED_SHAPE_COUNT:
NOTREACHED_NORETURN()
<< "PAINTED_SHAPE_COUNT is not an actual shape type.";
}
ui::Layer* layer = new ui::Layer();
root_layer_.Add(layer);
layer->SetBounds(gfx::Rect(large_size_));
layer->SetFillsBoundsOpaquely(false);
layer->set_delegate(delegate);
layer->SetVisible(true);
layer->SetOpacity(1.0);
layer->SetMasksToBounds(false);
layer->SetName("PAINTED_SHAPE_COUNT:" + ToLayerName(painted_shape));
callback_subscriptions_[painted_shape] =
layer->GetAnimator()->AddSequenceScheduledCallback(base::BindRepeating(
&SquareInkDropRipple::OnLayerAnimationSequenceScheduled,
base::Unretained(this)));
painted_layers_[painted_shape].reset(layer);
}
void SquareInkDropRipple::OnLayerAnimationSequenceScheduled(
ui::LayerAnimationSequence* sequence) {
sequence->AddObserver(GetLayerAnimationObserver());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/square_ink_drop_ripple.cc | C++ | unknown | 23,165 |
// 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_ANIMATION_SQUARE_INK_DROP_RIPPLE_H_
#define UI_VIEWS_ANIMATION_SQUARE_INK_DROP_RIPPLE_H_
#include <memory>
#include <string>
#include "base/callback_list.h"
#include "base/time/time.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/gfx/animation/tween.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
} // namespace ui
namespace views {
class CircleLayerDelegate;
class InkDropHost;
class RectangleLayerDelegate;
namespace test {
class SquareInkDropRippleTestApi;
} // namespace test
// An ink drop ripple that smoothly animates between a circle and a rounded
// rectangle of different sizes for each of the different InkDropStates. The
// final frame for each InkDropState will be bounded by either a |large_size_|
// rectangle or a |small_size_| rectangle.
//
// The valid InkDropState transitions are defined below:
//
// {All InkDropStates} => HIDDEN
// HIDDEN => ACTION_PENDING
// HIDDEN, ACTION_PENDING => ACTION_TRIGGERED
// ACTION_PENDING => ALTERNATE_ACTION_PENDING
// ALTERNATE_ACTION_PENDING => ALTERNATE_ACTION_TRIGGERED
// {All InkDropStates} => ACTIVATED
// {All InkDropStates} => DEACTIVATED
//
class VIEWS_EXPORT SquareInkDropRipple : public InkDropRipple {
public:
// The shape to use for the ACTIVATED/DEACTIVATED states.
enum class ActivatedShape { kCircle, kRoundedRect };
SquareInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& large_size,
int large_corner_radius,
const gfx::Size& small_size,
int small_corner_radius,
const gfx::Point& center_point,
SkColor color,
float visible_opacity);
SquareInkDropRipple(const SquareInkDropRipple&) = delete;
SquareInkDropRipple& operator=(const SquareInkDropRipple&) = delete;
~SquareInkDropRipple() override;
void set_activated_shape(ActivatedShape shape) { activated_shape_ = shape; }
// InkDropRipple:
void SnapToActivated() override;
ui::Layer* GetRootLayer() override;
private:
friend class test::SquareInkDropRippleTestApi;
// Enumeration of the different shapes that compose the ink drop.
enum PaintedShape {
TOP_LEFT_CIRCLE = 0,
TOP_RIGHT_CIRCLE,
BOTTOM_RIGHT_CIRCLE,
BOTTOM_LEFT_CIRCLE,
HORIZONTAL_RECT,
VERTICAL_RECT,
// The total number of shapes, not an actual shape.
PAINTED_SHAPE_COUNT
};
// Returns a human readable string for the |painted_shape| value.
static std::string ToLayerName(PaintedShape painted_shape);
// Type that contains a gfx::Tansform for each of the layers required by the
// ink drop.
using InkDropTransforms = gfx::Transform[PAINTED_SHAPE_COUNT];
float GetCurrentOpacity() const;
// InkDropRipple:
void AnimateStateChange(InkDropState old_ink_drop_state,
InkDropState new_ink_drop_state) override;
void SetStateToHidden() override;
void AbortAllAnimations() override;
// Sets the |transforms| on all of the shape layers. Note that this does not
// perform any animation.
void SetTransforms(const InkDropTransforms transforms);
// Sets the opacity of the ink drop. Note that this does not perform any
// animation.
void SetOpacity(float opacity);
// Updates all of the Transforms in |transforms_out| for a circle of the given
// |size|.
void CalculateCircleTransforms(const gfx::Size& desired_size,
InkDropTransforms* transforms_out) const;
// Updates all of the Transforms in |transforms_out| for a rounded rectangle
// of the given |desired_size| and |corner_radius|. The effective size may
// differ from |desired_size| at certain scale factors to make sure the ripple
// is pixel-aligned.
void CalculateRectTransforms(const gfx::Size& desired_size,
float corner_radius,
InkDropTransforms* transforms_out) const;
// Calculates a Transform for a circle layer.
gfx::Transform CalculateCircleTransform(float scale,
float target_center_x,
float target_center_y) const;
// Calculates a Transform for a rectangle layer.
gfx::Transform CalculateRectTransform(float x_scale, float y_scale) const;
// Updates all of the Transforms in |transforms_out| to the current Transforms
// of the painted shape Layers.
void GetCurrentTransforms(InkDropTransforms* transforms_out) const;
// Updates all of the Transforms in |transforms_out| with the target
// Transforms for the ACTIVATED animation.
void GetActivatedTargetTransforms(InkDropTransforms* transforms_out) const;
// Updates all of the Transforms in |transforms_out| with the target
// Transforms for the DEACTIVATED animation.
void GetDeactivatedTargetTransforms(InkDropTransforms* transforms_out) const;
// Adds and configures a new |painted_shape| layer to |painted_layers_|.
void AddPaintLayer(PaintedShape painted_shape);
// Called from LayerAnimator when a new LayerAnimationSequence is scheduled
// which allows for assigning the observer to the sequence.
void OnLayerAnimationSequenceScheduled(ui::LayerAnimationSequence* sequence);
// The shape used for the ACTIVATED/DEACTIVATED states.
ActivatedShape activated_shape_ = ActivatedShape::kRoundedRect;
// Ink drop opacity when it is visible.
float visible_opacity_;
// Maximum size that an ink drop will be drawn to for any InkDropState whose
// final frame should be large.
const gfx::Size large_size_;
// Corner radius used to draw the rounded rectangles corner for any
// InkDropState whose final frame should be large.
const int large_corner_radius_;
// Maximum size that an ink drop will be drawn to for any InkDropState whose
// final frame should be small.
const gfx::Size small_size_;
// Corner radius used to draw the rounded rectangles corner for any
// InkDropState whose final frame should be small.
const int small_corner_radius_;
// The center point of the ripple, relative to the root layer's origin.
gfx::Point center_point_;
// ui::LayerDelegate to paint circles for all the circle layers.
std::unique_ptr<CircleLayerDelegate> circle_layer_delegate_;
// ui::LayerDelegate to paint rectangles for all the rectangle layers.
std::unique_ptr<RectangleLayerDelegate> rect_layer_delegate_;
// The root layer that parents the animating layers. The root layer is used to
// manipulate opacity and location, and its children are used to manipulate
// the different painted shapes that compose the ink drop.
ui::Layer root_layer_;
// Sequence scheduled callback subscription for the root layer.
base::CallbackListSubscription root_callback_subscription_;
// ui::Layers for all of the painted shape layers that compose the ink drop.
std::unique_ptr<ui::Layer> painted_layers_[PAINTED_SHAPE_COUNT];
// Sequence scheduled callback subscriptions for the painted layers.
base::CallbackListSubscription callback_subscriptions_[PAINTED_SHAPE_COUNT];
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_SQUARE_INK_DROP_RIPPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/square_ink_drop_ripple.h | C++ | unknown | 7,718 |
// 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/animation/square_ink_drop_ripple.h"
#include <memory>
#include <vector>
#include "base/numerics/safe_conversions.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/views/animation/ink_drop_ripple_observer.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/animation/test/square_ink_drop_ripple_test_api.h"
#include "ui/views/animation/test/test_ink_drop_ripple_observer.h"
#include "ui/views/test/widget_test.h"
namespace views::test {
namespace {
using PaintedShape = views::test::SquareInkDropRippleTestApi::PaintedShape;
class SquareInkDropRippleCalculateTransformsTest : public WidgetTest {
public:
SquareInkDropRippleCalculateTransformsTest();
SquareInkDropRippleCalculateTransformsTest(
const SquareInkDropRippleCalculateTransformsTest&) = delete;
SquareInkDropRippleCalculateTransformsTest& operator=(
const SquareInkDropRippleCalculateTransformsTest&) = delete;
~SquareInkDropRippleCalculateTransformsTest() override;
protected:
// Half the width/height of the drawn ink drop.
static constexpr int kHalfDrawnSize = 5;
// The full width/height of the drawn ink drop.
static constexpr int kDrawnSize = 2 * kHalfDrawnSize;
// The radius of the rounded rectangle corners.
static constexpr int kTransformedRadius = 10;
// Half the width/height of the transformed ink drop.
static const int kHalfTransformedSize = 100;
// The full width/height of the transformed ink drop.
static const int kTransformedSize = 2 * kHalfTransformedSize;
// Constant points in the drawn space that will be transformed.
static constexpr gfx::Point kDrawnCenterPoint =
gfx::Point(kHalfDrawnSize, kHalfDrawnSize);
static constexpr gfx::Point kDrawnMidLeftPoint =
gfx::Point(0, kHalfDrawnSize);
static constexpr gfx::Point kDrawnMidRightPoint =
gfx::Point(kDrawnSize, kHalfDrawnSize);
static constexpr gfx::Point kDrawnTopMidPoint = gfx::Point(kHalfDrawnSize, 0);
static constexpr gfx::Point kDrawnBottomMidPoint =
gfx::Point(kHalfDrawnSize, kDrawnSize);
// The test target.
SquareInkDropRipple ink_drop_ripple_{
nullptr,
gfx::Size(kDrawnSize, kDrawnSize),
2,
gfx::Size(kHalfDrawnSize, kHalfDrawnSize),
1,
gfx::Point(),
SK_ColorBLACK,
0.175f};
// Provides internal access to the test target.
SquareInkDropRippleTestApi test_api_{&ink_drop_ripple_};
// The gfx::Transforms collection that is populated via the
// Calculate*Transforms() calls.
SquareInkDropRippleTestApi::InkDropTransforms transforms_;
};
SquareInkDropRippleCalculateTransformsTest::
SquareInkDropRippleCalculateTransformsTest() = default;
SquareInkDropRippleCalculateTransformsTest::
~SquareInkDropRippleCalculateTransformsTest() = default;
constexpr gfx::Point
SquareInkDropRippleCalculateTransformsTest::kDrawnCenterPoint;
constexpr gfx::Point
SquareInkDropRippleCalculateTransformsTest::kDrawnMidLeftPoint;
constexpr gfx::Point
SquareInkDropRippleCalculateTransformsTest::kDrawnMidRightPoint;
constexpr gfx::Point
SquareInkDropRippleCalculateTransformsTest::kDrawnTopMidPoint;
constexpr gfx::Point
SquareInkDropRippleCalculateTransformsTest::kDrawnBottomMidPoint;
} // namespace
TEST_F(SquareInkDropRippleCalculateTransformsTest,
TransformedPointsUsingTransformsFromCalculateCircleTransforms) {
test_api_.CalculateCircleTransforms(
gfx::Size(kTransformedSize, kTransformedSize), &transforms_);
constexpr struct {
PaintedShape shape;
gfx::Point center_point;
gfx::Point mid_left_point;
gfx::Point mid_right_point;
gfx::Point top_mid_point;
gfx::Point bottom_mid_point;
} test_cases[] = {
{PaintedShape::TOP_LEFT_CIRCLE, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0),
gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)},
{PaintedShape::TOP_RIGHT_CIRCLE, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0),
gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)},
{PaintedShape::BOTTOM_RIGHT_CIRCLE, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0),
gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)},
{PaintedShape::BOTTOM_LEFT_CIRCLE, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0),
gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)},
{PaintedShape::HORIZONTAL_RECT, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0), gfx::Point(0, 0), gfx::Point(0, 0)},
{PaintedShape::VERTICAL_RECT, gfx::Point(0, 0), gfx::Point(0, 0),
gfx::Point(0, 0), gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)}};
for (const auto& test_case : test_cases) {
PaintedShape shape = test_case.shape;
SCOPED_TRACE(testing::Message() << " shape=" << shape);
gfx::Transform transform = transforms_[shape];
EXPECT_EQ(test_case.center_point, transform.MapPoint(kDrawnCenterPoint));
EXPECT_EQ(test_case.mid_left_point, transform.MapPoint(kDrawnMidLeftPoint));
EXPECT_EQ(test_case.mid_right_point,
transform.MapPoint(kDrawnMidRightPoint));
EXPECT_EQ(test_case.top_mid_point, transform.MapPoint(kDrawnTopMidPoint));
EXPECT_EQ(test_case.bottom_mid_point,
transform.MapPoint(kDrawnBottomMidPoint));
}
}
TEST_F(SquareInkDropRippleCalculateTransformsTest,
TransformedPointsUsingTransformsFromCalculateRectTransforms) {
test_api_.CalculateRectTransforms(
gfx::Size(kTransformedSize, kTransformedSize), kTransformedRadius,
&transforms_);
constexpr int x_offset = kHalfTransformedSize - kTransformedRadius;
constexpr int y_offset = kHalfTransformedSize - kTransformedRadius;
constexpr struct {
PaintedShape shape;
gfx::Point center_point;
gfx::Point mid_left_point;
gfx::Point mid_right_point;
gfx::Point top_mid_point;
gfx::Point bottom_mid_point;
} test_cases[] = {
{PaintedShape::TOP_LEFT_CIRCLE, gfx::Point(-x_offset, -y_offset),
gfx::Point(-kHalfTransformedSize, -y_offset),
gfx::Point(-x_offset + kTransformedRadius, -y_offset),
gfx::Point(-x_offset, -kHalfTransformedSize),
gfx::Point(-x_offset, -y_offset + kTransformedRadius)},
{PaintedShape::TOP_RIGHT_CIRCLE, gfx::Point(x_offset, -y_offset),
gfx::Point(x_offset - kTransformedRadius, -y_offset),
gfx::Point(kHalfTransformedSize, -y_offset),
gfx::Point(x_offset, -kHalfTransformedSize),
gfx::Point(x_offset, -y_offset + kTransformedRadius)},
{PaintedShape::BOTTOM_RIGHT_CIRCLE, gfx::Point(x_offset, y_offset),
gfx::Point(x_offset - kTransformedRadius, y_offset),
gfx::Point(kHalfTransformedSize, y_offset),
gfx::Point(x_offset, y_offset - kTransformedRadius),
gfx::Point(x_offset, kHalfTransformedSize)},
{PaintedShape::BOTTOM_LEFT_CIRCLE, gfx::Point(-x_offset, y_offset),
gfx::Point(-kHalfTransformedSize, y_offset),
gfx::Point(-x_offset + kTransformedRadius, y_offset),
gfx::Point(-x_offset, y_offset - kTransformedRadius),
gfx::Point(-x_offset, kHalfTransformedSize)},
{PaintedShape::HORIZONTAL_RECT, gfx::Point(0, 0),
gfx::Point(-kHalfTransformedSize, 0),
gfx::Point(kHalfTransformedSize, 0), gfx::Point(0, -y_offset),
gfx::Point(0, y_offset)},
{PaintedShape::VERTICAL_RECT, gfx::Point(0, 0), gfx::Point(-x_offset, 0),
gfx::Point(x_offset, 0), gfx::Point(0, -kHalfTransformedSize),
gfx::Point(0, kHalfTransformedSize)}};
for (const auto& test_case : test_cases) {
PaintedShape shape = test_case.shape;
SCOPED_TRACE(testing::Message() << " shape=" << shape);
gfx::Transform transform = transforms_[shape];
EXPECT_EQ(test_case.center_point, transform.MapPoint(kDrawnCenterPoint));
EXPECT_EQ(test_case.mid_left_point, transform.MapPoint(kDrawnMidLeftPoint));
EXPECT_EQ(test_case.mid_right_point,
transform.MapPoint(kDrawnMidRightPoint));
EXPECT_EQ(test_case.top_mid_point, transform.MapPoint(kDrawnTopMidPoint));
EXPECT_EQ(test_case.bottom_mid_point,
transform.MapPoint(kDrawnBottomMidPoint));
}
}
TEST_F(SquareInkDropRippleCalculateTransformsTest, RippleIsPixelAligned) {
// Create a ripple that would not naturally be pixel aligned at a fractional
// scale factor.
constexpr gfx::Point kCenter(14, 14);
constexpr gfx::Rect kDrawnRectBounds(0, 0, 10, 10);
SquareInkDropRipple ink_drop_ripple(nullptr, kDrawnRectBounds.size(), 2,
gfx::Size(1, 1), // unimportant
1, kCenter, SK_ColorBLACK, 0.175f);
SquareInkDropRippleTestApi test_api(&ink_drop_ripple);
// Add to a widget so we can control the DSF.
auto* widget = CreateTopLevelPlatformWidget();
widget->SetBounds(gfx::Rect(0, 0, 100, 100));
auto* host_view = new View();
host_view->SetPaintToLayer();
widget->GetContentsView()->AddChildView(host_view);
host_view->layer()->Add(ink_drop_ripple.GetRootLayer());
// Test a variety of scale factors and target transform sizes.
const std::vector<float> dsfs({1.0f, 1.25f, 1.5f, 2.0f, 3.0f});
const std::vector<int> target_sizes({5, 7, 11, 13, 31});
for (float dsf : dsfs) {
for (int target_size : target_sizes) {
SCOPED_TRACE(testing::Message()
<< "target_size=" << target_size << " dsf=" << dsf);
host_view->layer()->GetCompositor()->SetScaleAndSize(
dsf, gfx::Size(100, 100), viz::LocalSurfaceId());
SquareInkDropRippleTestApi::InkDropTransforms transforms;
test_api.CalculateRectTransforms(gfx::Size(target_size, target_size), 0,
&transforms);
// Checks that a rectangle is integer-aligned modulo floating point error.
auto verify_bounds = [](const gfx::RectF& rect) {
float float_min_x = rect.x();
float float_min_y = rect.y();
float float_max_x = rect.right();
float float_max_y = rect.bottom();
int min_x = base::ClampRound(float_min_x);
int min_y = base::ClampRound(float_min_y);
int max_x = base::ClampRound(float_max_x);
int max_y = base::ClampRound(float_max_y);
EXPECT_LT(std::abs(min_x - float_min_x), 0.01f);
EXPECT_LT(std::abs(min_y - float_min_y), 0.01f);
EXPECT_LT(std::abs(max_x - float_max_x), 0.01f);
EXPECT_LT(std::abs(max_y - float_max_y), 0.01f);
};
// When you feed in the bounds of the rectangle layer delegate, no matter
// what the target size was you should get an integer aligned bounding
// box.
gfx::Transform transform = transforms[PaintedShape::HORIZONTAL_RECT];
gfx::RectF horizontal_rect =
transform.MapRect(gfx::RectF(kDrawnRectBounds));
horizontal_rect.Scale(dsf);
verify_bounds(horizontal_rect);
transform = transforms[PaintedShape::VERTICAL_RECT];
gfx::RectF vertical_rect =
transform.MapRect(gfx::RectF(kDrawnRectBounds));
vertical_rect.Scale(dsf);
verify_bounds(vertical_rect);
}
}
widget->CloseNow();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/square_ink_drop_ripple_unittest.cc | C++ | unknown | 11,837 |
// 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/animation/test/flood_fill_ink_drop_ripple_test_api.h"
#include <vector>
#include "base/time/time.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/test/layer_animator_test_controller.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/views/animation/ink_drop_ripple.h"
namespace views::test {
FloodFillInkDropRippleTestApi::FloodFillInkDropRippleTestApi(
FloodFillInkDropRipple* ink_drop_ripple)
: InkDropRippleTestApi(ink_drop_ripple) {}
FloodFillInkDropRippleTestApi::~FloodFillInkDropRippleTestApi() = default;
gfx::Point3F FloodFillInkDropRippleTestApi::MapPoint(
float radius,
const gfx::Point3F& point) {
return ink_drop_ripple()->CalculateTransform(radius).MapPoint(point);
}
gfx::Point FloodFillInkDropRippleTestApi::GetDrawnCenterPoint() const {
return ToRoundedPoint(PointAtOffsetFromOrigin(
ink_drop_ripple()->circle_layer_delegate_.GetCenteringOffset()));
}
float FloodFillInkDropRippleTestApi::MaxDistanceToCorners(
const gfx::Point& point) const {
return ink_drop_ripple()->MaxDistanceToCorners(point);
}
gfx::Transform FloodFillInkDropRippleTestApi::GetPaintedLayerTransform() const {
return ink_drop_ripple()->painted_layer_.transform();
}
float FloodFillInkDropRippleTestApi::GetCurrentOpacity() const {
return ink_drop_ripple()->root_layer_.opacity();
}
std::vector<ui::LayerAnimator*>
FloodFillInkDropRippleTestApi::GetLayerAnimators() {
std::vector<ui::LayerAnimator*> animators =
InkDropRippleTestApi::GetLayerAnimators();
animators.push_back(ink_drop_ripple()->GetRootLayer()->GetAnimator());
animators.push_back(ink_drop_ripple()->painted_layer_.GetAnimator());
return animators;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/flood_fill_ink_drop_ripple_test_api.cc | C++ | unknown | 1,922 |
// 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_ANIMATION_TEST_FLOOD_FILL_INK_DROP_RIPPLE_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_FLOOD_FILL_INK_DROP_RIPPLE_TEST_API_H_
#include <vector>
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_ripple_test_api.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views::test {
// Test API to provide internal access to a FloodFillInkDropRipple.
class FloodFillInkDropRippleTestApi : public InkDropRippleTestApi {
public:
explicit FloodFillInkDropRippleTestApi(
FloodFillInkDropRipple* ink_drop_ripple);
FloodFillInkDropRippleTestApi(const FloodFillInkDropRippleTestApi&) = delete;
FloodFillInkDropRippleTestApi& operator=(
const FloodFillInkDropRippleTestApi&) = delete;
~FloodFillInkDropRippleTestApi() override;
// Transforms |point| into the FloodFillInkDropRipples clip layer coordinate
// space for the given radius.
gfx::Point3F MapPoint(float radius, const gfx::Point3F& point);
// Returns the center point that the ripple is drawn at in the original Canvas
// coordinate space.
gfx::Point GetDrawnCenterPoint() const;
// Wrapper for FloodFillInkDropRipple::MaxDistanceToCorners().
float MaxDistanceToCorners(const gfx::Point& point) const;
// Gets the transform currently applied to the painted layer of the ripple.
gfx::Transform GetPaintedLayerTransform() const;
// InkDropRippleTestApi:
float GetCurrentOpacity() const override;
protected:
// InkDropRippleTestApi:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
private:
FloodFillInkDropRipple* ink_drop_ripple() {
return static_cast<const FloodFillInkDropRippleTestApi*>(this)
->ink_drop_ripple();
}
FloodFillInkDropRipple* ink_drop_ripple() const {
return static_cast<FloodFillInkDropRipple*>(
InkDropRippleTestApi::ink_drop_ripple());
}
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_FLOOD_FILL_INK_DROP_RIPPLE_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/flood_fill_ink_drop_ripple_test_api.h | C++ | unknown | 2,182 |
// 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/animation/test/ink_drop_highlight_test_api.h"
#include "base/time/time.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/test/layer_animator_test_controller.h"
#include "ui/views/animation/ink_drop_highlight.h"
namespace views::test {
InkDropHighlightTestApi::InkDropHighlightTestApi(
InkDropHighlight* ink_drop_highlight)
: ui::test::MultiLayerAnimatorTestController(this),
ink_drop_highlight_(ink_drop_highlight) {}
InkDropHighlightTestApi::~InkDropHighlightTestApi() = default;
std::vector<ui::LayerAnimator*> InkDropHighlightTestApi::GetLayerAnimators() {
std::vector<ui::LayerAnimator*> animators;
animators.push_back(ink_drop_highlight()->layer_->GetAnimator());
return animators;
}
gfx::Transform InkDropHighlightTestApi::CalculateTransform() {
return ink_drop_highlight()->CalculateTransform();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_highlight_test_api.cc | C++ | unknown | 1,077 |
// 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_ANIMATION_TEST_INK_DROP_HIGHLIGHT_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_INK_DROP_HIGHLIGHT_TEST_API_H_
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/compositor/test/multi_layer_animator_test_controller.h"
#include "ui/compositor/test/multi_layer_animator_test_controller_delegate.h"
#include "ui/gfx/geometry/transform.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views {
class InkDropHighlight;
namespace test {
// Test API to provide internal access to an InkDropHighlight instance. This can
// also be used to control the animations via the
// ui::test::MultiLayerAnimatorTestController API.
class InkDropHighlightTestApi
: public ui::test::MultiLayerAnimatorTestController,
public ui::test::MultiLayerAnimatorTestControllerDelegate {
public:
explicit InkDropHighlightTestApi(InkDropHighlight* ink_drop_highlight);
InkDropHighlightTestApi(const InkDropHighlightTestApi&) = delete;
InkDropHighlightTestApi& operator=(const InkDropHighlightTestApi&) = delete;
~InkDropHighlightTestApi() override;
// MultiLayerAnimatorTestControllerDelegate:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
gfx::Transform CalculateTransform();
protected:
InkDropHighlight* ink_drop_highlight() {
return static_cast<const InkDropHighlightTestApi*>(this)
->ink_drop_highlight();
}
InkDropHighlight* ink_drop_highlight() const { return ink_drop_highlight_; }
private:
// The InkDropHighlight to provide internal access to.
raw_ptr<InkDropHighlight> ink_drop_highlight_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_INK_DROP_HIGHLIGHT_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_highlight_test_api.h | C++ | unknown | 1,849 |
// 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/animation/test/ink_drop_host_test_api.h"
#include <utility>
namespace views::test {
InkDropHostTestApi::InkDropHostTestApi(InkDropHost* ink_drop_host)
: ink_drop_host_(ink_drop_host) {}
InkDropHostTestApi::~InkDropHostTestApi() = default;
void InkDropHostTestApi::SetInkDropMode(InkDropMode ink_drop_mode) {
ink_drop_host_->SetMode(ink_drop_mode);
}
void InkDropHostTestApi::SetInkDrop(std::unique_ptr<InkDrop> ink_drop,
bool handles_gesture_events) {
ink_drop_host_->SetMode(
handles_gesture_events
? views::InkDropHost::InkDropMode::ON
: views::InkDropHost::InkDropMode::ON_NO_GESTURE_HANDLER);
ink_drop_host_->ink_drop_ = std::move(ink_drop);
}
void InkDropHostTestApi::SetInkDrop(std::unique_ptr<InkDrop> ink_drop) {
SetInkDrop(std::move(ink_drop), true);
}
bool InkDropHostTestApi::HasInkDrop() const {
return ink_drop_host_->HasInkDrop();
}
InkDrop* InkDropHostTestApi::GetInkDrop() {
return ink_drop_host_->GetInkDrop();
}
void InkDropHostTestApi::AnimateToState(InkDropState state,
const ui::LocatedEvent* event) {
ink_drop_host_->AnimateToState(state, event);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_host_test_api.cc | C++ | unknown | 1,393 |
// 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_ANIMATION_TEST_INK_DROP_HOST_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_INK_DROP_HOST_TEST_API_H_
#include <memory>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_host.h"
namespace views::test {
// Test API to provide internal access to an InkDropHost instance.
class InkDropHostTestApi {
public:
// Make the protected enum accessible.
using InkDropMode = views::InkDropHost::InkDropMode;
explicit InkDropHostTestApi(InkDropHost* ink_drop_host);
InkDropHostTestApi(const InkDropHostTestApi&) = delete;
InkDropHostTestApi& operator=(const InkDropHostTestApi&) = delete;
~InkDropHostTestApi();
void SetInkDropMode(InkDropMode ink_drop_mode);
void SetInkDrop(std::unique_ptr<InkDrop> ink_drop,
bool handles_gesture_events);
void SetInkDrop(std::unique_ptr<InkDrop> ink_drop);
InkDrop* ink_drop() { return ink_drop_host_->ink_drop_.get(); }
// Wrapper for InkDropHost::HasInkDrop().
bool HasInkDrop() const;
// Wrapper for InkDropHost::GetInkDrop() which lazily creates the ink drop
// instance if it doesn't already exist. If you need direct access to
// InkDropHost::ink_drop_ use ink_drop() instead.
InkDrop* GetInkDrop();
bool HasInkdropEventHandler() const;
// Wrapper for InkDropHost::AnimateToState().
void AnimateToState(InkDropState state, const ui::LocatedEvent* event);
InkDropMode ink_drop_mode() const { return ink_drop_host_->ink_drop_mode_; }
private:
// The InkDropHost to provide internal access to.
raw_ptr<InkDropHost, DanglingUntriaged> ink_drop_host_;
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_INK_DROP_HOST_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_host_test_api.h | C++ | unknown | 1,888 |
// 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/animation/test/ink_drop_impl_test_api.h"
#include <utility>
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_highlight_test_api.h"
#include "ui/views/animation/test/ink_drop_ripple_test_api.h"
namespace views::test {
//
// AccessFactoryOnExitHighlightState
//
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::Install(
InkDropImpl::HighlightStateFactory* state_factory) {
state_factory->ink_drop()->SetHighlightState(
std::make_unique<InkDropImplTestApi::AccessFactoryOnExitHighlightState>(
state_factory));
}
InkDropImplTestApi::AccessFactoryOnExitHighlightState::
AccessFactoryOnExitHighlightState(
InkDropImpl::HighlightStateFactory* state_factory)
: HighlightState(state_factory) {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::Exit() {
state_factory()->ink_drop()->SetHovered(false);
}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::
ShowOnHoverChanged() {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::OnHoverChanged() {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::
ShowOnFocusChanged() {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::OnFocusChanged() {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::AnimationStarted(
InkDropState ink_drop_state) {}
void InkDropImplTestApi::AccessFactoryOnExitHighlightState::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {}
//
// AccessFactoryOnExitHighlightState
//
void InkDropImplTestApi::SetStateOnExitHighlightState::Install(
InkDropImpl::HighlightStateFactory* state_factory) {
state_factory->ink_drop()->SetHighlightState(
std::make_unique<InkDropImplTestApi::SetStateOnExitHighlightState>(
state_factory));
}
InkDropImplTestApi::SetStateOnExitHighlightState::SetStateOnExitHighlightState(
InkDropImpl::HighlightStateFactory* state_factory)
: HighlightState(state_factory) {}
void InkDropImplTestApi::SetStateOnExitHighlightState::Exit() {
InkDropImplTestApi::AccessFactoryOnExitHighlightState::Install(
state_factory());
}
void InkDropImplTestApi::SetStateOnExitHighlightState::ShowOnHoverChanged() {}
void InkDropImplTestApi::SetStateOnExitHighlightState::OnHoverChanged() {}
void InkDropImplTestApi::SetStateOnExitHighlightState::ShowOnFocusChanged() {}
void InkDropImplTestApi::SetStateOnExitHighlightState::OnFocusChanged() {}
void InkDropImplTestApi::SetStateOnExitHighlightState::AnimationStarted(
InkDropState ink_drop_state) {}
void InkDropImplTestApi::SetStateOnExitHighlightState::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {}
//
// InkDropImplTestApi
//
InkDropImplTestApi::InkDropImplTestApi(InkDropImpl* ink_drop)
: ui::test::MultiLayerAnimatorTestController(this), ink_drop_(ink_drop) {}
InkDropImplTestApi::~InkDropImplTestApi() = default;
void InkDropImplTestApi::SetShouldHighlight(bool should_highlight) {
ink_drop_->SetShowHighlightOnHover(should_highlight);
ink_drop_->SetHovered(should_highlight);
ink_drop_->SetShowHighlightOnFocus(should_highlight);
ink_drop_->SetFocused(should_highlight);
DCHECK_EQ(should_highlight, ink_drop_->ShouldHighlight());
}
void InkDropImplTestApi::SetHighlightState(
std::unique_ptr<InkDropImpl::HighlightState> highlight_state) {
ink_drop_->highlight_state_ = std::move(highlight_state);
}
const InkDropHighlight* InkDropImplTestApi::highlight() const {
return ink_drop_->highlight_.get();
}
bool InkDropImplTestApi::IsHighlightFadingInOrVisible() const {
return ink_drop_->IsHighlightFadingInOrVisible();
}
bool InkDropImplTestApi::ShouldHighlight() const {
return ink_drop_->ShouldHighlight();
}
ui::Layer* InkDropImplTestApi::GetRootLayer() const {
return ink_drop_->root_layer_.get();
}
std::vector<ui::LayerAnimator*> InkDropImplTestApi::GetLayerAnimators() {
std::vector<ui::LayerAnimator*> animators;
if (ink_drop_->highlight_) {
InkDropHighlightTestApi* ink_drop_highlight_test_api =
ink_drop_->highlight_->GetTestApi();
std::vector<ui::LayerAnimator*> ink_drop_highlight_animators =
ink_drop_highlight_test_api->GetLayerAnimators();
animators.insert(animators.end(), ink_drop_highlight_animators.begin(),
ink_drop_highlight_animators.end());
}
if (ink_drop_->ink_drop_ripple_) {
InkDropRippleTestApi* ink_drop_ripple_test_api =
ink_drop_->ink_drop_ripple_->GetTestApi();
std::vector<ui::LayerAnimator*> ink_drop_ripple_animators =
ink_drop_ripple_test_api->GetLayerAnimators();
animators.insert(animators.end(), ink_drop_ripple_animators.begin(),
ink_drop_ripple_animators.end());
}
return animators;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_impl_test_api.cc | C++ | unknown | 5,056 |
// 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_ANIMATION_TEST_INK_DROP_IMPL_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_INK_DROP_IMPL_TEST_API_H_
#include <memory>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/compositor/test/multi_layer_animator_test_controller.h"
#include "ui/compositor/test/multi_layer_animator_test_controller_delegate.h"
#include "ui/views/animation/ink_drop_impl.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views {
class InkDropHighlight;
namespace test {
// Test API to provide internal access to an InkDropImpl instance. This can also
// be used to control the InkDropRipple and InkDropHighlight animations via the
// ui::test::MultiLayerAnimatorTestController API.
class InkDropImplTestApi
: public ui::test::MultiLayerAnimatorTestController,
public ui::test::MultiLayerAnimatorTestControllerDelegate {
public:
// Highlight state that access the HighlightStateFactory during the Exit()
// method.
class AccessFactoryOnExitHighlightState : public InkDropImpl::HighlightState {
public:
// Installs an instance of |this| to the ink drop that owns |state_factory|.
static void Install(InkDropImpl::HighlightStateFactory* state_factory);
explicit AccessFactoryOnExitHighlightState(
InkDropImpl::HighlightStateFactory* state_factory);
AccessFactoryOnExitHighlightState(
const AccessFactoryOnExitHighlightState&) = delete;
AccessFactoryOnExitHighlightState& operator=(
const AccessFactoryOnExitHighlightState&) = delete;
// HighlightState:
void Exit() override;
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
};
// Highlight state that attempts to set a new highlight state during Exit().
class SetStateOnExitHighlightState : public InkDropImpl::HighlightState {
public:
// Installs an instance of |this| to the ink drop that owns |state_factory|.
static void Install(InkDropImpl::HighlightStateFactory* state_factory);
explicit SetStateOnExitHighlightState(
InkDropImpl::HighlightStateFactory* state_factory);
SetStateOnExitHighlightState(const SetStateOnExitHighlightState&) = delete;
SetStateOnExitHighlightState& operator=(
const SetStateOnExitHighlightState&) = delete;
// HighlightState:
void Exit() override;
void ShowOnHoverChanged() override;
void OnHoverChanged() override;
void ShowOnFocusChanged() override;
void OnFocusChanged() override;
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
};
explicit InkDropImplTestApi(InkDropImpl* ink_drop);
InkDropImplTestApi(const InkDropImplTestApi&) = delete;
InkDropImplTestApi& operator=(const InkDropImplTestApi&) = delete;
~InkDropImplTestApi() override;
// Ensures that |ink_drop_|->ShouldHighlight() returns the same value as
// |should_highlight| by updating the hover/focus status of |ink_drop_|.
void SetShouldHighlight(bool should_highlight);
// Wrappers to InkDropImpl internals:
InkDropImpl::HighlightStateFactory* state_factory() {
return &ink_drop_->highlight_state_factory_;
}
void SetHighlightState(
std::unique_ptr<InkDropImpl::HighlightState> highlight_state);
const InkDropHighlight* highlight() const;
bool IsHighlightFadingInOrVisible() const;
bool ShouldHighlight() const;
ui::Layer* GetRootLayer() const;
protected:
// MultiLayerAnimatorTestControllerDelegate:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
private:
// The InkDrop to provide internal access to.
raw_ptr<InkDropImpl> ink_drop_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_INK_DROP_IMPL_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_impl_test_api.h | C++ | unknown | 4,218 |
// 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/animation/test/ink_drop_ripple_test_api.h"
namespace views::test {
InkDropRippleTestApi::InkDropRippleTestApi(InkDropRipple* ink_drop_ripple)
: ui::test::MultiLayerAnimatorTestController(this),
ink_drop_ripple_(ink_drop_ripple) {}
InkDropRippleTestApi::~InkDropRippleTestApi() = default;
std::vector<ui::LayerAnimator*> InkDropRippleTestApi::GetLayerAnimators() {
return std::vector<ui::LayerAnimator*>();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_ripple_test_api.cc | C++ | unknown | 616 |
// 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_ANIMATION_TEST_INK_DROP_RIPPLE_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_INK_DROP_RIPPLE_TEST_API_H_
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/compositor/test/multi_layer_animator_test_controller.h"
#include "ui/compositor/test/multi_layer_animator_test_controller_delegate.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views {
class InkDropRipple;
namespace test {
// Test API to provide internal access to an InkDropRipple instance. This can
// also be used to control the animations via the
// ui::test::MultiLayerAnimatorTestController API.
class InkDropRippleTestApi
: public ui::test::MultiLayerAnimatorTestController,
public ui::test::MultiLayerAnimatorTestControllerDelegate {
public:
explicit InkDropRippleTestApi(InkDropRipple* ink_drop_ripple);
InkDropRippleTestApi(const InkDropRippleTestApi&) = delete;
InkDropRippleTestApi& operator=(const InkDropRippleTestApi&) = delete;
~InkDropRippleTestApi() override;
// Gets the opacity of the ink drop.
virtual float GetCurrentOpacity() const = 0;
// MultiLayerAnimatorTestControllerDelegate:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
protected:
InkDropRipple* ink_drop_ripple() {
return static_cast<const InkDropRippleTestApi*>(this)->ink_drop_ripple();
}
InkDropRipple* ink_drop_ripple() const { return ink_drop_ripple_; }
private:
// The InkDropedRipple to provide internal access to.
raw_ptr<InkDropRipple> ink_drop_ripple_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_INK_DROP_RIPPLE_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_ripple_test_api.h | C++ | unknown | 1,778 |
// 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 <ostream>
#include "ui/views/animation/ink_drop_animation_ended_reason.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_state.h"
namespace views {
void PrintTo(InkDropState ink_drop_state, ::std::ostream* os) {
*os << ToString(ink_drop_state);
}
void PrintTo(InkDropHighlight::AnimationType animation_type,
::std::ostream* os) {
*os << ToString(animation_type);
}
void PrintTo(InkDropAnimationEndedReason reason, ::std::ostream* os) {
*os << ToString(reason);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/ink_drop_utils.cc | C++ | unknown | 705 |
// 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/animation/test/square_ink_drop_ripple_test_api.h"
#include <vector>
#include "base/time/time.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/test/layer_animator_test_controller.h"
#include "ui/views/animation/ink_drop_ripple.h"
namespace views::test {
SquareInkDropRippleTestApi::SquareInkDropRippleTestApi(
SquareInkDropRipple* ink_drop_ripple)
: InkDropRippleTestApi(ink_drop_ripple) {}
SquareInkDropRippleTestApi::~SquareInkDropRippleTestApi() = default;
void SquareInkDropRippleTestApi::CalculateCircleTransforms(
const gfx::Size& size,
InkDropTransforms* transforms_out) const {
ink_drop_ripple()->CalculateCircleTransforms(size, transforms_out);
}
void SquareInkDropRippleTestApi::CalculateRectTransforms(
const gfx::Size& size,
float corner_radius,
InkDropTransforms* transforms_out) const {
ink_drop_ripple()->CalculateRectTransforms(size, corner_radius,
transforms_out);
}
float SquareInkDropRippleTestApi::GetCurrentOpacity() const {
return ink_drop_ripple()->GetCurrentOpacity();
}
std::vector<ui::LayerAnimator*>
SquareInkDropRippleTestApi::GetLayerAnimators() {
std::vector<ui::LayerAnimator*> animators =
InkDropRippleTestApi::GetLayerAnimators();
animators.push_back(ink_drop_ripple()->GetRootLayer()->GetAnimator());
for (auto& painted_layer : ink_drop_ripple()->painted_layers_)
animators.push_back(painted_layer->GetAnimator());
return animators;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/square_ink_drop_ripple_test_api.cc | C++ | unknown | 1,718 |
// 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_ANIMATION_TEST_SQUARE_INK_DROP_RIPPLE_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_RIPPLE_TEST_API_H_
#include <vector>
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_ripple_test_api.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views::test {
// Test API to provide internal access to a SquareInkDropRipple.
class SquareInkDropRippleTestApi : public InkDropRippleTestApi {
public:
// Make the private typedefs accessible.
using InkDropTransforms = SquareInkDropRipple::InkDropTransforms;
using PaintedShape = SquareInkDropRipple::PaintedShape;
explicit SquareInkDropRippleTestApi(SquareInkDropRipple* ink_drop_ripple);
SquareInkDropRippleTestApi(const SquareInkDropRippleTestApi&) = delete;
SquareInkDropRippleTestApi& operator=(const SquareInkDropRippleTestApi&) =
delete;
~SquareInkDropRippleTestApi() override;
// Wrapper functions to the wrapped InkDropRipple:
void CalculateCircleTransforms(const gfx::Size& size,
InkDropTransforms* transforms_out) const;
void CalculateRectTransforms(const gfx::Size& size,
float corner_radius,
InkDropTransforms* transforms_out) const;
// InkDropRippleTestApi:
float GetCurrentOpacity() const override;
protected:
// InkDropRippleTestApi:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
private:
SquareInkDropRipple* ink_drop_ripple() {
return static_cast<const SquareInkDropRippleTestApi*>(this)
->ink_drop_ripple();
}
SquareInkDropRipple* ink_drop_ripple() const {
return static_cast<SquareInkDropRipple*>(
InkDropRippleTestApi::ink_drop_ripple());
}
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_RIPPLE_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/square_ink_drop_ripple_test_api.h | C++ | unknown | 2,070 |
// 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/animation/test/test_ink_drop.h"
#include "ui/gfx/geometry/transform.h"
namespace views::test {
TestInkDrop::TestInkDrop() = default;
TestInkDrop::~TestInkDrop() = default;
void TestInkDrop::HostSizeChanged(const gfx::Size& new_size) {}
void TestInkDrop::HostTransformChanged(const gfx::Transform& new_transform) {}
InkDropState TestInkDrop::GetTargetInkDropState() const {
return state_;
}
void TestInkDrop::AnimateToState(InkDropState ink_drop_state) {
state_ = ink_drop_state;
}
void TestInkDrop::SetHoverHighlightFadeDuration(base::TimeDelta duration_ms) {}
void TestInkDrop::UseDefaultHoverHighlightFadeDuration() {}
void TestInkDrop::SnapToActivated() {
state_ = InkDropState::ACTIVATED;
}
void TestInkDrop::SnapToHidden() {
state_ = InkDropState::HIDDEN;
}
void TestInkDrop::SetHovered(bool is_hovered) {
is_hovered_ = is_hovered;
}
void TestInkDrop::SetFocused(bool is_focused) {}
bool TestInkDrop::IsHighlightFadingInOrVisible() const {
return false;
}
void TestInkDrop::SetShowHighlightOnHover(bool show_highlight_on_hover) {}
void TestInkDrop::SetShowHighlightOnFocus(bool show_highlight_on_focus) {}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop.cc | C++ | unknown | 1,330 |
// 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_ANIMATION_TEST_TEST_INK_DROP_H_
#define UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_H_
#include "ui/views/animation/ink_drop.h"
namespace views::test {
// A InkDrop test double that tracks the last requested state changes.
//
// NOTE: This does not auto transition between any of the InkDropStates.
//
class TestInkDrop : public InkDrop {
public:
TestInkDrop();
TestInkDrop(const TestInkDrop&) = delete;
TestInkDrop& operator=(const TestInkDrop&) = delete;
~TestInkDrop() override;
bool is_hovered() const { return is_hovered_; }
// InkDrop:
void HostSizeChanged(const gfx::Size& new_size) override;
void HostTransformChanged(const gfx::Transform& new_transform) override;
InkDropState GetTargetInkDropState() const override;
void AnimateToState(InkDropState ink_drop_state) override;
void SetHoverHighlightFadeDuration(base::TimeDelta duration) override;
void UseDefaultHoverHighlightFadeDuration() override;
void SnapToActivated() override;
void SnapToHidden() override;
void SetHovered(bool is_hovered) override;
void SetFocused(bool is_focused) override;
bool IsHighlightFadingInOrVisible() const override;
void SetShowHighlightOnHover(bool show_highlight_on_hover) override;
void SetShowHighlightOnFocus(bool show_highlight_on_focus) override;
private:
InkDropState state_ = InkDropState::HIDDEN;
bool is_hovered_ = false;
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop.h | C++ | unknown | 1,620 |
// 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_ANIMATION_TEST_TEST_INK_DROP_ANIMATION_OBSERVER_HELPER_H_
#define UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_ANIMATION_OBSERVER_HELPER_H_
#include <algorithm>
#include <vector>
#include "base/ranges/algorithm.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/animation/ink_drop_animation_ended_reason.h"
namespace views::test {
// Context tracking helper that can be used with test implementations of
// ink drop animation observers.
template <typename ContextType>
class TestInkDropAnimationObserverHelper {
public:
TestInkDropAnimationObserverHelper()
: last_animation_started_context_(),
last_animation_ended_context_() {}
TestInkDropAnimationObserverHelper(
const TestInkDropAnimationObserverHelper&) = delete;
TestInkDropAnimationObserverHelper& operator=(
const TestInkDropAnimationObserverHelper&) = delete;
virtual ~TestInkDropAnimationObserverHelper() = default;
int last_animation_started_ordinal() const {
return last_animation_started_ordinal_;
}
ContextType last_animation_started_context() const {
return last_animation_started_context_;
}
int last_animation_ended_ordinal() const {
return last_animation_ended_ordinal_;
}
ContextType last_animation_ended_context() const {
return last_animation_ended_context_;
}
InkDropAnimationEndedReason last_animation_ended_reason() const {
return last_animation_ended_reason_;
}
void OnAnimationStarted(ContextType context) {
animation_started_contexts_.push_back(context);
last_animation_started_context_ = context;
last_animation_started_ordinal_ = GetNextOrdinal();
}
void OnAnimationEnded(ContextType context,
InkDropAnimationEndedReason reason) {
animation_ended_contexts_.push_back(context);
last_animation_ended_context_ = context;
last_animation_ended_ordinal_ = GetNextOrdinal();
last_animation_ended_reason_ = reason;
}
//
// Collection of assertion predicates to be used with GTest test assertions.
// i.e. EXPECT_TRUE/EXPECT_FALSE and the ASSERT_ counterparts.
//
// Example:
//
// TestInkDropAnimationObserverHelper<int> observer;
// event_source.set_observer(observer);
// EXPECT_TRUE(observer.AnimationHasNotStarted());
//
// Passes *_TRUE assertions when an AnimationStarted() event has been
// observed.
testing::AssertionResult AnimationHasStarted() {
if (last_animation_started_ordinal() > 0) {
return testing::AssertionSuccess()
<< "Animations were started at ordinal="
<< last_animation_started_ordinal() << ".";
}
return testing::AssertionFailure() << "Animations have not started.";
}
// Passes *_TRUE assertions when an AnimationStarted() event has NOT been
// observed.
testing::AssertionResult AnimationHasNotStarted() {
if (last_animation_started_ordinal() < 0)
return testing::AssertionSuccess();
return testing::AssertionFailure()
<< "Animations were started at ordinal="
<< last_animation_started_ordinal() << ".";
}
// Passes *_TRUE assertions when an AnimationEnded() event has been observed.
testing::AssertionResult AnimationHasEnded() {
if (last_animation_ended_ordinal() > 0) {
return testing::AssertionSuccess()
<< "Animations were ended at ordinal="
<< last_animation_ended_ordinal() << ".";
}
return testing::AssertionFailure() << "Animations have not ended.";
}
// Passes *_TRUE assertions when an AnimationEnded() event has NOT been
// observed.
testing::AssertionResult AnimationHasNotEnded() {
if (last_animation_ended_ordinal() < 0)
return testing::AssertionSuccess();
return testing::AssertionFailure() << "Animations were ended at ordinal="
<< last_animation_ended_ordinal() << ".";
}
// Passes *_TRUE assertions when |animation_started_context_| is the same as
// |expected_contexts|.
testing::AssertionResult AnimationStartedContextsMatch(
const std::vector<ContextType>& expected_contexts) {
return ContextsMatch(expected_contexts, animation_started_contexts_);
}
// Passes *_TRUE assertions when |animation_ended_context_| is the same as
// |expected_contexts|.
testing::AssertionResult AnimationEndedContextsMatch(
const std::vector<ContextType>& expected_contexts) {
return ContextsMatch(expected_contexts, animation_ended_contexts_);
}
private:
// Helper function that checks if |actual_contexts| is the same as
// |expected_contexts| returning appropriate AssertionResult.
testing::AssertionResult ContextsMatch(
const std::vector<ContextType>& expected_contexts,
const std::vector<ContextType>& actual_contexts) {
const bool match = base::ranges::equal(expected_contexts, actual_contexts);
testing::AssertionResult result =
match ? (testing::AssertionSuccess() << "Expected == Actual: {")
: (testing::AssertionFailure() << "Expected != Actual: {");
for (auto eit = expected_contexts.begin(), ait = actual_contexts.begin();
eit != expected_contexts.end() || ait != actual_contexts.end();) {
if (eit != expected_contexts.begin())
result << ", ";
const bool eexists = eit != expected_contexts.end();
const bool aexists = ait != actual_contexts.end();
const bool item_match = eexists && aexists && *eit == *ait;
result << (eexists ? ToString(*eit) : "<none>")
<< (item_match ? " == " : " != ")
<< (aexists ? ToString(*ait) : "<none>");
if (eexists)
eit++;
if (aexists)
ait++;
}
result << "}";
return result;
}
// Returns the next event ordinal. The first returned ordinal will be 1.
int GetNextOrdinal() const {
return std::max(1, std::max(last_animation_started_ordinal_,
last_animation_ended_ordinal_) +
1);
}
// The ordinal time of the last AnimationStarted() call.
int last_animation_started_ordinal_ = -1;
// List of contexts for which animation is started.
std::vector<ContextType> animation_started_contexts_;
// The |context| passed to the last call to AnimationStarted().
ContextType last_animation_started_context_;
// The ordinal time of the last AnimationEnded() call.
int last_animation_ended_ordinal_ = -1;
// List of contexts for which animation is ended.
std::vector<ContextType> animation_ended_contexts_;
// The |context| passed to the last call to AnimationEnded().
ContextType last_animation_ended_context_;
InkDropAnimationEndedReason last_animation_ended_reason_ =
InkDropAnimationEndedReason::SUCCESS;
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_ANIMATION_OBSERVER_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_animation_observer_helper.h | C++ | unknown | 7,019 |
// 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/animation/test/test_ink_drop_highlight_observer.h"
#include "ui/views/animation/ink_drop_highlight.h"
namespace views::test {
TestInkDropHighlightObserver::TestInkDropHighlightObserver() = default;
void TestInkDropHighlightObserver::AnimationStarted(
InkDropHighlight::AnimationType animation_type) {
ObserverHelper::OnAnimationStarted(animation_type);
}
void TestInkDropHighlightObserver::AnimationEnded(
InkDropHighlight::AnimationType animation_type,
InkDropAnimationEndedReason reason) {
ObserverHelper::OnAnimationEnded(animation_type, reason);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_highlight_observer.cc | C++ | unknown | 765 |
// 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_ANIMATION_TEST_TEST_INK_DROP_HIGHLIGHT_OBSERVER_H_
#define UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_HIGHLIGHT_OBSERVER_H_
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_highlight_observer.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/animation/test/test_ink_drop_animation_observer_helper.h"
namespace views::test {
// Simple InkDropHighlightObserver test double that tracks if
// InkDropHighlightObserver methods are invoked and the parameters used for the
// last invocation.
class TestInkDropHighlightObserver : public InkDropHighlightObserver,
public TestInkDropAnimationObserverHelper<
InkDropHighlight::AnimationType> {
public:
TestInkDropHighlightObserver();
TestInkDropHighlightObserver(const TestInkDropHighlightObserver&) = delete;
TestInkDropHighlightObserver& operator=(const TestInkDropHighlightObserver&) =
delete;
~TestInkDropHighlightObserver() override = default;
void set_ink_drop_highlight(InkDropHighlight* ink_drop_highlight) {
ink_drop_highlight_ = ink_drop_highlight;
}
// InkDropHighlightObserver:
void AnimationStarted(
InkDropHighlight::AnimationType animation_type) override;
void AnimationEnded(InkDropHighlight::AnimationType animation_type,
InkDropAnimationEndedReason reason) override;
private:
// The type this inherits from. Reduces verbosity in .cc file.
using ObserverHelper =
TestInkDropAnimationObserverHelper<InkDropHighlight::AnimationType>;
// An InkDropHighlight to spy info from when notifications are handled.
raw_ptr<InkDropHighlight> ink_drop_highlight_ = nullptr;
};
} // namespace views::test
#endif // UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_HIGHLIGHT_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_highlight_observer.h | C++ | unknown | 2,076 |
// 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/animation/test/test_ink_drop_host.h"
#include <memory>
#include "base/functional/bind.h"
#include "ui/gfx/geometry/size.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/square_ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_highlight_test_api.h"
#include "ui/views/animation/test/square_ink_drop_ripple_test_api.h"
namespace views {
class InkDropHost;
namespace {
// Test specific subclass of InkDropRipple that returns a test api from
// GetTestApi().
class TestInkDropRipple : public SquareInkDropRipple {
public:
TestInkDropRipple(InkDropHost* ink_drop_host,
const gfx::Size& large_size,
int large_corner_radius,
const gfx::Size& small_size,
int small_corner_radius,
const gfx::Point& center_point,
SkColor color,
float visible_opacity)
: SquareInkDropRipple(ink_drop_host,
large_size,
large_corner_radius,
small_size,
small_corner_radius,
center_point,
color,
visible_opacity) {}
TestInkDropRipple(const TestInkDropRipple&) = delete;
TestInkDropRipple& operator=(const TestInkDropRipple&) = delete;
~TestInkDropRipple() override = default;
test::InkDropRippleTestApi* GetTestApi() override {
if (!test_api_)
test_api_ = std::make_unique<test::SquareInkDropRippleTestApi>(this);
return test_api_.get();
}
private:
std::unique_ptr<test::InkDropRippleTestApi> test_api_;
};
// Test specific subclass of InkDropHighlight that returns a test api from
// GetTestApi().
class TestInkDropHighlight : public InkDropHighlight {
public:
TestInkDropHighlight(const gfx::Size& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color)
: InkDropHighlight(size, corner_radius, center_point, color) {}
TestInkDropHighlight(const TestInkDropHighlight&) = delete;
TestInkDropHighlight& operator=(const TestInkDropHighlight&) = delete;
~TestInkDropHighlight() override = default;
test::InkDropHighlightTestApi* GetTestApi() override {
if (!test_api_)
test_api_ = std::make_unique<test::InkDropHighlightTestApi>(this);
return test_api_.get();
}
private:
std::unique_ptr<test::InkDropHighlightTestApi> test_api_;
};
} // namespace
TestInkDropHost::TestInkDropHost(
InkDropImpl::AutoHighlightMode auto_highlight_mode) {
InkDrop::Install(this, std::make_unique<InkDropHost>(this));
InkDrop::Get(this)->SetCreateInkDropCallback(base::BindRepeating(
[](TestInkDropHost* host,
InkDropImpl::AutoHighlightMode auto_highlight_mode)
-> std::unique_ptr<views::InkDrop> {
return std::make_unique<views::InkDropImpl>(
InkDrop::Get(host), host->size(), auto_highlight_mode);
},
this, auto_highlight_mode));
InkDrop::Get(this)->SetCreateHighlightCallback(base::BindRepeating(
[](TestInkDropHost* host) -> std::unique_ptr<views::InkDropHighlight> {
auto highlight = std::make_unique<TestInkDropHighlight>(
host->size(), 0, gfx::PointF(), SK_ColorBLACK);
if (host->disable_timers_for_test_)
highlight->GetTestApi()->SetDisableAnimationTimers(true);
host->num_ink_drop_highlights_created_++;
host->last_ink_drop_highlight_ = highlight.get();
return highlight;
},
this));
InkDrop::Get(this)->SetCreateRippleCallback(base::BindRepeating(
[](TestInkDropHost* host) -> std::unique_ptr<views::InkDropRipple> {
auto ripple = std::make_unique<TestInkDropRipple>(
InkDrop::Get(host), host->size(), 0, host->size(), 0, gfx::Point(),
SK_ColorBLACK, 0.175f);
if (host->disable_timers_for_test_)
ripple->GetTestApi()->SetDisableAnimationTimers(true);
host->num_ink_drop_ripples_created_++;
host->last_ink_drop_ripple_ = ripple.get();
return ripple;
},
this));
}
void TestInkDropHost::AddLayerToRegion(ui::Layer* layer,
views::LayerRegion region) {
++num_ink_drop_layers_added_;
}
void TestInkDropHost::RemoveLayerFromRegions(ui::Layer* layer) {
++num_ink_drop_layers_removed_;
}
TestInkDropHost::~TestInkDropHost() {
// 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);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_host.cc | C++ | unknown | 5,026 |
// 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_ANIMATION_TEST_TEST_INK_DROP_HOST_H_
#define UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_HOST_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_impl.h"
namespace views {
// A non-functional implementation of an View with an ink drop that can be used
// during tests. Tracks the number of hosted ink drop layers.
class TestInkDropHost : public View {
public:
explicit TestInkDropHost(InkDropImpl::AutoHighlightMode auto_highlight_mode =
InkDropImpl::AutoHighlightMode::NONE);
TestInkDropHost(const TestInkDropHost&) = delete;
TestInkDropHost& operator=(const TestInkDropHost&) = delete;
~TestInkDropHost() override;
int num_ink_drop_layers_added() const { return num_ink_drop_layers_added_; }
int num_ink_drop_layers() const {
return num_ink_drop_layers_added_ - num_ink_drop_layers_removed_;
}
int num_ink_drop_ripples_created() const {
return num_ink_drop_ripples_created_;
}
int num_ink_drop_highlights_created() const {
return num_ink_drop_highlights_created_;
}
const InkDropRipple* last_ink_drop_ripple() const {
return last_ink_drop_ripple_;
}
const InkDropHighlight* last_ink_drop_highlight() const {
return last_ink_drop_highlight_;
}
void set_disable_timers_for_test(bool disable_timers_for_test) {
disable_timers_for_test_ = disable_timers_for_test;
}
// View:
void AddLayerToRegion(ui::Layer* layer, views::LayerRegion region) override;
void RemoveLayerFromRegions(ui::Layer* layer) override;
private:
int num_ink_drop_layers_added_ = 0;
int num_ink_drop_layers_removed_ = 0;
// CreateInkDrop{Ripple,Highlight} are const, so these members must be
// mutable.
mutable int num_ink_drop_ripples_created_ = 0;
mutable int num_ink_drop_highlights_created_ = 0;
mutable raw_ptr<const InkDropRipple> last_ink_drop_ripple_ = nullptr;
mutable raw_ptr<const InkDropHighlight> last_ink_drop_highlight_ = nullptr;
// When true, the InkDropRipple/InkDropHighlight instances will have their
// timers disabled after creation.
bool disable_timers_for_test_ = false;
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_HOST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_host.h | C++ | unknown | 2,405 |
// 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/animation/test/test_ink_drop_ripple_observer.h"
#include "ui/views/animation/ink_drop_ripple.h"
namespace views::test {
TestInkDropRippleObserver::TestInkDropRippleObserver() = default;
TestInkDropRippleObserver::~TestInkDropRippleObserver() = default;
void TestInkDropRippleObserver::AnimationStarted(InkDropState ink_drop_state) {
ObserverHelper::OnAnimationStarted(ink_drop_state);
if (ink_drop_ripple_) {
target_state_at_last_animation_started_ =
ink_drop_ripple_->target_ink_drop_state();
}
}
void TestInkDropRippleObserver::AnimationEnded(
InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) {
ObserverHelper::OnAnimationEnded(ink_drop_state, reason);
if (ink_drop_ripple_) {
target_state_at_last_animation_ended_ =
ink_drop_ripple_->target_ink_drop_state();
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_ripple_observer.cc | C++ | unknown | 1,024 |
// 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_ANIMATION_TEST_TEST_INK_DROP_RIPPLE_OBSERVER_H_
#define UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_RIPPLE_OBSERVER_H_
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/animation/ink_drop_ripple_observer.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/animation/test/test_ink_drop_animation_observer_helper.h"
namespace views {
class InkDropRipple;
namespace test {
// Simple InkDropRippleObserver test double that tracks if InkDropRippleObserver
// methods are invoked and the parameters used for the last invocation.
class TestInkDropRippleObserver
: public InkDropRippleObserver,
public TestInkDropAnimationObserverHelper<InkDropState> {
public:
TestInkDropRippleObserver();
TestInkDropRippleObserver(const TestInkDropRippleObserver&) = delete;
TestInkDropRippleObserver& operator=(const TestInkDropRippleObserver&) =
delete;
~TestInkDropRippleObserver() override;
void set_ink_drop_ripple(InkDropRipple* ink_drop_ripple) {
ink_drop_ripple_ = ink_drop_ripple;
}
InkDropState target_state_at_last_animation_started() const {
return target_state_at_last_animation_started_;
}
InkDropState target_state_at_last_animation_ended() const {
return target_state_at_last_animation_ended_;
}
// InkDropRippleObserver:
void AnimationStarted(InkDropState ink_drop_state) override;
void AnimationEnded(InkDropState ink_drop_state,
InkDropAnimationEndedReason reason) override;
private:
// The type this inherits from. Reduces verbosity in .cc file.
using ObserverHelper = TestInkDropAnimationObserverHelper<InkDropState>;
// The value of InkDropRipple::GetTargetInkDropState() the last time an
// AnimationStarted() event was handled. This is only valid if
// |ink_drop_ripple_| is not null.
InkDropState target_state_at_last_animation_started_ = InkDropState::HIDDEN;
// The value of InkDropRipple::GetTargetInkDropState() the last time an
// AnimationEnded() event was handled. This is only valid if
// |ink_drop_ripple_| is not null.
InkDropState target_state_at_last_animation_ended_ = InkDropState::HIDDEN;
// An InkDropRipple to spy info from when notifications are handled.
raw_ptr<InkDropRipple> ink_drop_ripple_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_TEST_INK_DROP_RIPPLE_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/animation/test/test_ink_drop_ripple_observer.h | C++ | unknown | 2,569 |