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 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/test/test_views.h"
#include "ui/events/event.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
namespace views {
StaticSizedView::StaticSizedView(const gfx::Size& preferred_size)
// Default GetMinimumSize() is GetPreferredSize(). Default GetMaximumSize()
// is 0x0.
: preferred_size_(preferred_size), minimum_size_(preferred_size) {}
StaticSizedView::~StaticSizedView() = default;
gfx::Size StaticSizedView::CalculatePreferredSize() const {
return preferred_size_;
}
gfx::Size StaticSizedView::GetMinimumSize() const {
return minimum_size_;
}
gfx::Size StaticSizedView::GetMaximumSize() const {
return maximum_size_;
}
ProportionallySizedView::ProportionallySizedView(int factor)
: factor_(factor) {}
ProportionallySizedView::~ProportionallySizedView() = default;
void ProportionallySizedView::SetPreferredWidth(int width) {
preferred_width_ = width;
PreferredSizeChanged();
}
int ProportionallySizedView::GetHeightForWidth(int w) const {
return w * factor_;
}
gfx::Size ProportionallySizedView::CalculatePreferredSize() const {
if (preferred_width_ >= 0)
return gfx::Size(preferred_width_, GetHeightForWidth(preferred_width_));
return View::CalculatePreferredSize();
}
CloseWidgetView::CloseWidgetView(ui::EventType event_type)
: event_type_(event_type) {}
void CloseWidgetView::OnEvent(ui::Event* event) {
if (event->type() == event_type_) {
// Go through NativeWidgetPrivate to simulate what happens if the OS
// deletes the NativeWindow out from under us.
// TODO(tapted): Change this to ViewsTestBase::SimulateNativeDestroy for a
// more authentic test on Mac.
GetWidget()->native_widget_private()->CloseNow();
} else {
View::OnEvent(event);
if (!event->IsTouchEvent())
event->SetHandled();
}
}
EventCountView::EventCountView() = default;
EventCountView::~EventCountView() = default;
int EventCountView::GetEventCount(ui::EventType type) {
return event_count_[type];
}
void EventCountView::ResetCounts() {
event_count_.clear();
}
void EventCountView::OnMouseMoved(const ui::MouseEvent& event) {
// MouseMove events are not re-dispatched from the RootView.
++event_count_[ui::ET_MOUSE_MOVED];
last_flags_ = 0;
}
void EventCountView::OnKeyEvent(ui::KeyEvent* event) {
RecordEvent(event);
}
void EventCountView::OnMouseEvent(ui::MouseEvent* event) {
RecordEvent(event);
}
void EventCountView::OnScrollEvent(ui::ScrollEvent* event) {
RecordEvent(event);
}
void EventCountView::OnGestureEvent(ui::GestureEvent* event) {
RecordEvent(event);
}
void EventCountView::RecordEvent(ui::Event* event) {
++event_count_[event->type()];
last_flags_ = event->flags();
if (handle_mode_ == CONSUME_EVENTS)
event->SetHandled();
}
ResizeAwareParentView::ResizeAwareParentView() {
SetLayoutManager(
std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal));
}
void ResizeAwareParentView::ChildPreferredSizeChanged(View* child) {
Layout();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_views.cc | C++ | unknown | 3,242 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_TEST_VIEWS_H_
#define UI_VIEWS_TEST_TEST_VIEWS_H_
#include <map>
#include <memory>
#include "ui/events/types/event_type.h"
#include "ui/views/view.h"
namespace views {
// A view that requests a set amount of space.
class StaticSizedView : public View {
public:
explicit StaticSizedView(const gfx::Size& preferred_size = gfx::Size());
StaticSizedView(const StaticSizedView&) = delete;
StaticSizedView& operator=(const StaticSizedView&) = delete;
~StaticSizedView() override;
void set_minimum_size(const gfx::Size& minimum_size) {
minimum_size_ = minimum_size;
InvalidateLayout();
}
void set_maximum_size(const gfx::Size& maximum_size) {
maximum_size_ = maximum_size;
InvalidateLayout();
}
// View overrides:
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
private:
gfx::Size preferred_size_;
gfx::Size minimum_size_;
gfx::Size maximum_size_;
};
// A view that accomodates testing layouts that use GetHeightForWidth.
class ProportionallySizedView : public View {
public:
explicit ProportionallySizedView(int factor);
ProportionallySizedView(const ProportionallySizedView&) = delete;
ProportionallySizedView& operator=(const ProportionallySizedView&) = delete;
~ProportionallySizedView() override;
void SetPreferredWidth(int width);
int GetHeightForWidth(int w) const override;
gfx::Size CalculatePreferredSize() const override;
private:
// The multiplicative factor between width and height, i.e.
// height = width * factor_.
int factor_;
// The width used as the preferred size. -1 if not used.
int preferred_width_ = -1;
};
// Class that closes the widget (which ends up deleting it immediately) when the
// appropriate event is received.
class CloseWidgetView : public View {
public:
explicit CloseWidgetView(ui::EventType event_type);
CloseWidgetView(const CloseWidgetView&) = delete;
CloseWidgetView& operator=(const CloseWidgetView&) = delete;
// ui::EventHandler override:
void OnEvent(ui::Event* event) override;
private:
const ui::EventType event_type_;
};
// A view that keeps track of the events it receives, optionally consuming them.
class EventCountView : public View {
public:
// Whether to call SetHandled() on events as they are received. For some event
// types, this will allow EventCountView to receives future events in the
// event sequence, such as a drag.
enum HandleMode { PROPAGATE_EVENTS, CONSUME_EVENTS };
EventCountView();
EventCountView(const EventCountView&) = delete;
EventCountView& operator=(const EventCountView&) = delete;
~EventCountView() override;
int GetEventCount(ui::EventType type);
void ResetCounts();
int last_flags() const { return last_flags_; }
void set_handle_mode(HandleMode handle_mode) { handle_mode_ = handle_mode; }
protected:
// Overridden from View:
void OnMouseMoved(const ui::MouseEvent& event) override;
// Overridden from ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
private:
void RecordEvent(ui::Event* event);
std::map<ui::EventType, int> event_count_;
int last_flags_ = 0;
HandleMode handle_mode_ = PROPAGATE_EVENTS;
};
// A view which reacts to PreferredSizeChanged() from its children and calls
// Layout().
class ResizeAwareParentView : public View {
public:
ResizeAwareParentView();
ResizeAwareParentView(const ResizeAwareParentView&) = delete;
ResizeAwareParentView& operator=(const ResizeAwareParentView&) = delete;
// Overridden from View:
void ChildPreferredSizeChanged(View* child) override;
};
} // namespace views
#endif // UI_VIEWS_TEST_TEST_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_views.h | C++ | unknown | 4,045 |
// 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_TEST_TEST_VIEWS_DELEGATE_H_
#define UI_VIEWS_TEST_TEST_VIEWS_DELEGATE_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/views_delegate.h"
namespace views {
class TestViewsDelegate : public ViewsDelegate {
public:
TestViewsDelegate();
TestViewsDelegate(const TestViewsDelegate&) = delete;
TestViewsDelegate& operator=(const TestViewsDelegate&) = delete;
~TestViewsDelegate() override;
// If set to |true|, forces widgets that do not provide a native widget to use
// DesktopNativeWidgetAura instead of whatever the default native widget would
// be. This has no effect on ChromeOS.
void set_use_desktop_native_widgets(bool desktop) {
use_desktop_native_widgets_ = desktop;
}
void set_use_transparent_windows(bool transparent) {
use_transparent_windows_ = transparent;
}
// When running on ChromeOS, NativeWidgetAura requires the parent and/or context
// to be non-null. Some test views provide neither, so we do it here. Normally
// this is done by the browser-specific ViewsDelegate.
#if BUILDFLAG(IS_CHROMEOS)
void set_context(gfx::NativeWindow context) { context_ = context; }
#endif
#if BUILDFLAG(IS_MAC)
// Allows tests to provide a ContextFactory via the ViewsDelegate interface.
void set_context_factory(ui::ContextFactory* context_factory) {
context_factory_ = context_factory;
}
#endif
// For convenience, we create a layout provider by default, but embedders
// that use their own layout provider subclasses may need to set those classes
// as the layout providers for their tests.
void set_layout_provider(std::unique_ptr<LayoutProvider> layout_provider) {
layout_provider_.swap(layout_provider);
}
// ViewsDelegate:
#if BUILDFLAG(IS_WIN)
HICON GetSmallWindowIcon() const override;
#endif
void OnBeforeWidgetInit(Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) override;
#if BUILDFLAG(IS_MAC)
ui::ContextFactory* GetContextFactory() override;
#endif
private:
#if BUILDFLAG(IS_MAC)
raw_ptr<ui::ContextFactory> context_factory_ = nullptr;
#endif
bool use_desktop_native_widgets_ = false;
bool use_transparent_windows_ = false;
std::unique_ptr<LayoutProvider> layout_provider_ =
std::make_unique<LayoutProvider>();
#if BUILDFLAG(IS_CHROMEOS)
gfx::NativeWindow context_ = nullptr;
#endif
};
} // namespace views
#endif // UI_VIEWS_TEST_TEST_VIEWS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_views_delegate.h | C++ | unknown | 2,673 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/test_views_delegate.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/views/buildflags.h"
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA)
namespace views {
TestViewsDelegate::TestViewsDelegate() = default;
TestViewsDelegate::~TestViewsDelegate() = default;
#if BUILDFLAG(IS_WIN)
HICON TestViewsDelegate::GetSmallWindowIcon() const {
return nullptr;
}
#endif
void TestViewsDelegate::OnBeforeWidgetInit(
Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
if (!params->parent && !params->context)
params->context = context_;
#endif
if (params->opacity == Widget::InitParams::WindowOpacity::kInferred) {
params->opacity = use_transparent_windows_
? Widget::InitParams::WindowOpacity::kTranslucent
: Widget::InitParams::WindowOpacity::kOpaque;
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
if (!params->native_widget && use_desktop_native_widgets_)
params->native_widget = new DesktopNativeWidgetAura(delegate);
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA)
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_views_delegate_aura.cc | C++ | unknown | 1,409 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/widget/native_widget_mac.h"
namespace views {
TestViewsDelegate::TestViewsDelegate() = default;
TestViewsDelegate::~TestViewsDelegate() = default;
void TestViewsDelegate::OnBeforeWidgetInit(
Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) {
if (params->opacity == Widget::InitParams::WindowOpacity::kInferred) {
params->opacity = use_transparent_windows_
? Widget::InitParams::WindowOpacity::kTranslucent
: Widget::InitParams::WindowOpacity::kOpaque;
}
// TODO(tapted): This should return a *Desktop*NativeWidgetMac.
if (!params->native_widget && use_desktop_native_widgets_)
params->native_widget = new NativeWidgetMac(delegate);
}
ui::ContextFactory* TestViewsDelegate::GetContextFactory() {
return context_factory_;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_views_delegate_mac.mm | Objective-C++ | unknown | 1,060 |
// 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/test/test_widget_observer.h"
#include "base/check_op.h"
#include "ui/views/widget/widget.h"
namespace views::test {
TestWidgetObserver::TestWidgetObserver(Widget* widget) : widget_(widget) {
widget_->AddObserver(this);
}
TestWidgetObserver::~TestWidgetObserver() {
if (widget_)
widget_->RemoveObserver(this);
CHECK(!IsInObserverList());
}
void TestWidgetObserver::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(widget_, widget);
widget_ = nullptr;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_widget_observer.cc | C++ | unknown | 661 |
// 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_TEST_TEST_WIDGET_OBSERVER_H_
#define UI_VIEWS_TEST_TEST_WIDGET_OBSERVER_H_
#include <stddef.h>
#include "base/memory/raw_ptr.h"
#include "ui/views/widget/widget_observer.h"
namespace views::test {
// A Widget observer class used in the tests below to observe bubbles closing.
class TestWidgetObserver : public WidgetObserver {
public:
explicit TestWidgetObserver(Widget* widget);
TestWidgetObserver(const TestWidgetObserver&) = delete;
TestWidgetObserver& operator=(const TestWidgetObserver&) = delete;
~TestWidgetObserver() override;
bool widget_closed() const { return widget_ == nullptr; }
private:
// WidgetObserver overrides:
void OnWidgetDestroying(Widget* widget) override;
raw_ptr<Widget> widget_;
};
} // namespace views::test
#endif // UI_VIEWS_TEST_TEST_WIDGET_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_widget_observer.h | C++ | unknown | 976 |
// 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 <memory>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/ranges/algorithm.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "cef/libcef/features/features.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/test/aura_test_utils.h"
#include "ui/aura/test/ui_controls_factory_aura.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/test/ui_controls.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/ozone_ui_controls_test_helper.h"
#include "ui/views/test/test_desktop_screen_ozone.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace {
ui::OzoneUIControlsTestHelper* g_ozone_ui_controls_test_helper = nullptr;
using ui_controls::DOWN;
using ui_controls::LEFT;
using ui_controls::MIDDLE;
using ui_controls::MouseButton;
using ui_controls::RIGHT;
using ui_controls::UIControlsAura;
using ui_controls::UP;
aura::Window* RootWindowForPoint(const gfx::Point& point,
aura::Window* window_hint = nullptr) {
// Most interactive_ui_tests run inside of the aura_test_helper
// environment. This means that we can't rely on display::Screen and several
// other things to work properly. Therefore we hack around this by
// iterating across the windows owned DesktopWindowTreeHostLinux since this
// doesn't rely on having a DesktopScreenX11.
std::vector<aura::Window*> windows =
views::DesktopWindowTreeHostPlatform::GetAllOpenWindows();
const auto i = base::ranges::find_if(windows, [point](auto* window) {
return window->GetBoundsInScreen().Contains(point) || window->HasCapture();
});
// Compare the window we found (if any) and the window hint (again, if any).
// If there is a hint and a window with capture they had better be the same
// or the test is trying to do something that can't actually happen.
aura::Window* const found =
i != windows.cend() ? (*i)->GetRootWindow() : nullptr;
aura::Window* const hint =
window_hint ? window_hint->GetRootWindow() : nullptr;
if (found && hint && found->HasCapture()) {
CHECK_EQ(found, hint);
}
return hint ? hint : found;
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
aura::Window* TopRootWindow() {
std::vector<aura::Window*> windows =
views::DesktopWindowTreeHostPlatform::GetAllOpenWindows();
DCHECK(!windows.empty());
return windows[0]->GetRootWindow();
}
#endif
} // namespace
namespace ui_controls {
void EnableUIControls() {
// TODO(crbug.com/1396661): This gets called twice in some tests.
// Add DCHECK once these tests are fixed.
if (!g_ozone_ui_controls_test_helper) {
g_ozone_ui_controls_test_helper =
ui::CreateOzoneUIControlsTestHelper().release();
}
}
void ResetUIControlsIfEnabled() {
if (g_ozone_ui_controls_test_helper) {
g_ozone_ui_controls_test_helper->Reset();
}
}
// An interface to provide Aura implementation of UI control.
// static
bool SendKeyPress(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
DCHECK(!command); // No command key on Aura
return SendKeyPressNotifyWhenDone(window, key, control, shift, alt, command,
base::OnceClosure());
}
// static
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command,
base::OnceClosure closure) {
DCHECK(!command); // No command key on Aura
return SendKeyEventsNotifyWhenDone(
window, key, kKeyPress | kKeyRelease, std::move(closure),
GenerateAcceleratorState(control, shift, alt, command));
}
// static
bool SendKeyEvents(gfx::NativeWindow window,
ui::KeyboardCode key,
int key_event_types,
int accelerator_state) {
DCHECK(!(accelerator_state & kCommand)); // No command key on Aura
return SendKeyEventsNotifyWhenDone(window, key, key_event_types,
base::OnceClosure(), accelerator_state);
}
// static
bool SendKeyEventsNotifyWhenDone(gfx::NativeWindow window,
ui::KeyboardCode key,
int key_event_types,
base::OnceClosure closure,
int accelerator_state) {
DCHECK(g_ozone_ui_controls_test_helper);
DCHECK(!(accelerator_state & kCommand)); // No command key on Aura
aura::WindowTreeHost* host = window->GetHost();
g_ozone_ui_controls_test_helper->SendKeyEvents(
host->GetAcceleratedWidget(), key, key_event_types, accelerator_state,
std::move(closure));
return true;
}
// static
bool SendMouseMove(int screen_x, int screen_y, gfx::NativeWindow window_hint) {
return SendMouseMoveNotifyWhenDone(screen_x, screen_y, base::OnceClosure(),
window_hint);
}
// static
bool SendMouseMoveNotifyWhenDone(int screen_x,
int screen_y,
base::OnceClosure task,
gfx::NativeWindow window_hint) {
if (g_ozone_ui_controls_test_helper->SupportsScreenCoordinates()) {
window_hint = nullptr;
}
gfx::Point screen_location(screen_x, screen_y);
gfx::Point root_location = screen_location;
aura::Window* root_window = RootWindowForPoint(screen_location, window_hint);
if (root_window == nullptr) {
return true;
}
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(root_window);
if (screen_position_client) {
screen_position_client->ConvertPointFromScreen(root_window, &root_location);
}
aura::WindowTreeHost* host = root_window->GetHost();
gfx::Point root_current_location =
aura::test::QueryLatestMousePositionRequestInHost(host);
host->ConvertPixelsToDIP(&root_current_location);
#if !BUILDFLAG(ENABLE_CEF)
auto* screen = views::test::TestDesktopScreenOzone::GetInstance();
DCHECK_EQ(screen, display::Screen::GetScreen());
screen->set_cursor_screen_point(gfx::Point(screen_x, screen_y));
#endif
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
if (root_location != root_current_location &&
g_ozone_ui_controls_test_helper->ButtonDownMask() == 0 &&
!g_ozone_ui_controls_test_helper->MustUseUiControlsForMoveCursorTo()) {
// Move the cursor because EnterNotify/LeaveNotify are generated with the
// current mouse position as a result of XGrabPointer()
root_window->MoveCursorTo(root_location);
g_ozone_ui_controls_test_helper->RunClosureAfterAllPendingUIEvents(
std::move(task));
return true;
}
#endif
g_ozone_ui_controls_test_helper->SendMouseMotionNotifyEvent(
host->GetAcceleratedWidget(), root_location, screen_location,
std::move(task));
return true;
}
// static
bool SendMouseEvents(MouseButton type,
int button_state,
int accelerator_state,
gfx::NativeWindow window_hint) {
return SendMouseEventsNotifyWhenDone(type, button_state, base::OnceClosure(),
accelerator_state, window_hint);
}
// static
bool SendMouseEventsNotifyWhenDone(MouseButton type,
int button_state,
base::OnceClosure task,
int accelerator_state,
gfx::NativeWindow window_hint) {
if (g_ozone_ui_controls_test_helper->SupportsScreenCoordinates()) {
window_hint = nullptr;
}
gfx::Point mouse_loc_in_screen =
aura::Env::GetInstance()->last_mouse_location();
gfx::Point mouse_loc = mouse_loc_in_screen;
aura::Window* root_window = RootWindowForPoint(mouse_loc, window_hint);
if (root_window == nullptr) {
return true;
}
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(root_window);
if (screen_position_client) {
screen_position_client->ConvertPointFromScreen(root_window, &mouse_loc);
}
g_ozone_ui_controls_test_helper->SendMouseEvent(
root_window->GetHost()->GetAcceleratedWidget(), type, button_state,
accelerator_state, mouse_loc, mouse_loc_in_screen, std::move(task));
return true;
}
// static
bool SendMouseClick(MouseButton type, gfx::NativeWindow window_hint) {
return SendMouseEvents(type, UP | DOWN, ui_controls::kNoAccelerator,
window_hint);
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// static
bool SendTouchEvents(int action, int id, int x, int y) {
return SendTouchEventsNotifyWhenDone(action, id, x, y, base::OnceClosure());
}
// static
bool SendTouchEventsNotifyWhenDone(int action,
int id,
int x,
int y,
base::OnceClosure task) {
DCHECK(g_ozone_ui_controls_test_helper);
gfx::Point screen_location(x, y);
aura::Window* root_window;
// Touch release events might not have coordinates that match any window, so
// just use whichever window is on top.
if (action & ui_controls::kTouchRelease) {
root_window = TopRootWindow();
} else {
root_window = RootWindowForPoint(screen_location);
}
if (root_window == nullptr) {
return true;
}
g_ozone_ui_controls_test_helper->SendTouchEvent(
root_window->GetHost()->GetAcceleratedWidget(), action, id,
screen_location, std::move(task));
return true;
}
#endif
} // namespace ui_controls
| Zhao-PengFei35/chromium_src_4 | ui/views/test/ui_controls_factory_desktop_aura_ozone.cc | C++ | unknown | 10,264 |
// 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/test/view_metadata_test_utils.h"
#include <string>
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/metadata/metadata_types.h"
namespace views::test {
void TestViewMetadata(View* view) {
ui::metadata::ClassMetaData* meta_data = view->GetClassMetaData();
EXPECT_NE(meta_data, nullptr);
for (auto* property : *meta_data) {
std::u16string value = property->GetValueAsString(view);
ui::metadata::PropertyFlags flags = property->GetPropertyFlags();
if (!(flags & ui::metadata::PropertyFlags::kReadOnly) &&
!!(flags & ui::metadata::PropertyFlags::kSerializable)) {
property->SetValueAsString(view, value);
}
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/view_metadata_test_utils.cc | C++ | unknown | 856 |
// 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_TEST_VIEW_METADATA_TEST_UTILS_H_
#define UI_VIEWS_TEST_VIEW_METADATA_TEST_UTILS_H_
#include "ui/views/view.h"
namespace views::test {
// Iterate through all the metadata for the given instance, reading each
// property and then setting the property. Exercises the getters, setters, and
// property type-converters associated with each.
void TestViewMetadata(View* view);
} // namespace views::test
#endif // UI_VIEWS_TEST_VIEW_METADATA_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/view_metadata_test_utils.h | C++ | unknown | 618 |
// 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/test/view_skia_gold_pixel_diff.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/base/test/skia_gold_matching_algorithm.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/image/image.h"
#include "ui/snapshot/snapshot.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/snapshot/snapshot_aura.h"
#endif
namespace views {
namespace {
void SnapshotCallback(base::RunLoop* run_loop,
gfx::Image* ret_image,
gfx::Image image) {
*ret_image = image;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, run_loop->QuitClosure());
}
} // namespace
ViewSkiaGoldPixelDiff::ViewSkiaGoldPixelDiff() = default;
ViewSkiaGoldPixelDiff::~ViewSkiaGoldPixelDiff() = default;
bool ViewSkiaGoldPixelDiff::CompareViewScreenshot(
const std::string& screenshot_name,
const views::View* view,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm) const {
DCHECK(Initialized()) << "Initialize the class before using this method.";
// Calculate the snapshot bounds in the widget's coordinates.
gfx::Rect rc = view->GetBoundsInScreen();
const views::Widget* widget = view->GetWidget();
gfx::Rect bounds_in_screen = widget->GetRootView()->GetBoundsInScreen();
gfx::Rect bounds = widget->GetRootView()->bounds();
rc.Offset(bounds.x() - bounds_in_screen.x(),
bounds.y() - bounds_in_screen.y());
return CompareNativeWindowScreenshot(
screenshot_name, widget->GetNativeWindow(), rc, algorithm);
}
bool ViewSkiaGoldPixelDiff::CompareNativeWindowScreenshot(
const std::string& screenshot_name,
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm) const {
DCHECK(Initialized()) << "Initialize the class before using this method.";
gfx::Image image;
bool ret = GrabWindowSnapshotInternal(window, snapshot_bounds, &image);
if (!ret) {
return false;
}
return SkiaGoldPixelDiff::CompareScreenshot(screenshot_name,
*image.ToSkBitmap(), algorithm);
}
bool ViewSkiaGoldPixelDiff::CompareNativeWindowScreenshotInRects(
const std::string& screenshot_name,
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm,
const std::vector<gfx::Rect>& regions_of_interest) const {
DCHECK(Initialized()) << "Initialize the class before using this method.";
CHECK(!algorithm || algorithm->GetCommandLineSwitchName() != "sobel");
gfx::Image image;
bool ret = GrabWindowSnapshotInternal(window, snapshot_bounds, &image);
if (!ret) {
return false;
}
// Only keep the pixels within `regions_of_interest` so that the differences
// outside of `regions_of_interest` are ignored.
KeepPixelsInRects(regions_of_interest, &image);
return SkiaGoldPixelDiff::CompareScreenshot(screenshot_name,
*image.ToSkBitmap(), algorithm);
}
bool ViewSkiaGoldPixelDiff::GrabWindowSnapshotInternal(
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) const {
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
#if defined(USE_AURA)
ui::GrabWindowSnapshotAsyncAura(
#else
ui::GrabWindowSnapshotAsync(
#endif
window, snapshot_bounds,
base::BindOnce(&SnapshotCallback, &run_loop, image));
run_loop.Run();
const bool success = !image->IsEmpty();
if (!success) {
LOG(ERROR) << "Grab screenshot failed.";
}
return success;
}
void ViewSkiaGoldPixelDiff::KeepPixelsInRects(
const std::vector<gfx::Rect>& rects,
gfx::Image* image) const {
// `rects` should not be empty.
CHECK(!rects.empty());
// Create a bitmap with the same size as `image`. NOTE: `image` is immutable.
// Therefore, we have to create a new bitmap.
SkBitmap bitmap;
bitmap.allocPixels(image->ToSkBitmap()->info());
bitmap.eraseColor(SK_ColorTRANSPARENT);
// Allow `canvas` to draw on `bitmap`.
SkCanvas canvas(bitmap, SkSurfaceProps{});
// Only copy the pixels within `rects`.
SkPaint paint;
for (const auto& rect : rects) {
canvas.drawImageRect(image->ToSkBitmap()->asImage(),
gfx::RectToSkRect(rect), gfx::RectToSkRect(rect),
SkSamplingOptions(), &paint,
SkCanvas::kStrict_SrcRectConstraint);
}
*image = gfx::Image::CreateFrom1xBitmap(bitmap);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/view_skia_gold_pixel_diff.cc | C++ | unknown | 4,977 |
// 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_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_
#define UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_
#include <string>
#include <vector>
#include "ui/base/test/skia_gold_pixel_diff.h"
#include "ui/gfx/native_widget_types.h"
namespace gfx {
class Rect;
class Image;
} // namespace gfx
namespace ui::test {
class SkiaGoldMatchingAlgorithm;
class SkiaGoldPixelDiff;
} // namespace ui::test
namespace views {
class View;
// This is the utility class to protect views with pixeltest based on Skia Gold.
// For an example on how to write pixeltests, please refer to the demo.
// NOTE: this class has to be initialized before using. A screenshot prefix and
// a corpus string are required for initialization. Check
// `SkiaGoldPixelDiff::Init()` for more details.
class ViewSkiaGoldPixelDiff : public ui::test::SkiaGoldPixelDiff {
public:
ViewSkiaGoldPixelDiff();
ViewSkiaGoldPixelDiff(const ViewSkiaGoldPixelDiff&) = delete;
ViewSkiaGoldPixelDiff& operator=(const ViewSkiaGoldPixelDiff&) = delete;
~ViewSkiaGoldPixelDiff() override;
// Takes a screenshot then uploads to Skia Gold and compares it with the
// remote golden image. Returns true if the screenshot is the same as the
// golden image (compared with hashcode).
// `screenshot_name` specifies the name of the screenshot to be taken. For
// every screenshot you take, it should have a unique name across Chromium,
// because all screenshots (aka golden images) stores in one bucket on GCS.
// The standard convention is to use the browser test class name as the
// prefix. The name will be `screenshot_prefix` + "_" + `screenshot_name`.
// E.g. 'ToolbarTest_BackButtonHover'. Here `screenshot_prefix` is passed as
// an argument during initialization.
// `view` is the view you want to take screenshot.
// `algorithm` specifies how two images are matched. Use the exact match as
// default. Read the comment of `SkiaGoldMatchingAlgorithm` to learn more.
bool CompareViewScreenshot(
const std::string& screenshot_name,
const views::View* view,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm = nullptr) const;
// Similar to `CompareViewScreenshot()`. But the screenshot is taken within
// the specified bounds on `window`. `snapshot_bounds` is based on `window`'s
// local coordinates.
bool CompareNativeWindowScreenshot(
const std::string& screenshot_name,
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm = nullptr) const;
// Similar to `CompareNativeWindowScreenshot()` but with the difference that
// only the pixel differences within `regions_of_interest` should affect the
// comparison result. Each rect in `regions_of_interest` is in pixel
// coordinates. NOTE:
// 1. If `algorithm` is `FuzzySkiaGoldMatchingAlgorithm`, the total amount of
// different pixels across `regions_of_interest` is compared with the
// threshold carried by `algorithm`.
// 2. `algorithm` cannot be `SobelSkiaGoldMatchingAlgorithm` because the
// border of an image with `regions_of_interest` is ambiguous.
bool CompareNativeWindowScreenshotInRects(
const std::string& screenshot_name,
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const ui::test::SkiaGoldMatchingAlgorithm* algorithm,
const std::vector<gfx::Rect>& regions_of_interest) const;
protected:
// Takes a screenshot of `window` within the specified area and stores the
// screenshot in `image`. Returns true if succeeding.
virtual bool GrabWindowSnapshotInternal(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) const;
private:
// Updates `image` so that only the pixels within `rects` are kept.
void KeepPixelsInRects(const std::vector<gfx::Rect>& rects,
gfx::Image* image) const;
};
} // namespace views
#endif // UI_VIEWS_TEST_VIEW_SKIA_GOLD_PIXEL_DIFF_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/view_skia_gold_pixel_diff.h | C++ | unknown | 4,191 |
// 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/test/view_skia_gold_pixel_diff.h"
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
using ::testing::_;
using ::testing::Return;
namespace views {
class MockBrowserSkiaGoldPixelDiff : public ViewSkiaGoldPixelDiff {
public:
MockBrowserSkiaGoldPixelDiff() = default;
MOCK_CONST_METHOD1(LaunchProcess, int(const base::CommandLine&));
bool GrabWindowSnapshotInternal(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) const override {
SkBitmap bitmap;
bitmap.allocN32Pixels(10, 10);
*image = gfx::Image::CreateFrom1xBitmap(bitmap);
return true;
}
};
class MockViewSkiaGoldPixelDiffMockUpload
: public MockBrowserSkiaGoldPixelDiff {
public:
MockViewSkiaGoldPixelDiffMockUpload() = default;
MOCK_CONST_METHOD3(UploadToSkiaGoldServer,
bool(const base::FilePath&,
const std::string&,
const ui::test::SkiaGoldMatchingAlgorithm*));
};
class ViewSkiaGoldPixelDiffTest : public views::test::WidgetTest {
public:
ViewSkiaGoldPixelDiffTest() {
auto* cmd_line = base::CommandLine::ForCurrentProcess();
cmd_line->AppendSwitchASCII("git-revision", "test");
}
ViewSkiaGoldPixelDiffTest(const ViewSkiaGoldPixelDiffTest&) = delete;
ViewSkiaGoldPixelDiffTest& operator=(const ViewSkiaGoldPixelDiffTest&) =
delete;
views::View* AddChildViewToWidget(views::Widget* widget) {
auto view_unique_ptr = std::make_unique<views::View>();
if (widget->client_view())
return widget->client_view()->AddChildView(std::move(view_unique_ptr));
return widget->SetContentsView(std::move(view_unique_ptr));
}
};
TEST_F(ViewSkiaGoldPixelDiffTest, CompareScreenshotByView) {
MockViewSkiaGoldPixelDiffMockUpload mock_pixel;
#if BUILDFLAG(IS_CHROMEOS_ASH)
constexpr char kPrefix[] = "Prefix.Demo.";
#else
constexpr char kPrefix[] = "Prefix_Demo_";
#endif
EXPECT_CALL(mock_pixel,
UploadToSkiaGoldServer(
_, kPrefix + ui::test::SkiaGoldPixelDiff::GetPlatform(), _))
.Times(1)
.WillOnce(Return(true));
views::Widget* widget = CreateTopLevelNativeWidget();
views::View* child_view = AddChildViewToWidget(widget);
mock_pixel.Init("Prefix");
bool ret = mock_pixel.CompareViewScreenshot("Demo", child_view);
EXPECT_TRUE(ret);
widget->CloseNow();
}
TEST_F(ViewSkiaGoldPixelDiffTest, BypassSkiaGoldFunctionality) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
"bypass-skia-gold-functionality");
MockBrowserSkiaGoldPixelDiff mock_pixel;
EXPECT_CALL(mock_pixel, LaunchProcess(_)).Times(0);
views::Widget* widget = CreateTopLevelNativeWidget();
views::View* child_view = AddChildViewToWidget(widget);
mock_pixel.Init("Prefix");
bool ret = mock_pixel.CompareViewScreenshot("Demo", child_view);
EXPECT_TRUE(ret);
widget->CloseNow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/view_skia_gold_pixel_diff_unittest.cc | C++ | unknown | 3,393 |
// 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/test/views_drawing_test_utils.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/compositor/canvas_painter.h"
#include "ui/gfx/color_palette.h"
#include "ui/views/paint_info.h"
#include "ui/views/view.h"
namespace views::test {
SkBitmap PaintViewToBitmap(View* view) {
SkBitmap bitmap;
{
gfx::Size size = view->size();
ui::CanvasPainter canvas_painter(&bitmap, size, 1.f, gfx::kPlaceholderColor,
false);
view->Paint(PaintInfo::CreateRootPaintInfo(canvas_painter.context(), size));
}
return bitmap;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_drawing_test_utils.cc | C++ | unknown | 769 |
// 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_TEST_VIEWS_DRAWING_TEST_UTILS_H_
#define UI_VIEWS_TEST_VIEWS_DRAWING_TEST_UTILS_H_
class SkBitmap;
namespace views {
class View;
namespace test {
// Paints the provided View and all its children to an SkBitmap, exactly like
// the view would be painted in actual use. This includes antialiasing of text,
// graphical effects, hover state, focus rings, and so on.
SkBitmap PaintViewToBitmap(View* view);
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_DRAWING_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_drawing_test_utils.h | C++ | unknown | 666 |
// 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/test/views_test_base.h"
#include <utility>
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "mojo/core/embedder/embedder.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gl/test/gl_surface_test_support.h"
#include "ui/views/buildflags.h"
#include "ui/views/test/test_platform_native_widget.h"
#include "ui/views/view_test_api.h"
#if defined(USE_AURA)
#include "ui/views/widget/native_widget_aura.h"
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif
#elif BUILDFLAG(IS_MAC)
#include "ui/views/widget/native_widget_mac.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_gl_egl_utility.h"
#endif
namespace views {
namespace {
bool DoesVisualHaveAlphaForTest() {
#if BUILDFLAG(IS_OZONE)
const auto* const egl_utility =
ui::OzonePlatform::GetInstance()->GetPlatformGLEGLUtility();
return egl_utility ? egl_utility->X11DoesVisualHaveAlphaForTest() : false;
#else
return false;
#endif
}
} // namespace
void ViewsTestBase::WidgetCloser::operator()(Widget* widget) const {
widget->CloseNow();
}
ViewsTestBase::ViewsTestBase(
std::unique_ptr<base::test::TaskEnvironment> task_environment)
: task_environment_(std::move(task_environment)) {}
ViewsTestBase::~ViewsTestBase() {
CHECK(setup_called_)
<< "You have overridden SetUp but never called super class's SetUp";
CHECK(teardown_called_)
<< "You have overridden TearDown but never called super class's TearDown";
}
void ViewsTestBase::SetUp() {
has_compositing_manager_ = DoesVisualHaveAlphaForTest();
testing::Test::SetUp();
setup_called_ = true;
absl::optional<ViewsDelegate::NativeWidgetFactory> factory;
if (native_widget_type_ == NativeWidgetType::kDesktop) {
factory = base::BindRepeating(&ViewsTestBase::CreateNativeWidgetForTest,
base::Unretained(this));
}
test_helper_ = std::make_unique<ScopedViewsTestHelper>(
std::move(views_delegate_for_setup_), std::move(factory));
}
void ViewsTestBase::TearDown() {
if (interactive_setup_called_)
ui::ResourceBundle::CleanupSharedInstance();
ui::Clipboard::DestroyClipboardForCurrentThread();
// Flush the message loop because we have pending release tasks
// and these tasks if un-executed would upset Valgrind.
RunPendingMessages();
teardown_called_ = true;
testing::Test::TearDown();
test_helper_.reset();
}
void ViewsTestBase::SetUpForInteractiveTests() {
DCHECK(!setup_called_);
interactive_setup_called_ = true;
// Mojo is initialized here similar to how each browser test case initializes
// Mojo when starting. This only works because each interactive_ui_test runs
// in a new process.
mojo::core::Init();
gl::GLSurfaceTestSupport::InitializeOneOff();
ui::RegisterPathProvider();
base::FilePath ui_test_pak_path;
ASSERT_TRUE(base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
}
void ViewsTestBase::RunPendingMessages() {
base::RunLoop run_loop;
run_loop.RunUntilIdle();
}
Widget::InitParams ViewsTestBase::CreateParams(Widget::InitParams::Type type) {
Widget::InitParams params(type);
params.context = GetContext();
return params;
}
std::unique_ptr<Widget> ViewsTestBase::CreateTestWidget(
Widget::InitParams::Type type) {
return CreateTestWidget(CreateParamsForTestWidget(type));
}
std::unique_ptr<Widget> ViewsTestBase::CreateTestWidget(
Widget::InitParams params) {
std::unique_ptr<Widget> widget = AllocateTestWidget();
widget->Init(std::move(params));
return widget;
}
bool ViewsTestBase::HasCompositingManager() const {
return has_compositing_manager_;
}
void ViewsTestBase::SimulateNativeDestroy(Widget* widget) {
test_helper_->SimulateNativeDestroy(widget);
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
void ViewsTestBase::SimulateDesktopNativeDestroy(Widget* widget) {
test_helper_->SimulateDesktopNativeDestroy(widget);
}
#endif
#if !BUILDFLAG(IS_MAC)
int ViewsTestBase::GetSystemReservedHeightAtTopOfScreen() {
return 0;
}
#endif
gfx::NativeWindow ViewsTestBase::GetContext() {
return test_helper_->GetContext();
}
NativeWidget* ViewsTestBase::CreateNativeWidgetForTest(
const Widget::InitParams& init_params,
internal::NativeWidgetDelegate* delegate) {
#if BUILDFLAG(IS_MAC)
return new test::TestPlatformNativeWidget<NativeWidgetMac>(delegate, false,
nullptr);
#elif defined(USE_AURA)
// For widgets that have a modal parent, don't force a native widget type.
// This logic matches DesktopTestViewsDelegate as well as ChromeViewsDelegate.
if (init_params.parent && init_params.type != Widget::InitParams::TYPE_MENU &&
init_params.type != Widget::InitParams::TYPE_TOOLTIP) {
// Returning null results in using the platform default, which is
// NativeWidgetAura.
return nullptr;
}
if (native_widget_type_ == NativeWidgetType::kDesktop) {
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
return new test::TestPlatformNativeWidget<DesktopNativeWidgetAura>(
delegate, false, nullptr);
#else
return new test::TestPlatformNativeWidget<NativeWidgetAura>(delegate, false,
nullptr);
#endif
}
return new test::TestPlatformNativeWidget<NativeWidgetAura>(delegate, true,
nullptr);
#else
NOTREACHED_NORETURN();
#endif
}
std::unique_ptr<Widget> ViewsTestBase::AllocateTestWidget() {
return std::make_unique<Widget>();
}
Widget::InitParams ViewsTestBase::CreateParamsForTestWidget(
Widget::InitParams::Type type) {
Widget::InitParams params = CreateParams(type);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 400, 400);
return params;
}
void ViewsTestWithDesktopNativeWidget::SetUp() {
set_native_widget_type(NativeWidgetType::kDesktop);
ViewsTestBase::SetUp();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_base.cc | C++ | unknown | 6,487 |
// 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_TEST_VIEWS_TEST_BASE_H_
#define UI_VIEWS_TEST_VIEWS_TEST_BASE_H_
#include <memory>
#include <utility>
#include "base/compiler_specific.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/ui_base_features.h"
#include "ui/views/test/scoped_views_test_helper.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/scoped_ole_initializer.h"
#endif
#if defined(USE_AURA)
#include "ui/aura/test/aura_test_helper.h"
#include "ui/aura/window_tree_host.h"
#endif
namespace views {
// A base class for views unit test. It creates a message loop necessary
// to drive UI events and takes care of OLE initialization for windows.
class ViewsTestBase : public PlatformTest {
public:
enum class NativeWidgetType {
// On Aura, corresponds to NativeWidgetAura.
kDefault,
// On chromeos, corresponds to NativeWidgetAura (DesktopNativeWidgetAura
// is not used on ChromeOS).
kDesktop,
};
// This class can be used as a deleter for std::unique_ptr<Widget>
// to call function Widget::CloseNow automatically.
struct WidgetCloser {
void operator()(Widget* widget) const;
};
using WidgetAutoclosePtr = std::unique_ptr<Widget, WidgetCloser>;
// Constructs a ViewsTestBase with |traits| being forwarded to its
// TaskEnvironment. MainThreadType always defaults to UI and must not be
// specified.
template <typename... TaskEnvironmentTraits>
NOINLINE explicit ViewsTestBase(TaskEnvironmentTraits&&... traits)
: ViewsTestBase(std::make_unique<base::test::TaskEnvironment>(
base::test::TaskEnvironment::MainThreadType::UI,
std::forward<TaskEnvironmentTraits>(traits)...)) {}
// Alternatively a subclass may pass a TaskEnvironment directly.
explicit ViewsTestBase(
std::unique_ptr<base::test::TaskEnvironment> task_environment);
ViewsTestBase(const ViewsTestBase&) = delete;
ViewsTestBase& operator=(const ViewsTestBase&) = delete;
~ViewsTestBase() override;
// testing::Test:
void SetUp() override;
void TearDown() override;
// This copies some of the setup done in ViewsTestSuite, so it's only
// necessary for a ViewsTestBase that runs out of that test suite, such as in
// interactive ui tests.
void SetUpForInteractiveTests();
void RunPendingMessages();
// Returns CreateParams for a widget of type |type|. This is used by
// CreateParamsForTestWidget() and thus by CreateTestWidget(), and may also be
// used directly. The default implementation sets the context to
// GetContext().
virtual Widget::InitParams CreateParams(Widget::InitParams::Type type);
virtual std::unique_ptr<Widget> CreateTestWidget(
Widget::InitParams::Type type =
Widget::InitParams::TYPE_WINDOW_FRAMELESS);
virtual std::unique_ptr<Widget> CreateTestWidget(Widget::InitParams params);
bool HasCompositingManager() const;
// Simulate an OS-level destruction of the native window held by non-desktop
// |widget|.
void SimulateNativeDestroy(Widget* widget);
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// Simulate an OS-level destruction of the native window held by desktop
// |widget|.
void SimulateDesktopNativeDestroy(Widget* widget);
#endif
// Get the system reserved height at the top of the screen. On Mac, this
// includes the menu bar and title bar.
static int GetSystemReservedHeightAtTopOfScreen();
protected:
base::test::TaskEnvironment* task_environment() {
return task_environment_.get();
}
TestViewsDelegate* test_views_delegate() const {
return test_helper_->test_views_delegate();
}
void set_native_widget_type(NativeWidgetType native_widget_type) {
DCHECK(!setup_called_);
native_widget_type_ = native_widget_type;
}
void set_views_delegate(std::unique_ptr<TestViewsDelegate> views_delegate) {
DCHECK(!setup_called_);
views_delegate_for_setup_.swap(views_delegate);
}
#if defined(USE_AURA)
aura::Window* root_window() {
return aura::test::AuraTestHelper::GetInstance()->GetContext();
}
ui::EventSink* GetEventSink() { return host()->GetEventSink(); }
aura::WindowTreeHost* host() {
return aura::test::AuraTestHelper::GetInstance()->GetHost();
}
#endif
// Returns a context view. In aura builds, this will be the RootWindow.
gfx::NativeWindow GetContext();
// Factory for creating the native widget when |native_widget_type_| is set to
// kDesktop.
NativeWidget* CreateNativeWidgetForTest(
const Widget::InitParams& init_params,
internal::NativeWidgetDelegate* delegate);
// Instantiates a Widget for CreateTestWidget(), but does no other
// initialization. Overriding this allows subclasses to customize the Widget
// subclass returned from CreateTestWidget().
virtual std::unique_ptr<Widget> AllocateTestWidget();
// Constructs the params for CreateTestWidget().
Widget::InitParams CreateParamsForTestWidget(
Widget::InitParams::Type type =
Widget::InitParams::TYPE_WINDOW_FRAMELESS);
private:
std::unique_ptr<base::test::TaskEnvironment> task_environment_;
// Controls what type of widget will be created by default for a test (i.e.
// when creating a Widget and leaving InitParams::native_widget unspecified).
// kDefault will allow the system default to be used (typically
// NativeWidgetAura on Aura). kDesktop forces DesktopNativeWidgetAura on Aura.
// There are exceptions, such as for modal dialog widgets, for which this
// value is ignored.
NativeWidgetType native_widget_type_ = NativeWidgetType::kDefault;
std::unique_ptr<TestViewsDelegate> views_delegate_for_setup_;
std::unique_ptr<ScopedViewsTestHelper> test_helper_;
bool interactive_setup_called_ = false;
bool setup_called_ = false;
bool teardown_called_ = false;
bool has_compositing_manager_ = false;
#if BUILDFLAG(IS_WIN)
ui::ScopedOleInitializer ole_initializer_;
#endif
};
// A helper that makes it easier to declare basic views tests that want to test
// desktop native widgets. See |ViewsTestBase::native_widget_type_| and
// |ViewsTestBase::CreateNativeWidgetForTest|. In short, for Aura, this will
// result in most Widgets automatically being backed by a
// DesktopNativeWidgetAura. For Mac, it has no impact as a NativeWidgetMac is
// used either way.
class ViewsTestWithDesktopNativeWidget : public ViewsTestBase {
public:
using ViewsTestBase::ViewsTestBase;
ViewsTestWithDesktopNativeWidget(const ViewsTestWithDesktopNativeWidget&) =
delete;
ViewsTestWithDesktopNativeWidget& operator=(
const ViewsTestWithDesktopNativeWidget&) = delete;
~ViewsTestWithDesktopNativeWidget() override = default;
// ViewsTestBase:
void SetUp() override;
};
class ScopedAXModeSetter {
public:
explicit ScopedAXModeSetter(ui::AXMode new_mode) {
ui::AXPlatformNode::SetAXMode(new_mode);
}
~ScopedAXModeSetter() { ui::AXPlatformNode::SetAXMode(ui::AXMode::kNone); }
};
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_TEST_BASE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_base.h | C++ | unknown | 7,347 |
// 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/test/views_test_base.h"
#include <Cocoa/Cocoa.h>
namespace views {
int ViewsTestBase::GetSystemReservedHeightAtTopOfScreen() {
// Includes gap of 1 px b/w menu bar and title bar.
CGFloat menu_bar_height = NSHeight([[NSScreen mainScreen] frame]) -
[[NSScreen mainScreen] visibleFrame].origin.y -
NSHeight([[NSScreen mainScreen] visibleFrame]);
CGFloat title_bar_height =
NSHeight([NSWindow frameRectForContentRect:NSZeroRect
styleMask:NSWindowStyleMaskTitled]);
return menu_bar_height + title_bar_height;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_base_mac.mm | Objective-C++ | unknown | 805 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/views_test_helper.h"
#include "ui/views/test/test_views_delegate.h"
namespace views {
std::unique_ptr<TestViewsDelegate>
ViewsTestHelper::GetFallbackTestViewsDelegate() {
return std::make_unique<TestViewsDelegate>();
}
void ViewsTestHelper::SetUpTestViewsDelegate(
TestViewsDelegate* delegate,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory) {
if (factory.has_value())
delegate->set_native_widget_factory(factory.value());
}
void ViewsTestHelper::SetUp() {}
gfx::NativeWindow ViewsTestHelper::GetContext() {
return nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper.cc | C++ | unknown | 753 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_
#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_
#include <memory>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_delegate.h"
namespace views {
class TestViewsDelegate;
// A helper class owned by tests that performs platform specific initialization
// required for running tests.
class ViewsTestHelper {
public:
// Create a platform specific instance.
static std::unique_ptr<ViewsTestHelper> Create();
ViewsTestHelper(const ViewsTestHelper&) = delete;
ViewsTestHelper& operator=(const ViewsTestHelper&) = delete;
virtual ~ViewsTestHelper() = default;
// Returns the delegate to use if the test/owner does not create one.
virtual std::unique_ptr<TestViewsDelegate> GetFallbackTestViewsDelegate();
// Does any additional necessary setup of the provided |delegate|.
virtual void SetUpTestViewsDelegate(
TestViewsDelegate* delegate,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory);
// Does any additional necessary setup of this object or its members.
virtual void SetUp();
// Returns a context window, e.g. the Aura root window.
virtual gfx::NativeWindow GetContext();
protected:
ViewsTestHelper() = default;
};
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper.h | C++ | unknown | 1,499 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/views_test_helper_aura.h"
#include "base/check_op.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/aura/window.h"
#include "ui/views/test/test_views_delegate.h"
namespace views {
namespace {
ViewsTestHelperAura::AuraTestHelperFactory g_helper_factory = nullptr;
ViewsTestHelperAura::TestViewsDelegateFactory g_delegate_factory = nullptr;
} // namespace
// static
std::unique_ptr<ViewsTestHelper> ViewsTestHelper::Create() {
return std::make_unique<ViewsTestHelperAura>();
}
ViewsTestHelperAura::ViewsTestHelperAura() {
aura_test_helper_ = g_helper_factory
? (*g_helper_factory)()
: std::make_unique<aura::test::AuraTestHelper>();
}
#if DCHECK_IS_ON() && !BUILDFLAG(IS_CHROMEOS_ASH)
ViewsTestHelperAura::~ViewsTestHelperAura() {
// Ensure all Widgets (and Windows) are closed in unit tests.
//
// Most tests do not try to create desktop Aura Widgets, and on most platforms
// will thus create Widgets that are owned by the RootWindow. These will
// automatically be destroyed when the RootWindow is torn down (during
// destruction of the AuraTestHelper). However, on Mac there are only desktop
// widgets, so any unclosed widgets will remain unowned, holding a Compositor,
// and will cause UAFs if closed (e.g. by the test freeing a
// unique_ptr<Widget> with WIDGET_OWNS_NATIVE_WIDGET) after the ContextFactory
// is destroyed by our owner.
//
// So, although it shouldn't matter for this helper, check for unclosed
// windows to complain about faulty tests early.
//
// This is not done on ChromeOS, where depending on the AuraTestHelper
// subclass, the root window may be owned by the Shell and contain various
// automatically-created container Windows that are never destroyed until
// Shell deletion. In theory we could attempt to check whether remaining
// children were these sorts of things and not warn, but doing so while
// avoiding layering violations is challenging, and since this is just a
// convenience check anyway, skip it.
gfx::NativeWindow root_window = GetContext();
if (root_window) {
DCHECK(root_window->children().empty())
<< "Not all windows were closed:\n"
<< root_window->GetWindowHierarchy(0);
}
}
#else
ViewsTestHelperAura::~ViewsTestHelperAura() = default;
#endif
std::unique_ptr<TestViewsDelegate>
ViewsTestHelperAura::GetFallbackTestViewsDelegate() {
// The factory delegate takes priority over the parent default.
return g_delegate_factory ? (*g_delegate_factory)()
: ViewsTestHelper::GetFallbackTestViewsDelegate();
}
void ViewsTestHelperAura::SetUp() {
aura_test_helper_->SetUp();
}
gfx::NativeWindow ViewsTestHelperAura::GetContext() {
return aura_test_helper_->GetContext();
}
// static
void ViewsTestHelperAura::SetAuraTestHelperFactory(
AuraTestHelperFactory factory) {
DCHECK_NE(g_helper_factory == nullptr, factory == nullptr);
g_helper_factory = factory;
}
// static
void ViewsTestHelperAura::SetFallbackTestViewsDelegateFactory(
TestViewsDelegateFactory factory) {
DCHECK_NE(g_delegate_factory == nullptr, factory == nullptr);
g_delegate_factory = factory;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper_aura.cc | C++ | unknown | 3,428 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_
#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_
#include <memory>
#include "ui/aura/test/aura_test_helper.h"
#include "ui/views/test/views_test_helper.h"
namespace views {
class ViewsTestHelperAura : public ViewsTestHelper {
public:
using AuraTestHelperFactory =
std::unique_ptr<aura::test::AuraTestHelper> (*)();
using TestViewsDelegateFactory = std::unique_ptr<TestViewsDelegate> (*)();
ViewsTestHelperAura();
ViewsTestHelperAura(const ViewsTestHelperAura&) = delete;
ViewsTestHelperAura& operator=(const ViewsTestHelperAura&) = delete;
~ViewsTestHelperAura() override;
// ViewsTestHelper:
std::unique_ptr<TestViewsDelegate> GetFallbackTestViewsDelegate() override;
void SetUp() override;
gfx::NativeWindow GetContext() override;
// Provides a way for test bases to customize what test helper will be used
// for |aura_test_helper_|.
static void SetAuraTestHelperFactory(AuraTestHelperFactory factory);
// Provides a way for test helpers to customize what delegate will be used
// if one is not provided by the test/framework.
static void SetFallbackTestViewsDelegateFactory(
TestViewsDelegateFactory factory);
private:
std::unique_ptr<aura::test::AuraTestHelper> aura_test_helper_;
};
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper_aura.h | C++ | unknown | 1,512 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_
#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_
#include <memory>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/test/scoped_fake_full_keyboard_access.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/test/test_context_factories.h"
#include "ui/display/screen.h"
#include "ui/views/test/views_test_helper.h"
namespace ui::test {
class ScopedFakeNSWindowFocus;
class ScopedFakeNSWindowFullscreen;
} // namespace ui::test
namespace views {
class ViewsTestHelperMac : public ViewsTestHelper {
public:
ViewsTestHelperMac();
ViewsTestHelperMac(const ViewsTestHelperMac&) = delete;
ViewsTestHelperMac& operator=(const ViewsTestHelperMac&) = delete;
~ViewsTestHelperMac() override;
// ViewsTestHelper:
void SetUpTestViewsDelegate(
TestViewsDelegate* delegate,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory) override;
private:
ui::TestContextFactories context_factories_{false};
// Disable animations during tests.
ui::ScopedAnimationDurationScaleMode zero_duration_mode_{
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION};
// When using desktop widgets on Mac, window activation is asynchronous
// because the window server is involved. A window may also be deactivated by
// a test running in parallel, making it flaky. In non-interactive/sharded
// tests, |faked_focus_| is initialized, permitting a unit test to "fake" this
// activation, causing it to be synchronous and per-process instead.
std::unique_ptr<ui::test::ScopedFakeNSWindowFocus> faked_focus_;
// Toggling fullscreen mode on Mac can be flaky for tests run in parallel
// because only one window may be animating into or out of fullscreen at a
// time. In non-interactive/sharded tests, |faked_fullscreen_| is initialized,
// permitting a unit test to 'fake' toggling fullscreen mode.
std::unique_ptr<ui::test::ScopedFakeNSWindowFullscreen> faked_fullscreen_;
// Enable fake full keyboard access by default, so that tests don't depend on
// system setting of the test machine. Also, this helps to make tests on Mac
// more consistent with other platforms, where most views are focusable by
// default.
ui::test::ScopedFakeFullKeyboardAccess faked_full_keyboard_access_;
display::ScopedNativeScreen screen_;
};
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper_mac.h | C++ | unknown | 2,602 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/views_test_helper_mac.h"
#import <Cocoa/Cocoa.h>
#include "base/functional/bind.h"
#include "ui/base/test/scoped_fake_nswindow_focus.h"
#include "ui/base/test/scoped_fake_nswindow_fullscreen.h"
#include "ui/base/test/ui_controls.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/test/event_generator_delegate_mac.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/widget/widget.h"
namespace views {
// static
std::unique_ptr<ViewsTestHelper> ViewsTestHelper::Create() {
return std::make_unique<ViewsTestHelperMac>();
}
ViewsTestHelperMac::ViewsTestHelperMac() {
// Unbundled applications (those without Info.plist) default to
// NSApplicationActivationPolicyProhibited, which prohibits the application
// obtaining key status or activating windows without user interaction.
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
ui::test::EventGeneratorDelegate::SetFactoryFunction(
base::BindRepeating(&test::CreateEventGeneratorDelegateMac));
// Assume that if the methods in the ui_controls.h test header are enabled
// then the test runner is in a non-sharded mode, and will use "real"
// activations and fullscreen mode. This allows interactive_ui_tests to test
// the actual OS window activation and fullscreen codepaths.
if (!ui_controls::IsUIControlsEnabled()) {
faked_focus_ = std::make_unique<ui::test::ScopedFakeNSWindowFocus>();
faked_fullscreen_ =
std::make_unique<ui::test::ScopedFakeNSWindowFullscreen>();
}
}
ViewsTestHelperMac::~ViewsTestHelperMac() {
// Ensure all Widgets are closed explicitly in tests. The Widget may be
// hosting a Compositor. If that's torn down after the test ContextFactory
// then a lot of confusing use-after-free errors result. In browser tests,
// this is handled automatically by views::Widget::CloseAllSecondaryWidgets().
// Unit tests on Aura may create Widgets owned by a RootWindow that gets torn
// down, but on Mac we need to be more explicit.
@autoreleasepool {
NSArray* native_windows = [NSApp windows];
for (NSWindow* window : native_windows)
DCHECK(!Widget::GetWidgetForNativeWindow(window)) << "Widget not closed.";
ui::test::EventGeneratorDelegate::SetFactoryFunction(
ui::test::EventGeneratorDelegate::FactoryFunction());
}
}
void ViewsTestHelperMac::SetUpTestViewsDelegate(
TestViewsDelegate* delegate,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory) {
ViewsTestHelper::SetUpTestViewsDelegate(delegate, std::move(factory));
delegate->set_context_factory(context_factories_.GetContextFactory());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_helper_mac.mm | Objective-C++ | unknown | 2,816 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/views_test_utils.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views::test {
void RunScheduledLayout(Widget* widget) {
DCHECK(widget);
widget->LayoutRootViewIfNecessary();
}
void RunScheduledLayout(View* view) {
DCHECK(view);
Widget* widget = view->GetWidget();
if (widget) {
RunScheduledLayout(widget);
return;
}
View* parent_view = view;
while (parent_view->parent())
parent_view = parent_view->parent();
if (parent_view->needs_layout())
parent_view->Layout();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_utils.cc | C++ | unknown | 730 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_VIEWS_TEST_UTILS_H_
#define UI_VIEWS_TEST_VIEWS_TEST_UTILS_H_
namespace views {
class View;
class Widget;
namespace test {
// Ensure that the entire Widget root view is properly laid out. This will
// call Widget::LayoutRootViewIfNecessary().
void RunScheduledLayout(Widget* widget);
// Ensure the given view is properly laid out. If the view is in a Widget view
// tree, invoke RunScheduledLayout(widget). Otherwise lay out the
// root parent view.
void RunScheduledLayout(View* view);
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_VIEWS_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/views_test_utils.h | C++ | unknown | 748 |
// 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/test/webview_test_helper.h"
#include "content/public/test/test_content_client_initializer.h"
#include "ui/views/controls/webview/webview.h"
namespace views {
WebViewTestHelper::WebViewTestHelper() {
test_content_client_initializer_ =
std::make_unique<content::TestContentClientInitializer>();
// Setup to register a new RenderViewHost factory which manufactures
// mock render process hosts. This ensures that we never create a 'real'
// render view host since support for it doesn't exist in unit tests.
test_content_client_initializer_->CreateTestRenderViewHosts();
}
WebViewTestHelper::~WebViewTestHelper() = default;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/webview_test_helper.cc | C++ | unknown | 828 |
// 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_TEST_WEBVIEW_TEST_HELPER_H_
#define UI_VIEWS_TEST_WEBVIEW_TEST_HELPER_H_
#include <memory>
namespace content {
class TestContentClientInitializer;
} // namespace content
namespace views {
class WebViewTestHelper {
public:
WebViewTestHelper();
WebViewTestHelper(const WebViewTestHelper&) = delete;
WebViewTestHelper& operator=(const WebViewTestHelper&) = delete;
virtual ~WebViewTestHelper();
private:
std::unique_ptr<content::TestContentClientInitializer>
test_content_client_initializer_;
};
} // namespace views
#endif // UI_VIEWS_TEST_WEBVIEW_TEST_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/webview_test_helper.h | C++ | unknown | 752 |
// 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/test/widget_animation_waiter.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_delegate.h"
#include "ui/compositor/layer_animator.h"
#include "ui/views/widget/widget.h"
namespace views {
WidgetAnimationWaiter::WidgetAnimationWaiter(Widget* widget) : widget_(widget) {
widget->GetLayer()->GetAnimator()->AddObserver(this);
}
WidgetAnimationWaiter::WidgetAnimationWaiter(Widget* widget,
const gfx::Rect& target_bounds)
: target_bounds_(target_bounds), widget_(widget) {
widget->GetLayer()->GetAnimator()->AddObserver(this);
}
WidgetAnimationWaiter::~WidgetAnimationWaiter() {
widget_->GetLayer()->GetAnimator()->RemoveObserver(this);
}
void WidgetAnimationWaiter::OnLayerAnimationEnded(
ui::LayerAnimationSequence* sequence) {
if (!widget_->GetLayer()->GetAnimator()->is_animating() &&
animation_scheduled_) {
if (!target_bounds_.IsEmpty()) {
EXPECT_EQ(widget_->GetWindowBoundsInScreen(), target_bounds_);
EXPECT_EQ(widget_->GetLayer()->transform(), gfx::Transform());
}
is_valid_animation_ = true;
widget_->GetLayer()->GetAnimator()->RemoveObserver(this);
run_loop_.Quit();
}
}
void WidgetAnimationWaiter::OnLayerAnimationAborted(
ui::LayerAnimationSequence* sequence) {}
void WidgetAnimationWaiter::OnLayerAnimationScheduled(
ui::LayerAnimationSequence* sequence) {
animation_scheduled_ = true;
if (!target_bounds_.IsEmpty())
EXPECT_NE(widget_->GetLayer()->transform(), gfx::Transform());
}
void WidgetAnimationWaiter::WaitForAnimation() {
run_loop_.Run();
}
bool WidgetAnimationWaiter::WasValidAnimation() {
return animation_scheduled_ && is_valid_animation_;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_animation_waiter.cc | C++ | unknown | 1,954 |
// 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_TEST_WIDGET_ANIMATION_WAITER_H_
#define UI_VIEWS_TEST_WIDGET_ANIMATION_WAITER_H_
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "ui/compositor/layer_animation_observer.h"
namespace gfx {
class Rect;
}
namespace views {
class Widget;
// Class which waits until for a widget to finish animating and verifies
// that the layer transform animation was valid.
class WidgetAnimationWaiter : ui::LayerAnimationObserver {
public:
explicit WidgetAnimationWaiter(Widget* widget);
WidgetAnimationWaiter(Widget* widget, const gfx::Rect& target_bounds);
~WidgetAnimationWaiter() override;
// ui::LayerAnimationObserver:
void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override;
void OnLayerAnimationScheduled(ui::LayerAnimationSequence* sequence) override;
void WaitForAnimation();
// Returns true if the animation has completed.
bool WasValidAnimation();
private:
gfx::Rect target_bounds_;
// Unowned
const raw_ptr<Widget, DanglingUntriaged> widget_;
base::RunLoop run_loop_;
bool is_valid_animation_ = false;
bool animation_scheduled_ = false;
};
} // namespace views
#endif // UI_VIEWS_TEST_WIDGET_ANIMATION_WAITER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_animation_waiter.h | C++ | unknown | 1,433 |
// 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/test/widget_test.h"
#include "base/rand_util.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/widget/root_view.h"
#if BUILDFLAG(IS_MAC)
#include "base/test/scoped_run_loop_timeout.h"
#include "base/test/test_timeouts.h"
#endif
#if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
#include "ui/views/test/test_desktop_screen_ozone.h"
#endif
namespace views::test {
namespace {
View::Views ShuffledChildren(View* view) {
View::Views children(view->children());
base::RandomShuffle(children.begin(), children.end());
return children;
}
} // namespace
View* AnyViewMatchingPredicate(View* view, const ViewPredicate& predicate) {
if (predicate.Run(view))
return view;
// Note that we randomize the order of the children, to avoid this function
// always choosing the same View to return out of a set of possible Views.
// If we didn't do this, client code could accidentally depend on a specific
// search order.
for (auto* child : ShuffledChildren(view)) {
auto* found = AnyViewMatchingPredicate(child, predicate);
if (found)
return found;
}
return nullptr;
}
View* AnyViewMatchingPredicate(Widget* widget, const ViewPredicate& predicate) {
return AnyViewMatchingPredicate(widget->GetRootView(), predicate);
}
View* AnyViewWithClassName(Widget* widget, const std::string& classname) {
return AnyViewMatchingPredicate(widget, [&](const View* view) {
return view->GetClassName() == classname;
});
}
WidgetTest::WidgetTest() = default;
WidgetTest::WidgetTest(
std::unique_ptr<base::test::TaskEnvironment> task_environment)
: ViewsTestBase(std::move(task_environment)) {}
WidgetTest::~WidgetTest() = default;
Widget* WidgetTest::CreateTopLevelPlatformWidget() {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget =
CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
widget->Init(std::move(params));
return widget;
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
Widget* WidgetTest::CreateTopLevelPlatformDesktopWidget() {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget = CreatePlatformDesktopNativeWidgetImpl(
widget, kStubCapture, base::DoNothing());
widget->Init(std::move(params));
return widget;
}
#endif
Widget* WidgetTest::CreateTopLevelFramelessPlatformWidget() {
Widget* widget = new Widget;
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.native_widget =
CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
widget->Init(std::move(params));
return widget;
}
Widget* WidgetTest::CreateChildPlatformWidget(
gfx::NativeView parent_native_view) {
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_CONTROL);
params.parent = parent_native_view;
Widget* child = new Widget;
params.native_widget =
CreatePlatformNativeWidgetImpl(child, kStubCapture, nullptr);
child->Init(std::move(params));
child->SetContentsView(std::make_unique<View>());
return child;
}
Widget* WidgetTest::CreateTopLevelNativeWidget() {
Widget* toplevel = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
toplevel->Init(std::move(params));
return toplevel;
}
Widget* WidgetTest::CreateChildNativeWidgetWithParent(Widget* parent) {
Widget* child = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_CONTROL);
params.parent = parent->GetNativeView();
child->Init(std::move(params));
child->SetContentsView(std::make_unique<View>());
return child;
}
View* WidgetTest::GetMousePressedHandler(views::internal::RootView* root_view) {
return root_view->mouse_pressed_handler_;
}
View* WidgetTest::GetMouseMoveHandler(views::internal::RootView* root_view) {
return root_view->mouse_move_handler_;
}
View* WidgetTest::GetGestureHandler(views::internal::RootView* root_view) {
return root_view->gesture_handler_;
}
DesktopWidgetTest::DesktopWidgetTest() = default;
DesktopWidgetTest::~DesktopWidgetTest() = default;
void DesktopWidgetTest::SetUp() {
set_native_widget_type(NativeWidgetType::kDesktop);
WidgetTest::SetUp();
}
DesktopWidgetTestInteractive::DesktopWidgetTestInteractive() = default;
DesktopWidgetTestInteractive::~DesktopWidgetTestInteractive() = default;
void DesktopWidgetTestInteractive::SetUp() {
SetUpForInteractiveTests();
#if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
screen_ = views::test::TestDesktopScreenOzone::Create();
#endif
DesktopWidgetTest::SetUp();
}
#if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
void DesktopWidgetTestInteractive::TearDown() {
DesktopWidgetTest::TearDown();
screen_.reset();
}
#endif
TestDesktopWidgetDelegate::TestDesktopWidgetDelegate()
: TestDesktopWidgetDelegate(nullptr) {}
TestDesktopWidgetDelegate::TestDesktopWidgetDelegate(Widget* widget)
: widget_(widget ? widget : new Widget) {
SetFocusTraversesOut(true);
}
TestDesktopWidgetDelegate::~TestDesktopWidgetDelegate() {
if (widget_)
widget_->CloseNow();
EXPECT_FALSE(widget_);
}
void TestDesktopWidgetDelegate::InitWidget(Widget::InitParams init_params) {
init_params.delegate = this;
init_params.bounds = initial_bounds_;
widget_->Init(std::move(init_params));
}
void TestDesktopWidgetDelegate::WindowClosing() {
window_closing_count_++;
widget_ = nullptr;
}
Widget* TestDesktopWidgetDelegate::GetWidget() {
return widget_;
}
const Widget* TestDesktopWidgetDelegate::GetWidget() const {
return widget_;
}
View* TestDesktopWidgetDelegate::GetContentsView() {
return contents_view_ ? contents_view_.get()
: WidgetDelegate::GetContentsView();
}
bool TestDesktopWidgetDelegate::OnCloseRequested(
Widget::ClosedReason close_reason) {
last_closed_reason_ = close_reason;
return can_close_;
}
TestInitialFocusWidgetDelegate::TestInitialFocusWidgetDelegate(
gfx::NativeWindow context)
: view_(new View) {
view_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.context = context;
params.delegate = this;
GetWidget()->Init(std::move(params));
GetWidget()->GetContentsView()->AddChildView(view_.get());
}
TestInitialFocusWidgetDelegate::~TestInitialFocusWidgetDelegate() = default;
View* TestInitialFocusWidgetDelegate::GetInitiallyFocusedView() {
return view_;
}
WidgetActivationWaiter::WidgetActivationWaiter(Widget* widget, bool active)
: active_(active) {
if (active == widget->IsActive()) {
observed_ = true;
return;
}
widget_observation_.Observe(widget);
}
WidgetActivationWaiter::~WidgetActivationWaiter() = default;
void WidgetActivationWaiter::Wait() {
if (!observed_) {
#if BUILDFLAG(IS_MAC)
// Some tests waiting on widget creation + activation are flaky due to
// timeout. crbug.com/1327590.
const base::test::ScopedRunLoopTimeout increased_run_timeout(
FROM_HERE, TestTimeouts::action_max_timeout());
#endif
run_loop_.Run();
}
}
void WidgetActivationWaiter::OnWidgetActivationChanged(Widget* widget,
bool active) {
if (active_ != active)
return;
observed_ = true;
widget_observation_.Reset();
if (run_loop_.running())
run_loop_.Quit();
}
WidgetDestroyedWaiter::WidgetDestroyedWaiter(Widget* widget) {
widget_observation_.Observe(widget);
}
WidgetDestroyedWaiter::~WidgetDestroyedWaiter() = default;
void WidgetDestroyedWaiter::Wait() {
run_loop_.Run();
}
void WidgetDestroyedWaiter::OnWidgetDestroyed(Widget* widget) {
widget_observation_.Reset();
run_loop_.Quit();
}
WidgetVisibleWaiter::WidgetVisibleWaiter(Widget* widget) : widget_(widget) {}
WidgetVisibleWaiter::~WidgetVisibleWaiter() = default;
void WidgetVisibleWaiter::Wait() {
if (!widget_->IsVisible()) {
widget_observation_.Observe(widget_.get());
run_loop_.Run();
}
}
void WidgetVisibleWaiter::OnWidgetVisibilityChanged(Widget* widget,
bool visible) {
DCHECK_EQ(widget_, widget);
if (visible) {
DCHECK(widget_observation_.IsObservingSource(widget));
widget_observation_.Reset();
run_loop_.Quit();
}
}
void WidgetVisibleWaiter::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(widget_, widget);
ADD_FAILURE() << "Widget destroying before it became visible!";
// Even though the test failed, be polite and remove the observer so we
// don't crash with a UAF in the destructor.
DCHECK(widget_observation_.IsObservingSource(widget));
widget_observation_.Reset();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test.cc | C++ | unknown | 9,165 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_WIDGET_TEST_H_
#define UI_VIEWS_TEST_WIDGET_TEST_H_
#include <memory>
#include <string>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "build/chromecast_buildflags.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
#if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
#include "ui/display/screen.h"
#endif
namespace ui {
class EventSink;
class ImeKeyEventDispatcher;
} // namespace ui
namespace views {
class View;
class Widget;
namespace internal {
class RootView;
} // namespace internal
namespace test {
// These functions return an arbitrary view v such that:
//
// 1) v is a descendant of the root view of the provided widget, and
// 2) predicate.Run(v) returned true
//
// They are *not* guaranteed to return first child matching the predicate for
// any specific ordering of the children. In fact, these methods deliberately
// randomly choose a child to return, so make sure your predicate matches
// *only* the view you want!
using ViewPredicate = base::RepeatingCallback<bool(const View*)>;
View* AnyViewMatchingPredicate(View* root, const ViewPredicate& predicate);
template <typename Pred>
View* AnyViewMatchingPredicate(View* root, Pred predicate) {
return AnyViewMatchingPredicate(root, base::BindLambdaForTesting(predicate));
}
View* AnyViewMatchingPredicate(Widget* widget, const ViewPredicate& predicate);
template <typename Pred>
View* AnyViewMatchingPredicate(Widget* widget, Pred predicate) {
return AnyViewMatchingPredicate(widget,
base::BindLambdaForTesting(predicate));
}
View* AnyViewWithClassName(Widget* widget, const std::string& classname);
class WidgetTest : public ViewsTestBase {
public:
WidgetTest();
explicit WidgetTest(
std::unique_ptr<base::test::TaskEnvironment> task_environment);
WidgetTest(const WidgetTest&) = delete;
WidgetTest& operator=(const WidgetTest&) = delete;
~WidgetTest() override;
// Create Widgets with |native_widget| in InitParams set to an instance of
// platform specific widget type that has stubbled capture calls. This will
// create a non-desktop widget.
Widget* CreateTopLevelPlatformWidget();
Widget* CreateTopLevelFramelessPlatformWidget();
Widget* CreateChildPlatformWidget(gfx::NativeView parent_native_view);
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// Create Widgets with |native_widget| in InitParams set to an instance of
// platform specific widget type that has stubbled capture calls. This will
// create a desktop widget.
Widget* CreateTopLevelPlatformDesktopWidget();
#endif
// Create Widgets initialized without a |native_widget| set in InitParams.
// Depending on the test environment, ViewsDelegate::OnBeforeWidgetInit() may
// provide a desktop or non-desktop NativeWidget.
Widget* CreateTopLevelNativeWidget();
Widget* CreateChildNativeWidgetWithParent(Widget* parent);
View* GetMousePressedHandler(views::internal::RootView* root_view);
View* GetMouseMoveHandler(views::internal::RootView* root_view);
View* GetGestureHandler(views::internal::RootView* root_view);
// Simulate an activation of the native window held by |widget|, as if it was
// clicked by the user. This is a synchronous method for use in
// non-interactive tests that do not spin a RunLoop in the test body (since
// that may cause real focus changes to flakily manifest).
static void SimulateNativeActivate(Widget* widget);
// Return true if |window| is visible according to the native platform.
static bool IsNativeWindowVisible(gfx::NativeWindow window);
// Return true if |above| is higher than |below| in the native window Z-order.
// Both windows must be visible.
// WARNING: this does not work for Aura desktop widgets (crbug.com/1333445)
// and is not reliable on MacOS 10.13 and earlier.
static bool IsWindowStackedAbove(Widget* above, Widget* below);
// Query the native window system for the minimum size configured for user
// initiated window resizes.
gfx::Size GetNativeWidgetMinimumContentSize(Widget* widget);
// Return the event sink for |widget|. On aura platforms, this is an
// aura::WindowEventDispatcher. Otherwise, it is a bridge to the OS event
// sink.
static ui::EventSink* GetEventSink(Widget* widget);
// Get the ImeKeyEventDispatcher, for setting on a Mock InputMethod in tests.
static ui::ImeKeyEventDispatcher* GetImeKeyEventDispatcherForWidget(
Widget* widget);
// Return true if |window| is transparent according to the native platform.
static bool IsNativeWindowTransparent(gfx::NativeWindow window);
// Returns whether |widget| has a Window shadow managed in this process. That
// is, a shadow that is drawn outside of the Widget bounds, and managed by the
// WindowManager.
static bool WidgetHasInProcessShadow(Widget* widget);
// Returns the set of all Widgets that currently have a NativeWindow.
static Widget::Widgets GetAllWidgets();
// Waits for system app activation events, if any, to have happened. This is
// necessary on macOS 10.15+, where the system will attempt to find and
// activate a window owned by the app shortly after app startup, if there is
// one. See https://crbug.com/998868 for details.
static void WaitForSystemAppActivation();
};
class DesktopWidgetTest : public WidgetTest {
public:
DesktopWidgetTest();
DesktopWidgetTest(const DesktopWidgetTest&) = delete;
DesktopWidgetTest& operator=(const DesktopWidgetTest&) = delete;
~DesktopWidgetTest() override;
// WidgetTest:
void SetUp() override;
};
class DesktopWidgetTestInteractive : public DesktopWidgetTest {
public:
DesktopWidgetTestInteractive();
DesktopWidgetTestInteractive(const DesktopWidgetTestInteractive&) = delete;
DesktopWidgetTestInteractive& operator=(const DesktopWidgetTestInteractive&) =
delete;
~DesktopWidgetTestInteractive() override;
// DesktopWidgetTest
void SetUp() override;
#if (BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CASTOS)) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
void TearDown() override;
std::unique_ptr<display::Screen> screen_;
#endif
};
// A helper WidgetDelegate for tests that require hooks into WidgetDelegate
// calls, and removes some of the boilerplate for initializing a Widget. Calls
// Widget::CloseNow() when destroyed if it hasn't already been done.
class TestDesktopWidgetDelegate : public WidgetDelegate {
public:
TestDesktopWidgetDelegate();
explicit TestDesktopWidgetDelegate(Widget* widget);
TestDesktopWidgetDelegate(const TestDesktopWidgetDelegate&) = delete;
TestDesktopWidgetDelegate& operator=(const TestDesktopWidgetDelegate&) =
delete;
~TestDesktopWidgetDelegate() override;
// Initialize the Widget, adding some meaningful default InitParams.
void InitWidget(Widget::InitParams init_params);
// Set the contents view to be used during Widget initialization. For Widgets
// that use non-client views, this will be the contents_view used to
// initialize the ClientView in WidgetDelegate::CreateClientView(). Otherwise,
// it is the ContentsView of the Widget's RootView. Ownership passes to the
// view hierarchy during InitWidget().
void set_contents_view(View* contents_view) {
contents_view_ = contents_view;
}
// Sets the return value for CloseRequested().
void set_can_close(bool can_close) { can_close_ = can_close; }
int window_closing_count() const { return window_closing_count_; }
const gfx::Rect& initial_bounds() { return initial_bounds_; }
Widget::ClosedReason last_closed_reason() const {
return last_closed_reason_;
}
bool can_close() const { return can_close_; }
// WidgetDelegate:
void WindowClosing() override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
View* GetContentsView() override;
bool OnCloseRequested(Widget::ClosedReason close_reason) override;
private:
raw_ptr<Widget> widget_;
raw_ptr<View> contents_view_ = nullptr;
int window_closing_count_ = 0;
gfx::Rect initial_bounds_ = gfx::Rect(100, 100, 200, 200);
bool can_close_ = true;
Widget::ClosedReason last_closed_reason_ = Widget::ClosedReason::kUnspecified;
};
// Testing widget delegate that creates a widget with a single view, which is
// the initially focused view.
class TestInitialFocusWidgetDelegate : public TestDesktopWidgetDelegate {
public:
explicit TestInitialFocusWidgetDelegate(gfx::NativeWindow context);
TestInitialFocusWidgetDelegate(const TestInitialFocusWidgetDelegate&) =
delete;
TestInitialFocusWidgetDelegate& operator=(
const TestInitialFocusWidgetDelegate&) = delete;
~TestInitialFocusWidgetDelegate() override;
View* view() { return view_; }
// WidgetDelegate override:
View* GetInitiallyFocusedView() override;
private:
raw_ptr<View> view_;
};
// Use in tests to wait until a Widget's activation change to a particular
// value. To use create and call Wait().
class WidgetActivationWaiter : public WidgetObserver {
public:
WidgetActivationWaiter(Widget* widget, bool active);
WidgetActivationWaiter(const WidgetActivationWaiter&) = delete;
WidgetActivationWaiter& operator=(const WidgetActivationWaiter&) = delete;
~WidgetActivationWaiter() override;
// Returns when the active status matches that supplied to the constructor. If
// the active status does not match that of the constructor a RunLoop is used
// until the active status matches, otherwise this returns immediately.
void Wait();
private:
// views::WidgetObserver override:
void OnWidgetActivationChanged(Widget* widget, bool active) override;
bool observed_ = false;
bool active_;
base::RunLoop run_loop_;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
};
// Use in tests to wait for a widget to be destroyed.
class WidgetDestroyedWaiter : public WidgetObserver {
public:
explicit WidgetDestroyedWaiter(Widget* widget);
WidgetDestroyedWaiter(const WidgetDestroyedWaiter&) = delete;
WidgetDestroyedWaiter& operator=(const WidgetDestroyedWaiter&) = delete;
~WidgetDestroyedWaiter() override;
// Wait for the widget to be destroyed, or return immediately if it was
// already destroyed since this object was created.
void Wait();
private:
// views::WidgetObserver
void OnWidgetDestroyed(Widget* widget) override;
base::RunLoop run_loop_;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
};
// Helper class to wait for a Widget to become visible. This will add a failure
// to the currently-running test if the widget is destroyed before becoming
// visible.
class WidgetVisibleWaiter : public WidgetObserver {
public:
explicit WidgetVisibleWaiter(Widget* widget);
WidgetVisibleWaiter(const WidgetVisibleWaiter&) = delete;
WidgetVisibleWaiter& operator=(const WidgetVisibleWaiter&) = delete;
~WidgetVisibleWaiter() override;
// Waits for the widget to become visible.
void Wait();
private:
// WidgetObserver:
void OnWidgetVisibilityChanged(Widget* widget, bool visible) override;
void OnWidgetDestroying(Widget* widget) override;
const raw_ptr<Widget, DanglingUntriaged> widget_;
base::RunLoop run_loop_;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_WIDGET_TEST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test.h | C++ | unknown | 11,764 |
// 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/test/widget_test_api.h"
#include "ui/views/widget/widget.h"
namespace views {
void DisableActivationChangeHandlingForTests() {
Widget::SetDisableActivationChangeHandling(
Widget::DisableActivationChangeHandlingType::kIgnore);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test_api.cc | C++ | unknown | 425 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_WIDGET_TEST_API_H_
#define UI_VIEWS_TEST_WIDGET_TEST_API_H_
namespace views {
// Makes Widget::OnNativeWidgetActivationChanged return false, which prevents
// handling of the corresponding event (if the native widget implementation
// takes this into account).
void DisableActivationChangeHandlingForTests();
} // namespace views
#endif // UI_VIEWS_TEST_WIDGET_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test_api.h | C++ | unknown | 545 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/widget_test.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/test/aura_test_helper.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tree_host.h"
#include "ui/compositor/layer.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/shadow_controller.h"
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#endif
namespace views::test {
namespace {
// Perform a pre-order traversal of |children| and all descendants, looking for
// |first| and |second|. If |first| is found before |second|, return true.
// When a layer is found, it is set to null. Returns once |second| is found, or
// when there are no children left.
// Note that ui::Layer children are bottom-to-top stacking order.
bool FindLayersInOrder(const std::vector<ui::Layer*>& children,
const ui::Layer** first,
const ui::Layer** second) {
for (const ui::Layer* child : children) {
if (child == *second) {
*second = nullptr;
return *first == nullptr;
}
if (child == *first)
*first = nullptr;
if (FindLayersInOrder(child->children(), first, second))
return true;
// If second is cleared without success, exit early with failure.
if (!*second)
return false;
}
return false;
}
#if BUILDFLAG(IS_WIN)
struct FindAllWindowsData {
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #reinterpret-cast-trivial-type
RAW_PTR_EXCLUSION std::vector<aura::Window*>* windows;
};
BOOL CALLBACK FindAllWindowsCallback(HWND hwnd, LPARAM param) {
FindAllWindowsData* data = reinterpret_cast<FindAllWindowsData*>(param);
if (aura::WindowTreeHost* host =
aura::WindowTreeHost::GetForAcceleratedWidget(hwnd))
data->windows->push_back(host->window());
return TRUE;
}
#endif // BUILDFLAG(IS_WIN)
std::vector<aura::Window*> GetAllTopLevelWindows() {
std::vector<aura::Window*> roots;
#if BUILDFLAG(IS_WIN)
{
FindAllWindowsData data = {&roots};
EnumThreadWindows(GetCurrentThreadId(), FindAllWindowsCallback,
reinterpret_cast<LPARAM>(&data));
}
#elif BUILDFLAG(ENABLE_DESKTOP_AURA)
roots = DesktopWindowTreeHostPlatform::GetAllOpenWindows();
#endif
aura::test::AuraTestHelper* aura_test_helper =
aura::test::AuraTestHelper::GetInstance();
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Chrome OS browser tests must use ash::Shell::GetAllRootWindows.
DCHECK(aura_test_helper) << "Can't find all widgets without a test helper";
#endif
if (aura_test_helper)
roots.push_back(aura_test_helper->GetContext());
return roots;
}
} // namespace
// static
void WidgetTest::SimulateNativeActivate(Widget* widget) {
gfx::NativeView native_view = widget->GetNativeView();
aura::client::GetFocusClient(native_view)->FocusWindow(native_view);
}
// static
bool WidgetTest::IsNativeWindowVisible(gfx::NativeWindow window) {
return window->IsVisible();
}
// static
bool WidgetTest::IsWindowStackedAbove(Widget* above, Widget* below) {
EXPECT_TRUE(above->IsVisible());
EXPECT_TRUE(below->IsVisible());
ui::Layer* root_layer = above->GetNativeWindow()->GetRootWindow()->layer();
// Traversal is bottom-to-top, so |below| should be found first.
const ui::Layer* first = below->GetLayer();
const ui::Layer* second = above->GetLayer();
return FindLayersInOrder(root_layer->children(), &first, &second);
}
gfx::Size WidgetTest::GetNativeWidgetMinimumContentSize(Widget* widget) {
// On Windows, HWNDMessageHandler receives a WM_GETMINMAXINFO message whenever
// the window manager is interested in knowing the size constraints. On
// ChromeOS, it's handled internally. Elsewhere, the size constraints need to
// be pushed to the window server when they change.
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN)
return widget->GetNativeWindow()->delegate()->GetMinimumSize();
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
return widget->GetNativeWindow()->delegate()->GetMinimumSize();
#else
NOTREACHED_NORETURN();
#endif
}
// static
ui::EventSink* WidgetTest::GetEventSink(Widget* widget) {
return widget->GetNativeWindow()->GetHost()->GetEventSink();
}
// static
ui::ImeKeyEventDispatcher* WidgetTest::GetImeKeyEventDispatcherForWidget(
Widget* widget) {
return widget->GetNativeWindow()->GetRootWindow()->GetHost();
}
// static
bool WidgetTest::IsNativeWindowTransparent(gfx::NativeWindow window) {
return window->GetTransparent();
}
// static
bool WidgetTest::WidgetHasInProcessShadow(Widget* widget) {
aura::Window* window = widget->GetNativeWindow();
if (wm::ShadowController::GetShadowForWindow(window))
return true;
// If the Widget's native window is the content window for a
// DesktopWindowTreeHost, then giving the root window a shadow also has the
// effect of drawing a shadow around the window.
if (window->parent() == window->GetRootWindow())
return wm::ShadowController::GetShadowForWindow(window->GetRootWindow());
return false;
}
// static
Widget::Widgets WidgetTest::GetAllWidgets() {
Widget::Widgets all_widgets;
for (aura::Window* window : GetAllTopLevelWindows())
Widget::GetAllChildWidgets(window->GetRootWindow(), &all_widgets);
return all_widgets;
}
// static
void WidgetTest::WaitForSystemAppActivation() {}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test_aura.cc | C++ | unknown | 5,821 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/widget_test.h"
#include <Cocoa/Cocoa.h>
#include "base/mac/mac_util.h"
#import "base/mac/scoped_nsobject.h"
#import "base/mac/scoped_objc_class_swizzler.h"
#import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#import "ui/base/test/windowed_nsnotification_observer.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/native_widget_mac.h"
#include "ui/views/widget/root_view.h"
namespace views::test {
namespace {
// The NSWindow last activated by SimulateNativeActivate(). It will have a
// simulated deactivate on a subsequent call.
NSWindow* g_simulated_active_window_ = nil;
} // namespace
// static
void WidgetTest::SimulateNativeActivate(Widget* widget) {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
if (g_simulated_active_window_) {
[center postNotificationName:NSWindowDidResignKeyNotification
object:g_simulated_active_window_];
}
g_simulated_active_window_ = widget->GetNativeWindow().GetNativeNSWindow();
DCHECK(g_simulated_active_window_);
// For now, don't simulate main status or windows that can't activate.
DCHECK([g_simulated_active_window_ canBecomeKeyWindow]);
[center postNotificationName:NSWindowDidBecomeKeyNotification
object:g_simulated_active_window_];
}
// static
bool WidgetTest::IsNativeWindowVisible(gfx::NativeWindow window) {
return [window.GetNativeNSWindow() isVisible];
}
// static
bool WidgetTest::IsWindowStackedAbove(Widget* above, Widget* below) {
// Since 10.13, a trip to the runloop has been necessary to ensure [NSApp
// orderedWindows] has been updated.
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(above->IsVisible());
EXPECT_TRUE(below->IsVisible());
// -[NSApplication orderedWindows] are ordered front-to-back.
NSWindow* first = above->GetNativeWindow().GetNativeNSWindow();
NSWindow* second = below->GetNativeWindow().GetNativeNSWindow();
for (NSWindow* window in [NSApp orderedWindows]) {
if (window == second)
return !first;
if (window == first)
first = nil;
}
return false;
}
gfx::Size WidgetTest::GetNativeWidgetMinimumContentSize(Widget* widget) {
return gfx::Size(
[widget->GetNativeWindow().GetNativeNSWindow() contentMinSize]);
}
// static
ui::EventSink* WidgetTest::GetEventSink(Widget* widget) {
return static_cast<internal::RootView*>(widget->GetRootView());
}
// static
ui::ImeKeyEventDispatcher* WidgetTest::GetImeKeyEventDispatcherForWidget(
Widget* widget) {
return NativeWidgetMacNSWindowHost::GetFromNativeWindow(
widget->GetNativeWindow())
->native_widget_mac();
}
// static
bool WidgetTest::IsNativeWindowTransparent(gfx::NativeWindow window) {
return ![window.GetNativeNSWindow() isOpaque];
}
// static
bool WidgetTest::WidgetHasInProcessShadow(Widget* widget) {
return false;
}
// static
Widget::Widgets WidgetTest::GetAllWidgets() {
Widget::Widgets all_widgets;
for (NSWindow* window : [NSApp windows]) {
if (Widget* widget = Widget::GetWidgetForNativeWindow(window))
all_widgets.insert(widget);
}
return all_widgets;
}
// static
void WidgetTest::WaitForSystemAppActivation() {
if (base::mac::IsAtMostOS10_14())
return;
// This seems to be only necessary on 10.15+ but it's obscure why. Shortly
// after launching an app, the system sends ApplicationDidFinishLaunching
// (which is normal), which causes AppKit on 10.15 to try to find a window to
// activate. If it finds one it will makeKeyAndOrderFront: it, which breaks
// tests that are deliberately creating inactive windows.
base::scoped_nsobject<WindowedNSNotificationObserver> observer(
[[WindowedNSNotificationObserver alloc]
initForNotification:NSApplicationDidFinishLaunchingNotification
object:NSApp]);
[observer wait];
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test_mac.mm | Objective-C++ | unknown | 4,088 |
// 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/test/widget_test.h"
#include <vector>
#include "base/ranges/algorithm.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace views::test {
namespace {
// Insert |widget| into |expected| and ensure it's reported by GetAllWidgets().
void ExpectAdd(Widget::Widgets* expected, Widget* widget, const char* message) {
SCOPED_TRACE(message);
EXPECT_TRUE(expected->insert(widget).second);
EXPECT_TRUE(base::ranges::equal(*expected, WidgetTest::GetAllWidgets()));
}
// Close |widgets[0]|, and expect all |widgets| to be removed.
void ExpectClose(Widget::Widgets* expected,
std::vector<Widget*> widgets,
const char* message) {
SCOPED_TRACE(message);
for (Widget* widget : widgets)
EXPECT_EQ(1u, expected->erase(widget));
widgets[0]->CloseNow();
EXPECT_TRUE(base::ranges::equal(*expected, WidgetTest::GetAllWidgets()));
}
} // namespace
using WidgetTestTest = WidgetTest;
// Ensure that Widgets with various root windows are correctly reported by
// WidgetTest::GetAllWidgets().
TEST_F(WidgetTestTest, GetAllWidgets) {
// Note Widget::Widgets is a std::set ordered by pointer value, so the order
// that |expected| is updated below is not important.
Widget::Widgets expected;
EXPECT_EQ(expected, GetAllWidgets());
Widget* platform = CreateTopLevelPlatformWidget();
ExpectAdd(&expected, platform, "platform");
Widget* platform_child = CreateChildPlatformWidget(platform->GetNativeView());
ExpectAdd(&expected, platform_child, "platform_child");
Widget* frameless = CreateTopLevelFramelessPlatformWidget();
ExpectAdd(&expected, frameless, "frameless");
Widget* native = CreateTopLevelNativeWidget();
ExpectAdd(&expected, native, "native");
Widget* native_child = CreateChildNativeWidgetWithParent(native);
ExpectAdd(&expected, native_child, "native_child");
ExpectClose(&expected, {native, native_child}, "native");
ExpectClose(&expected, {platform, platform_child}, "platform");
ExpectClose(&expected, {frameless}, "frameless");
}
using DesktopWidgetTestTest = DesktopWidgetTest;
// As above, but with desktop native widgets (i.e. DesktopNativeWidgetAura on
// Aura).
TEST_F(DesktopWidgetTestTest, GetAllWidgets) {
// Note Widget::Widgets is a std::set ordered by pointer value, so the order
// that |expected| is updated below is not important.
Widget::Widgets expected;
EXPECT_EQ(expected, GetAllWidgets());
Widget* frameless = CreateTopLevelFramelessPlatformWidget();
ExpectAdd(&expected, frameless, "frameless");
Widget* native = CreateTopLevelNativeWidget();
ExpectAdd(&expected, native, "native");
Widget* native_child = CreateChildNativeWidgetWithParent(native);
ExpectAdd(&expected, native_child, "native_child");
Widget* desktop = CreateTopLevelNativeWidget();
ExpectAdd(&expected, desktop, "desktop");
Widget* desktop_child = CreateChildNativeWidgetWithParent(desktop);
ExpectAdd(&expected, desktop_child, "desktop_child");
#if defined(USE_AURA)
// A DesktopWindowTreeHost has both a root aura::Window and a content window.
// DesktopWindowTreeHostX11::GetAllOpenWindows() returns content windows, so
// ensure that a Widget parented to the root window is also found.
Widget* desktop_cousin =
CreateChildPlatformWidget(desktop->GetNativeView()->GetRootWindow());
ExpectAdd(&expected, desktop_cousin, "desktop_cousin");
ExpectClose(&expected, {desktop_cousin}, "desktop_cousin");
#endif // USE_AURA
ExpectClose(&expected, {desktop, desktop_child}, "desktop");
ExpectClose(&expected, {native, native_child}, "native");
ExpectClose(&expected, {frameless}, "frameless");
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/widget_test_unittest.cc | C++ | unknown | 3,887 |
// 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/touchui/touch_selection_controller_impl.h"
#include <set>
#include <utility>
#include "base/check_op.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/time/time.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_targeter.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/wm/core/coordinate_conversion.h"
namespace {
// Constants defining the visual attributes of selection handles
// The distance by which a handle image is offset from the bottom of the
// selection/text baseline.
constexpr int kSelectionHandleVerticalVisualOffset = 2;
// When a handle is dragged, the drag position reported to the client view is
// offset vertically to represent the cursor position. This constant specifies
// the offset in pixels above the bottom of the selection (see pic below). This
// is required because say if this is zero, that means the drag position we
// report is right on the text baseline. In that case, a vertical movement of
// even one pixel will make the handle jump to the line below it. So when the
// user just starts dragging, the handle will jump to the next line if the user
// makes any vertical movement. So we have this non-zero offset to prevent this
// jumping.
//
// Editing handle widget showing the padding and difference between the position
// of the ET_GESTURE_SCROLL_UPDATE event and the drag position reported to the
// client:
// ___________
// Selection Highlight --->_____|__|<-|---- Drag position reported to client
// _ | O |
// Vertical Padding __| | <-|---- ET_GESTURE_SCROLL_UPDATE position
// |_ |_____|<--- Editing handle widget
//
// | |
// T
// Horizontal Padding
//
constexpr int kSelectionHandleVerticalDragOffset = 5;
// Padding around the selection handle defining the area that will be included
// in the touch target to make dragging the handle easier (see pic above).
constexpr int kSelectionHandleHorizPadding = 10;
constexpr int kSelectionHandleVertPadding = 20;
// Minimum height for selection handle bar. If the bar height is going to be
// less than this value, handle will not be shown.
constexpr int kSelectionHandleBarMinHeight = 5;
// Maximum amount that selection handle bar can stick out of client view's
// boundaries.
constexpr int kSelectionHandleBarBottomAllowance = 3;
// Delay before showing the quick menu after it is requested, in milliseconds.
const int kQuickMenuDelayInMs = 200;
gfx::Image* GetCenterHandleImage() {
static gfx::Image* handle_image = nullptr;
if (!handle_image) {
handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_TEXT_SELECTION_HANDLE_CENTER);
}
return handle_image;
}
gfx::Image* GetLeftHandleImage() {
static gfx::Image* handle_image = nullptr;
if (!handle_image) {
handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_TEXT_SELECTION_HANDLE_LEFT);
}
return handle_image;
}
gfx::Image* GetRightHandleImage() {
static gfx::Image* handle_image = nullptr;
if (!handle_image) {
handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_TEXT_SELECTION_HANDLE_RIGHT);
}
return handle_image;
}
// Return the appropriate handle image based on the bound's type
gfx::Image* GetHandleImage(gfx::SelectionBound::Type bound_type) {
switch (bound_type) {
case gfx::SelectionBound::LEFT:
return GetLeftHandleImage();
case gfx::SelectionBound::CENTER:
return GetCenterHandleImage();
case gfx::SelectionBound::RIGHT:
return GetRightHandleImage();
default:
NOTREACHED_NORETURN()
<< "Invalid touch handle bound type: " << bound_type;
}
}
// Calculates the bounds of the widget containing the selection handle based
// on the SelectionBound's type and location.
gfx::Rect GetSelectionWidgetBounds(const gfx::SelectionBound& bound) {
gfx::Size image_size = GetHandleImage(bound.type())->Size();
int widget_width = image_size.width() + 2 * kSelectionHandleHorizPadding;
// Extend the widget height to handle touch events below the painted image.
int widget_height = bound.GetHeight() + image_size.height() +
kSelectionHandleVerticalVisualOffset +
kSelectionHandleVertPadding;
// Due to the shape of the handle images, the widget is aligned differently to
// the selection bound depending on the type of the bound.
int widget_left = 0;
switch (bound.type()) {
case gfx::SelectionBound::LEFT:
widget_left = bound.edge_start_rounded().x() - image_size.width() -
kSelectionHandleHorizPadding;
break;
case gfx::SelectionBound::RIGHT:
widget_left =
bound.edge_start_rounded().x() - kSelectionHandleHorizPadding;
break;
case gfx::SelectionBound::CENTER:
widget_left = bound.edge_start_rounded().x() - widget_width / 2;
break;
default:
NOTREACHED_NORETURN() << "Undefined bound type.";
}
return gfx::Rect(widget_left, bound.edge_start_rounded().y(), widget_width,
widget_height);
}
gfx::Size GetMaxHandleImageSize() {
gfx::Rect center_rect = gfx::Rect(GetCenterHandleImage()->Size());
gfx::Rect left_rect = gfx::Rect(GetLeftHandleImage()->Size());
gfx::Rect right_rect = gfx::Rect(GetRightHandleImage()->Size());
gfx::Rect union_rect = center_rect;
union_rect.Union(left_rect);
union_rect.Union(right_rect);
return union_rect.size();
}
// Convenience methods to convert a |bound| from screen to the |client|'s
// coordinate system and vice versa.
// Note that this is not quite correct because it does not take into account
// transforms such as rotation and scaling. This should be in TouchEditable.
// TODO(varunjain): Fix this.
gfx::SelectionBound ConvertFromScreen(ui::TouchEditable* client,
const gfx::SelectionBound& bound) {
gfx::SelectionBound result = bound;
gfx::Point edge_end = bound.edge_end_rounded();
gfx::Point edge_start = bound.edge_start_rounded();
client->ConvertPointFromScreen(&edge_end);
client->ConvertPointFromScreen(&edge_start);
result.SetEdge(gfx::PointF(edge_start), gfx::PointF(edge_end));
return result;
}
gfx::SelectionBound ConvertToScreen(ui::TouchEditable* client,
const gfx::SelectionBound& bound) {
gfx::SelectionBound result = bound;
gfx::Point edge_end = bound.edge_end_rounded();
gfx::Point edge_start = bound.edge_start_rounded();
client->ConvertPointToScreen(&edge_end);
client->ConvertPointToScreen(&edge_start);
result.SetEdge(gfx::PointF(edge_start), gfx::PointF(edge_end));
return result;
}
gfx::Rect BoundToRect(const gfx::SelectionBound& bound) {
return gfx::BoundingRect(bound.edge_start_rounded(),
bound.edge_end_rounded());
}
} // namespace
namespace views {
using EditingHandleView = TouchSelectionControllerImpl::EditingHandleView;
// A View that displays the text selection handle.
class TouchSelectionControllerImpl::EditingHandleView : public View {
public:
METADATA_HEADER(EditingHandleView);
EditingHandleView(TouchSelectionControllerImpl* controller,
gfx::NativeView parent,
bool is_cursor_handle)
: controller_(controller),
image_(GetCenterHandleImage()),
is_cursor_handle_(is_cursor_handle),
widget_(new views::Widget) {
// Create a widget to host EditingHandleView.
views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
params.shadow_type = views::Widget::InitParams::ShadowType::kNone;
params.parent = parent;
widget_->Init(std::move(params));
widget_->GetNativeWindow()->SetEventTargeter(
std::make_unique<aura::WindowTargeter>());
widget_->SetContentsView(this);
}
EditingHandleView(const EditingHandleView&) = delete;
EditingHandleView& operator=(const EditingHandleView&) = delete;
~EditingHandleView() override = default;
void CloseHandleWidget() {
SetWidgetVisible(false);
widget_->CloseNow();
}
gfx::SelectionBound::Type GetSelectionBoundType() const {
return selection_bound_.type();
}
// View:
void OnPaint(gfx::Canvas* canvas) override {
// Draw the handle image.
canvas->DrawImageInt(
*image_->ToImageSkia(), kSelectionHandleHorizPadding,
selection_bound_.GetHeight() + kSelectionHandleVerticalVisualOffset);
}
void OnGestureEvent(ui::GestureEvent* event) override {
event->SetHandled();
switch (event->type()) {
case ui::ET_GESTURE_TAP:
if (is_cursor_handle_) {
controller_->ToggleQuickMenu();
}
break;
case ui::ET_GESTURE_SCROLL_BEGIN: {
widget_->SetCapture(this);
controller_->OnDragBegin(this);
// Distance from the point which is |kSelectionHandleVerticalDragOffset|
// pixels above the bottom of the selection bound edge to the event
// location (aka the touch-drag point).
drag_offset_ = selection_bound_.edge_end_rounded() -
gfx::Vector2d(0, kSelectionHandleVerticalDragOffset) -
event->location();
break;
}
case ui::ET_GESTURE_SCROLL_UPDATE: {
controller_->OnDragUpdate(event->location() + drag_offset_);
break;
}
case ui::ET_GESTURE_SCROLL_END:
case ui::ET_SCROLL_FLING_START: {
widget_->ReleaseCapture();
controller_->OnDragEnd();
break;
}
default:
break;
}
}
gfx::Size CalculatePreferredSize() const override {
// This function will be called during widget initialization, i.e. before
// SetBoundInScreen has been called. No-op in that case.
if (selection_bound_.type() == gfx::SelectionBound::EMPTY)
return gfx::Size();
return GetSelectionWidgetBounds(selection_bound_).size();
}
bool GetWidgetVisible() const { return widget_->IsVisible(); }
void SetWidgetVisible(bool visible) {
if (widget_->IsVisible() == visible)
return;
if (visible)
widget_->Show();
else
widget_->Hide();
OnPropertyChanged(&widget_, kPropertyEffectsNone);
}
// If |is_visible| is true, this will update the widget and trigger a repaint
// if necessary. Otherwise this will only update the internal state:
// |selection_bound_| and |image_|, so that the state is valid for the time
// this becomes visible.
void SetBoundInScreen(const gfx::SelectionBound& bound, bool is_visible) {
bool update_bound_type = false;
// Cursor handle should always have the bound type CENTER
DCHECK(!is_cursor_handle_ || bound.type() == gfx::SelectionBound::CENTER);
if (bound.type() != selection_bound_.type()) {
// Unless this is a cursor handle, do not set the type to CENTER -
// selection handles corresponding to a selection should always use left
// or right handle image. If selection handles are dragged to be located
// at the same spot, the |bound|'s type here will be CENTER for both of
// them. In this case do not update the type of the |selection_bound_|.
if (bound.type() != gfx::SelectionBound::CENTER || is_cursor_handle_)
update_bound_type = true;
}
if (update_bound_type) {
selection_bound_.set_type(bound.type());
image_ = GetHandleImage(bound.type());
if (is_visible)
SchedulePaint();
}
if (is_visible) {
selection_bound_.SetEdge(bound.edge_start(), bound.edge_end());
widget_->SetBounds(GetSelectionWidgetBounds(selection_bound_));
aura::Window* window = widget_->GetNativeView();
gfx::Point edge_start = selection_bound_.edge_start_rounded();
gfx::Point edge_end = selection_bound_.edge_end_rounded();
wm::ConvertPointFromScreen(window, &edge_start);
wm::ConvertPointFromScreen(window, &edge_end);
selection_bound_.SetEdge(gfx::PointF(edge_start), gfx::PointF(edge_end));
}
const auto insets = gfx::Insets::TLBR(
selection_bound_.GetHeight() + kSelectionHandleVerticalVisualOffset, 0,
0, 0);
// Shifts the hit-test target below the apparent bounds to make dragging
// easier.
widget_->GetNativeWindow()->targeter()->SetInsets(insets, insets);
}
private:
raw_ptr<TouchSelectionControllerImpl> controller_;
// In local coordinates
gfx::SelectionBound selection_bound_;
raw_ptr<gfx::Image> image_;
// If true, this is a handle corresponding to the single cursor, otherwise it
// is a handle corresponding to one of the two selection bounds.
bool is_cursor_handle_;
// Offset applied to the scroll events location when calling
// TouchSelectionControllerImpl::OnDragUpdate while dragging the handle.
gfx::Vector2d drag_offset_;
// Owning widget.
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Widget* widget_ = nullptr;
};
BEGIN_METADATA(TouchSelectionControllerImpl, EditingHandleView, View)
ADD_READONLY_PROPERTY_METADATA(gfx::SelectionBound::Type, SelectionBoundType)
ADD_PROPERTY_METADATA(bool, WidgetVisible)
END_METADATA
TouchSelectionControllerImpl::TouchSelectionControllerImpl(
ui::TouchEditable* client_view)
: client_view_(client_view),
selection_handle_1_(
new EditingHandleView(this, client_view->GetNativeView(), false)),
selection_handle_2_(
new EditingHandleView(this, client_view->GetNativeView(), false)),
cursor_handle_(
new EditingHandleView(this, client_view->GetNativeView(), true)) {
selection_start_time_ = base::TimeTicks::Now();
aura::Window* client_window = client_view_->GetNativeView();
client_widget_ = Widget::GetTopLevelWidgetForNativeView(client_window);
// Observe client widget moves and resizes to update the selection handles.
if (client_widget_)
client_widget_->AddObserver(this);
// Observe certain event types sent to any event target, to hide this ui.
aura::Env* env = aura::Env::GetInstance();
std::set<ui::EventType> types = {ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_MOVED,
ui::ET_KEY_PRESSED, ui::ET_MOUSEWHEEL};
env->AddEventObserver(this, env, types);
toggle_menu_enabled_ = ::features::IsTouchTextEditingRedesignEnabled();
}
TouchSelectionControllerImpl::~TouchSelectionControllerImpl() {
UMA_HISTOGRAM_BOOLEAN("Event.TouchSelection.EndedWithAction",
command_executed_);
HideQuickMenu();
aura::Env::GetInstance()->RemoveEventObserver(this);
if (client_widget_)
client_widget_->RemoveObserver(this);
// Close the owning Widgets to clean up the EditingHandleViews.
selection_handle_1_->CloseHandleWidget();
selection_handle_2_->CloseHandleWidget();
cursor_handle_->CloseHandleWidget();
CHECK(!IsInObserverList());
}
void TouchSelectionControllerImpl::SelectionChanged() {
gfx::SelectionBound anchor, focus;
client_view_->GetSelectionEndPoints(&anchor, &focus);
gfx::SelectionBound screen_bound_anchor =
ConvertToScreen(client_view_, anchor);
gfx::SelectionBound screen_bound_focus = ConvertToScreen(client_view_, focus);
gfx::Rect client_bounds = client_view_->GetBounds();
if (anchor.edge_start().y() < client_bounds.y()) {
auto anchor_edge_start = gfx::PointF(anchor.edge_start_rounded());
anchor_edge_start.set_y(client_bounds.y());
anchor.SetEdgeStart(anchor_edge_start);
}
if (focus.edge_start().y() < client_bounds.y()) {
auto focus_edge_start = gfx::PointF(focus.edge_start_rounded());
focus_edge_start.set_y(client_bounds.y());
focus.SetEdgeStart(focus_edge_start);
}
gfx::SelectionBound screen_bound_anchor_clipped =
ConvertToScreen(client_view_, anchor);
gfx::SelectionBound screen_bound_focus_clipped =
ConvertToScreen(client_view_, focus);
if (screen_bound_anchor_clipped == selection_bound_1_clipped_ &&
screen_bound_focus_clipped == selection_bound_2_clipped_)
return;
selection_bound_1_ = screen_bound_anchor;
selection_bound_2_ = screen_bound_focus;
selection_bound_1_clipped_ = screen_bound_anchor_clipped;
selection_bound_2_clipped_ = screen_bound_focus_clipped;
if (dragging_handle_) {
// We need to reposition only the selection handle that is being dragged.
// The other handle stays the same. Also, the selection handle being dragged
// will always be at the end of selection, while the other handle will be at
// the start.
// If the new location of this handle is out of client view, its widget
// should not get hidden, since it should still receive touch events.
// Hence, we are not using |SetHandleBound()| method here.
dragging_handle_->SetBoundInScreen(screen_bound_focus_clipped, true);
if (dragging_handle_ != cursor_handle_) {
// The non-dragging-handle might have recently become visible.
EditingHandleView* non_dragging_handle = selection_handle_1_;
if (dragging_handle_ == selection_handle_1_) {
non_dragging_handle = selection_handle_2_;
// if handle 1 is being dragged, it is corresponding to the end of
// selection and the other handle to the start of selection.
selection_bound_1_ = screen_bound_focus;
selection_bound_2_ = screen_bound_anchor;
selection_bound_1_clipped_ = screen_bound_focus_clipped;
selection_bound_2_clipped_ = screen_bound_anchor_clipped;
}
SetHandleBound(non_dragging_handle, anchor, screen_bound_anchor_clipped);
}
} else {
if (screen_bound_anchor.edge_start() == screen_bound_focus.edge_start() &&
screen_bound_anchor.edge_end() == screen_bound_focus.edge_end()) {
// Empty selection, show cursor handle.
selection_handle_1_->SetWidgetVisible(false);
selection_handle_2_->SetWidgetVisible(false);
SetHandleBound(cursor_handle_, anchor, screen_bound_anchor_clipped);
quick_menu_requested_ = !toggle_menu_enabled_;
} else {
// Non-empty selection, show selection handles.
cursor_handle_->SetWidgetVisible(false);
SetHandleBound(selection_handle_1_, anchor, screen_bound_anchor_clipped);
SetHandleBound(selection_handle_2_, focus, screen_bound_focus_clipped);
quick_menu_requested_ = true;
}
UpdateQuickMenu();
}
}
void TouchSelectionControllerImpl::ToggleQuickMenu() {
if (toggle_menu_enabled_) {
quick_menu_requested_ = !quick_menu_requested_;
UpdateQuickMenu();
}
}
void TouchSelectionControllerImpl::ShowQuickMenuImmediatelyForTesting() {
if (quick_menu_timer_.IsRunning()) {
quick_menu_timer_.Stop();
QuickMenuTimerFired();
}
}
void TouchSelectionControllerImpl::OnDragBegin(EditingHandleView* handle) {
dragging_handle_ = handle;
UpdateQuickMenu();
if (dragging_handle_ == cursor_handle_) {
return;
}
DCHECK(dragging_handle_ == selection_handle_1_ ||
dragging_handle_ == selection_handle_2_);
// Find selection end points in client_view's coordinate system.
gfx::Point base = selection_bound_1_.edge_start_rounded();
base.Offset(0, selection_bound_1_.GetHeight() / 2);
client_view_->ConvertPointFromScreen(&base);
gfx::Point extent = selection_bound_2_.edge_start_rounded();
extent.Offset(0, selection_bound_2_.GetHeight() / 2);
client_view_->ConvertPointFromScreen(&extent);
if (dragging_handle_ == selection_handle_1_) {
std::swap(base, extent);
}
// When moving the handle we want to move only the extent point. Before
// doing so we must make sure that the base point is set correctly.
client_view_->SelectBetweenCoordinates(base, extent);
}
void TouchSelectionControllerImpl::OnDragUpdate(const gfx::Point& drag_pos) {
DCHECK(dragging_handle_);
gfx::Point drag_pos_in_client = drag_pos;
ConvertPointToClientView(dragging_handle_, &drag_pos_in_client);
if (dragging_handle_ == cursor_handle_) {
client_view_->MoveCaret(drag_pos_in_client);
return;
}
DCHECK(dragging_handle_ == selection_handle_1_ ||
dragging_handle_ == selection_handle_2_);
client_view_->MoveRangeSelectionExtent(drag_pos_in_client);
}
void TouchSelectionControllerImpl::OnDragEnd() {
dragging_handle_ = nullptr;
UpdateQuickMenu();
}
void TouchSelectionControllerImpl::ConvertPointToClientView(
EditingHandleView* source,
gfx::Point* point) {
View::ConvertPointToScreen(source, point);
client_view_->ConvertPointFromScreen(point);
}
void TouchSelectionControllerImpl::SetHandleBound(
EditingHandleView* handle,
const gfx::SelectionBound& bound,
const gfx::SelectionBound& bound_in_screen) {
handle->SetWidgetVisible(ShouldShowHandleFor(bound));
handle->SetBoundInScreen(bound_in_screen, handle->GetWidgetVisible());
}
bool TouchSelectionControllerImpl::ShouldShowHandleFor(
const gfx::SelectionBound& bound) const {
if (bound.GetHeight() < kSelectionHandleBarMinHeight)
return false;
gfx::Rect client_bounds = client_view_->GetBounds();
client_bounds.Inset(
gfx::Insets::TLBR(0, 0, -kSelectionHandleBarBottomAllowance, 0));
return client_bounds.Contains(BoundToRect(bound));
}
bool TouchSelectionControllerImpl::IsCommandIdEnabled(int command_id) const {
return client_view_->IsCommandIdEnabled(command_id);
}
void TouchSelectionControllerImpl::ExecuteCommand(int command_id,
int event_flags) {
command_executed_ = true;
base::TimeDelta duration = base::TimeTicks::Now() - selection_start_time_;
// Note that we only log the duration stats for the 'successful' selections,
// i.e. selections ending with the execution of a command.
UMA_HISTOGRAM_CUSTOM_TIMES("Event.TouchSelection.Duration", duration,
base::Milliseconds(500), base::Seconds(60), 60);
client_view_->ExecuteCommand(command_id, event_flags);
}
void TouchSelectionControllerImpl::RunContextMenu() {
// Context menu should appear centered on top of the selected region.
const gfx::Rect rect = GetQuickMenuAnchorRect();
const gfx::Point anchor(rect.CenterPoint().x(), rect.y());
client_view_->OpenContextMenu(anchor);
}
bool TouchSelectionControllerImpl::ShouldShowQuickMenu() {
return false;
}
std::u16string TouchSelectionControllerImpl::GetSelectedText() {
return std::u16string();
}
void TouchSelectionControllerImpl::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(client_widget_, widget);
client_widget_->RemoveObserver(this);
client_widget_ = nullptr;
}
void TouchSelectionControllerImpl::OnWidgetBoundsChanged(
Widget* widget,
const gfx::Rect& new_bounds) {
DCHECK_EQ(client_widget_, widget);
SelectionChanged();
}
void TouchSelectionControllerImpl::OnEvent(const ui::Event& event) {
if (event.IsMouseEvent()) {
auto* cursor = aura::client::GetCursorClient(
client_view_->GetNativeView()->GetRootWindow());
if (cursor && !cursor->IsMouseEventsEnabled())
return;
// Windows OS unhandled WM_POINTER* may be redispatched as WM_MOUSE*.
// Avoid adjusting the handles on synthesized events or events generated
// from touch as this can clear an active selection generated by the pen.
if ((event.flags() & (int{ui::EF_IS_SYNTHESIZED} | ui::EF_FROM_TOUCH)) ||
event.AsMouseEvent()->pointer_details().pointer_type ==
ui::EventPointerType::kPen) {
return;
}
}
client_view_->DestroyTouchSelection();
}
void TouchSelectionControllerImpl::QuickMenuTimerFired() {
gfx::Rect menu_anchor = GetQuickMenuAnchorRect();
if (menu_anchor == gfx::Rect())
return;
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), menu_anchor, GetMaxHandleImageSize(),
client_view_->GetNativeView());
}
void TouchSelectionControllerImpl::StartQuickMenuTimer() {
if (quick_menu_timer_.IsRunning())
return;
quick_menu_timer_.Start(FROM_HERE, base::Milliseconds(kQuickMenuDelayInMs),
this,
&TouchSelectionControllerImpl::QuickMenuTimerFired);
}
void TouchSelectionControllerImpl::UpdateQuickMenu() {
HideQuickMenu();
if (quick_menu_requested_ && !dragging_handle_) {
StartQuickMenuTimer();
}
}
void TouchSelectionControllerImpl::HideQuickMenu() {
if (ui::TouchSelectionMenuRunner::GetInstance()->IsRunning())
ui::TouchSelectionMenuRunner::GetInstance()->CloseMenu();
quick_menu_timer_.Stop();
}
gfx::Rect TouchSelectionControllerImpl::GetQuickMenuAnchorRect() const {
// Get selection end points in client_view's space.
gfx::SelectionBound b1_in_screen = selection_bound_1_clipped_;
gfx::SelectionBound b2_in_screen = cursor_handle_->GetWidgetVisible()
? b1_in_screen
: selection_bound_2_clipped_;
// Convert from screen to client.
gfx::SelectionBound b1 = ConvertFromScreen(client_view_, b1_in_screen);
gfx::SelectionBound b2 = ConvertFromScreen(client_view_, b2_in_screen);
// if selection is completely inside the view, we display the quick menu in
// the middle of the end points on the top. Else, we show it above the visible
// handle. If no handle is visible, we do not show the menu.
gfx::Rect menu_anchor;
if (ShouldShowHandleFor(b1) && ShouldShowHandleFor(b2))
menu_anchor = gfx::RectBetweenSelectionBounds(b1_in_screen, b2_in_screen);
else if (ShouldShowHandleFor(b1))
menu_anchor = BoundToRect(b1_in_screen);
else if (ShouldShowHandleFor(b2))
menu_anchor = BoundToRect(b2_in_screen);
else
return menu_anchor;
// Enlarge the anchor rect so that the menu is offset from the text at least
// by the same distance the handles are offset from the text.
menu_anchor.Inset(gfx::Insets::VH(-kSelectionHandleVerticalVisualOffset, 0));
return menu_anchor;
}
gfx::NativeView TouchSelectionControllerImpl::GetCursorHandleNativeView() {
return cursor_handle_->GetWidget()->GetNativeView();
}
gfx::SelectionBound::Type
TouchSelectionControllerImpl::GetSelectionHandle1Type() {
return selection_handle_1_->GetSelectionBoundType();
}
gfx::Rect TouchSelectionControllerImpl::GetSelectionHandle1Bounds() {
return selection_handle_1_->GetBoundsInScreen();
}
gfx::Rect TouchSelectionControllerImpl::GetSelectionHandle2Bounds() {
return selection_handle_2_->GetBoundsInScreen();
}
gfx::Rect TouchSelectionControllerImpl::GetCursorHandleBounds() {
return cursor_handle_->GetBoundsInScreen();
}
bool TouchSelectionControllerImpl::IsSelectionHandle1Visible() {
return selection_handle_1_->GetWidgetVisible();
}
bool TouchSelectionControllerImpl::IsSelectionHandle2Visible() {
return selection_handle_2_->GetWidgetVisible();
}
bool TouchSelectionControllerImpl::IsCursorHandleVisible() {
return cursor_handle_->GetWidgetVisible();
}
gfx::Rect TouchSelectionControllerImpl::GetExpectedHandleBounds(
const gfx::SelectionBound& bound) {
return GetSelectionWidgetBounds(bound);
}
View* TouchSelectionControllerImpl::GetHandle1View() {
return selection_handle_1_;
}
View* TouchSelectionControllerImpl::GetHandle2View() {
return selection_handle_2_;
}
} // namespace views
DEFINE_ENUM_CONVERTERS(gfx::SelectionBound::Type,
{gfx::SelectionBound::Type::LEFT, u"LEFT"},
{gfx::SelectionBound::Type::RIGHT, u"RIGHT"},
{gfx::SelectionBound::Type::CENTER, u"CENTER"},
{gfx::SelectionBound::Type::EMPTY, u"EMPTY"})
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_controller_impl.cc | C++ | unknown | 28,451 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
#define UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "ui/base/pointer/touch_editing_controller.h"
#include "ui/events/event_observer.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/selection_bound.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
// Touch specific implementation of TouchEditingControllerDeprecated.
// Responsible for displaying selection handles and menu elements relevant in a
// touch interface.
class VIEWS_EXPORT TouchSelectionControllerImpl
: public ui::TouchEditingControllerDeprecated,
public ui::TouchSelectionMenuClient,
public WidgetObserver,
public ui::EventObserver {
public:
class EditingHandleView;
// Use ui::TouchEditingControllerFactory::Create() instead.
explicit TouchSelectionControllerImpl(ui::TouchEditable* client_view);
TouchSelectionControllerImpl(const TouchSelectionControllerImpl&) = delete;
TouchSelectionControllerImpl& operator=(const TouchSelectionControllerImpl&) =
delete;
~TouchSelectionControllerImpl() override;
// ui::TouchEditingControllerDeprecated:
void SelectionChanged() override;
void ToggleQuickMenu() override;
void ShowQuickMenuImmediatelyForTesting();
private:
friend class TouchSelectionControllerImplTest;
void OnDragBegin(EditingHandleView* handle);
// Callback to inform the client view that the selection handle has been
// dragged, hence selection may need to be updated. |drag_pos| is the new
// position for the edge of the selection corresponding to |dragging_handle_|,
// specified in handle's coordinates
void OnDragUpdate(const gfx::Point& drag_pos);
void OnDragEnd();
// Convenience method to convert a point from a selection handle's coordinate
// system to that of the client view.
void ConvertPointToClientView(EditingHandleView* source, gfx::Point* point);
// Convenience method to set a handle's selection bound and hide it if it is
// located out of client view.
void SetHandleBound(EditingHandleView* handle,
const gfx::SelectionBound& bound,
const gfx::SelectionBound& bound_in_screen);
// Checks if handle should be shown for selection bound.
// |bound| should be the clipped version of the selection bound.
bool ShouldShowHandleFor(const gfx::SelectionBound& bound) const;
// ui::TouchSelectionMenuClient:
bool IsCommandIdEnabled(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
void RunContextMenu() override;
bool ShouldShowQuickMenu() override;
std::u16string GetSelectedText() override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
void OnWidgetBoundsChanged(Widget* widget,
const gfx::Rect& new_bounds) override;
// ui::EventObserver:
void OnEvent(const ui::Event& event) override;
// Time to show quick menu.
void QuickMenuTimerFired();
void StartQuickMenuTimer();
// Convenience method to update the position/visibility of the quick menu.
void UpdateQuickMenu();
// Convenience method for hiding quick menu.
void HideQuickMenu();
// Convenience method to calculate anchor rect for quick menu, in screen
// coordinates.
gfx::Rect GetQuickMenuAnchorRect() const;
// Convenience methods for testing.
gfx::NativeView GetCursorHandleNativeView();
gfx::SelectionBound::Type GetSelectionHandle1Type();
gfx::Rect GetSelectionHandle1Bounds();
gfx::Rect GetSelectionHandle2Bounds();
gfx::Rect GetCursorHandleBounds();
bool IsSelectionHandle1Visible();
bool IsSelectionHandle2Visible();
bool IsCursorHandleVisible();
gfx::Rect GetExpectedHandleBounds(const gfx::SelectionBound& bound);
View* GetHandle1View();
View* GetHandle2View();
raw_ptr<ui::TouchEditable, DanglingUntriaged> client_view_;
raw_ptr<Widget, DanglingUntriaged> client_widget_ = nullptr;
// Non-owning pointers to EditingHandleViews. These views are owned by their
// Widget and cleaned up when their Widget closes.
raw_ptr<EditingHandleView, DanglingUntriaged> selection_handle_1_;
raw_ptr<EditingHandleView, DanglingUntriaged> selection_handle_2_;
raw_ptr<EditingHandleView, DanglingUntriaged> cursor_handle_;
bool command_executed_ = false;
base::TimeTicks selection_start_time_;
// Whether to enable toggling the menu by tapping the cursor or cursor handle.
// If enabled, the menu defaults to being hidden when the cursor handle is
// initially created.
bool toggle_menu_enabled_ = false;
// Whether the quick menu has been requested to be shown.
bool quick_menu_requested_ = false;
// Timer to trigger quick menu after it has been requested. If a touch handle
// is being dragged, the menu will be hidden and the timer will only start
// after the drag is lifted.
base::OneShotTimer quick_menu_timer_;
// Pointer to the SelectionHandleView being dragged during a drag session.
raw_ptr<EditingHandleView, DanglingUntriaged> dragging_handle_ = nullptr;
// In cursor mode, the two selection bounds are the same and correspond to
// |cursor_handle_|; otherwise, they correspond to |selection_handle_1_| and
// |selection_handle_2_|, respectively. These values should be used when
// selection bounds needed rather than position of handles which might be
// invalid when handles are hidden.
gfx::SelectionBound selection_bound_1_;
gfx::SelectionBound selection_bound_2_;
// Selection bounds, clipped to client view's boundaries.
gfx::SelectionBound selection_bound_1_clipped_;
gfx::SelectionBound selection_bound_2_clipped_;
};
} // namespace views
#endif // UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_controller_impl.h | C++ | unknown | 6,128 |
// 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/touchui/touch_selection_controller_impl.h"
#include <stddef.h>
#include <memory>
#include <string>
#include <utility>
#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/time.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/test/test_cursor_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/pointer/touch_editing_controller.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/render_text.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_test_api.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/views_touch_selection_controller_factory.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
using base::ASCIIToUTF16;
using base::UTF16ToUTF8;
namespace {
// Should match kSelectionHandleBarMinHeight in touch_selection_controller.
const int kBarMinHeight = 5;
// Should match kSelectionHandleBarBottomAllowance in
// touch_selection_controller.
const int kBarBottomAllowance = 3;
// For selection bounds |b1| and |b2| in a paragraph of text, returns -1 if |b1|
// is physically before |b2|, +1 if |b2| is before |b1|, and 0 if they are at
// the same location.
int CompareTextSelectionBounds(const gfx::SelectionBound& b1,
const gfx::SelectionBound& b2) {
if (b1.edge_start().y() < b2.edge_start().y() ||
b1.edge_start().x() < b2.edge_start().x()) {
return -1;
}
if (b1 == b2)
return 0;
return 1;
}
} // namespace
namespace views {
class TouchSelectionControllerImplTest : public ViewsTestBase {
public:
TouchSelectionControllerImplTest()
: views_tsc_factory_(new ViewsTouchEditingControllerFactory) {
ui::TouchEditingControllerFactory::SetInstance(views_tsc_factory_.get());
}
TouchSelectionControllerImplTest(const TouchSelectionControllerImplTest&) =
delete;
TouchSelectionControllerImplTest& operator=(
const TouchSelectionControllerImplTest&) = delete;
~TouchSelectionControllerImplTest() override {
ui::TouchEditingControllerFactory::SetInstance(nullptr);
}
void SetUp() override {
ViewsTestBase::SetUp();
test_cursor_client_ =
std::make_unique<aura::test::TestCursorClient>(GetContext());
}
void TearDown() override {
test_cursor_client_.reset();
if (textfield_widget_ && !textfield_widget_->IsClosed())
textfield_widget_->Close();
if (widget_ && !widget_->IsClosed())
widget_->Close();
ViewsTestBase::TearDown();
}
void CreateTextfield() {
textfield_ = new Textfield();
// Focusable views must have an accessible name in order to pass the
// accessibility paint checks. The name can be literal text, placeholder
// text or an associated label.
textfield_->SetPlaceholderText(u"Foo");
textfield_widget_ = new Widget;
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(0, 0, 200, 200);
textfield_widget_->Init(std::move(params));
textfield_widget_->SetContentsView(std::make_unique<View>())
->AddChildView(textfield_.get());
textfield_->SetBoundsRect(gfx::Rect(0, 0, 200, 21));
textfield_->SetID(1);
textfield_widget_->Show();
textfield_->RequestFocus();
textfield_test_api_ = std::make_unique<TextfieldTestApi>(textfield_);
}
void CreateWidget() {
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget_->Init(std::move(params));
widget_->Show();
}
protected:
static bool IsCursorHandleVisibleFor(
ui::TouchEditingControllerDeprecated* controller) {
TouchSelectionControllerImpl* impl =
static_cast<TouchSelectionControllerImpl*>(controller);
return impl->IsCursorHandleVisible();
}
gfx::Rect GetCursorRect(const gfx::SelectionModel& sel) {
return textfield_test_api_->GetRenderText()->GetCursorBounds(sel, true);
}
gfx::Point GetCursorPosition(const gfx::SelectionModel& sel) {
return GetCursorRect(sel).origin();
}
TouchSelectionControllerImpl* GetSelectionController() {
return static_cast<TouchSelectionControllerImpl*>(
textfield_test_api_->touch_selection_controller());
}
void StartTouchEditing() {
textfield_test_api_->CreateTouchSelectionControllerAndNotifyIt();
}
void EndTouchEditing() {
textfield_test_api_->ResetTouchSelectionController();
}
void SimulateSelectionHandleDrag(gfx::Vector2d v, int selection_handle) {
TouchSelectionControllerImpl* controller = GetSelectionController();
views::View* handle = nullptr;
if (selection_handle == 1)
handle = controller->GetHandle1View();
else
handle = controller->GetHandle2View();
gfx::Point grip_location =
gfx::Point(handle->size().width() / 2, handle->size().height() / 2);
base::TimeTicks time_stamp = base::TimeTicks();
{
ui::GestureEventDetails details(ui::ET_GESTURE_SCROLL_BEGIN);
ui::GestureEvent scroll_begin(grip_location.x(), grip_location.y(), 0,
time_stamp, details);
handle->OnGestureEvent(&scroll_begin);
}
test_cursor_client_->DisableMouseEvents();
{
ui::GestureEventDetails details(ui::ET_GESTURE_SCROLL_UPDATE);
gfx::Point update_location = grip_location + v;
ui::GestureEvent scroll_update(update_location.x(), update_location.y(),
0, time_stamp, details);
handle->OnGestureEvent(&scroll_update);
}
{
ui::GestureEventDetails details(ui::ET_GESTURE_SCROLL_END);
ui::GestureEvent scroll_end(grip_location.x(), grip_location.y(), 0,
time_stamp, details);
handle->OnGestureEvent(&scroll_end);
}
test_cursor_client_->EnableMouseEvents();
}
gfx::NativeView GetCursorHandleNativeView() {
return GetSelectionController()->GetCursorHandleNativeView();
}
gfx::SelectionBound::Type GetSelectionHandle1Type() {
return GetSelectionController()->GetSelectionHandle1Type();
}
gfx::Rect GetSelectionHandle1Bounds() {
return GetSelectionController()->GetSelectionHandle1Bounds();
}
gfx::Rect GetSelectionHandle2Bounds() {
return GetSelectionController()->GetSelectionHandle2Bounds();
}
gfx::Rect GetCursorHandleBounds() {
return GetSelectionController()->GetCursorHandleBounds();
}
gfx::Rect GetExpectedHandleBounds(const gfx::SelectionBound& bound) {
return GetSelectionController()->GetExpectedHandleBounds(bound);
}
bool IsSelectionHandle1Visible() {
return GetSelectionController()->IsSelectionHandle1Visible();
}
bool IsSelectionHandle2Visible() {
return GetSelectionController()->IsSelectionHandle2Visible();
}
bool IsCursorHandleVisible() {
return GetSelectionController()->IsCursorHandleVisible();
}
bool IsQuickMenuVisible() {
TouchSelectionControllerImpl* controller = GetSelectionController();
if (controller && controller->quick_menu_requested_) {
controller->ShowQuickMenuImmediatelyForTesting();
}
return ui::TouchSelectionMenuRunner::GetInstance()->IsRunning();
}
gfx::RenderText* GetRenderText() {
return textfield_test_api_->GetRenderText();
}
gfx::Point GetCursorHandleDragPoint() {
gfx::Rect rect = GetCursorHandleBounds();
const gfx::SelectionModel& sel = textfield_->GetSelectionModel();
int cursor_height = GetCursorRect(sel).height();
gfx::Point point = rect.CenterPoint();
point.Offset(0, cursor_height);
return point;
}
// If textfield has selection, this verifies that the selection handles
// are visible, at the correct positions (at the end points of selection), and
// (if |check_direction| is set to true), that they have the correct
// directionality.
// |cursor_at_selection_handle_1| is used to decide whether selection
// handle 1's position is matched against the start of selection or the end.
void VerifyHandlePositions(bool cursor_at_selection_handle_1,
bool check_direction,
const base::Location& from_here) {
gfx::SelectionBound anchor, focus;
textfield_->GetSelectionEndPoints(&anchor, &focus);
std::string from_str = from_here.ToString();
if (textfield_->HasSelection()) {
EXPECT_TRUE(IsSelectionHandle1Visible()) << from_str;
EXPECT_TRUE(IsSelectionHandle2Visible()) << from_str;
EXPECT_FALSE(IsCursorHandleVisible());
gfx::Rect sh1_bounds = GetSelectionHandle1Bounds();
gfx::Rect sh2_bounds = GetSelectionHandle2Bounds();
if (cursor_at_selection_handle_1) {
EXPECT_EQ(sh1_bounds, GetExpectedHandleBounds(focus)) << from_str;
EXPECT_EQ(sh2_bounds, GetExpectedHandleBounds(anchor)) << from_str;
} else {
EXPECT_EQ(sh1_bounds, GetExpectedHandleBounds(anchor)) << from_str;
EXPECT_EQ(sh2_bounds, GetExpectedHandleBounds(focus)) << from_str;
}
} else {
EXPECT_FALSE(IsSelectionHandle1Visible()) << from_str;
EXPECT_FALSE(IsSelectionHandle2Visible()) << from_str;
EXPECT_TRUE(IsCursorHandleVisible());
gfx::Rect cursor_bounds = GetCursorHandleBounds();
DCHECK(anchor == focus);
EXPECT_EQ(cursor_bounds, GetExpectedHandleBounds(anchor)) << from_str;
}
if (check_direction) {
if (CompareTextSelectionBounds(anchor, focus) < 0) {
EXPECT_EQ(gfx::SelectionBound::LEFT, anchor.type()) << from_str;
EXPECT_EQ(gfx::SelectionBound::RIGHT, focus.type()) << from_str;
} else if (CompareTextSelectionBounds(anchor, focus) > 0) {
EXPECT_EQ(gfx::SelectionBound::LEFT, focus.type()) << from_str;
EXPECT_EQ(gfx::SelectionBound::RIGHT, anchor.type()) << from_str;
} else {
EXPECT_EQ(gfx::SelectionBound::CENTER, focus.type()) << from_str;
EXPECT_EQ(gfx::SelectionBound::CENTER, anchor.type()) << from_str;
}
}
}
// Sets up a textfield with a long text string such that it doesn't all fit
// into the textfield. Then selects the text - the first handle is expected
// to be invisible. |selection_start| is the position of the first handle.
void SetupSelectionInvisibleHandle(uint32_t selection_start) {
// Create a textfield with lots of text in it.
CreateTextfield();
std::string some_text("some text");
std::string textfield_text;
for (int i = 0; i < 10; ++i)
textfield_text += some_text;
textfield_->SetText(ASCIIToUTF16(textfield_text));
// Tap the textfield to invoke selection.
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), details);
textfield_->OnGestureEvent(&tap);
// Select some text such that one handle is hidden.
textfield_->SetSelectedRange(gfx::Range(
selection_start, static_cast<uint32_t>(textfield_text.length())));
// Check that one selection handle is hidden.
EXPECT_FALSE(IsSelectionHandle1Visible());
EXPECT_TRUE(IsSelectionHandle2Visible());
EXPECT_EQ(gfx::Range(selection_start,
static_cast<uint32_t>(textfield_text.length())),
textfield_->GetSelectedRange());
}
raw_ptr<Widget> textfield_widget_ = nullptr;
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<Textfield> textfield_ = nullptr;
std::unique_ptr<TextfieldTestApi> textfield_test_api_;
std::unique_ptr<ViewsTouchEditingControllerFactory> views_tsc_factory_;
std::unique_ptr<aura::test::TestCursorClient> test_cursor_client_;
};
// Tests that the selection handles are placed appropriately when selection in
// a Textfield changes.
TEST_F(TouchSelectionControllerImplTest, SelectionInTextfieldTest) {
CreateTextfield();
textfield_->SetText(u"some text");
// Tap the textfield to invoke touch selection.
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), details);
textfield_->OnGestureEvent(&tap);
// Test selecting a range.
textfield_->SetSelectedRange(gfx::Range(3, 7));
VerifyHandlePositions(false, true, FROM_HERE);
// Test selecting everything.
textfield_->SelectAll(false);
VerifyHandlePositions(false, true, FROM_HERE);
// Test with no selection.
textfield_->ClearSelection();
VerifyHandlePositions(false, true, FROM_HERE);
// Test with lost focus.
textfield_widget_->GetFocusManager()->ClearFocus();
EXPECT_FALSE(GetSelectionController());
// Test with focus re-gained.
textfield_widget_->GetFocusManager()->SetFocusedView(textfield_);
EXPECT_FALSE(GetSelectionController());
textfield_->OnGestureEvent(&tap);
VerifyHandlePositions(false, true, FROM_HERE);
}
// Tests that the selection handles are placed appropriately in bidi text.
TEST_F(TouchSelectionControllerImplTest, SelectionInBidiTextfieldTest) {
CreateTextfield();
textfield_->SetText(u"abc\x05d0\x05d1\x05d2");
// Tap the textfield to invoke touch selection.
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), details);
textfield_->OnGestureEvent(&tap);
// Test cursor at run boundary and with empty selection.
textfield_->SelectSelectionModel(
gfx::SelectionModel(3, gfx::CURSOR_BACKWARD));
VerifyHandlePositions(false, true, FROM_HERE);
// Test selection range inside one run and starts or ends at run boundary.
textfield_->SetSelectedRange(gfx::Range(2, 3));
VerifyHandlePositions(false, true, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(3, 2));
VerifyHandlePositions(false, true, FROM_HERE);
// TODO(mfomitchev): crbug.com/429705
// The correct behavior for handles in mixed ltr/rtl text line is not known,
// so passing false for |check_direction| in some of these tests.
textfield_->SetSelectedRange(gfx::Range(3, 4));
VerifyHandlePositions(false, false, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(4, 3));
VerifyHandlePositions(false, false, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(3, 6));
VerifyHandlePositions(false, false, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(6, 3));
VerifyHandlePositions(false, false, FROM_HERE);
// Test selection range accross runs.
textfield_->SetSelectedRange(gfx::Range(0, 6));
VerifyHandlePositions(false, true, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(6, 0));
VerifyHandlePositions(false, true, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(1, 4));
VerifyHandlePositions(false, true, FROM_HERE);
textfield_->SetSelectedRange(gfx::Range(4, 1));
VerifyHandlePositions(false, true, FROM_HERE);
}
// Tests if the selection update callbacks are called appropriately when
// selection handles are moved.
TEST_F(TouchSelectionControllerImplTest, SelectionUpdateCallbackTest) {
CreateTextfield();
textfield_->SetText(u"textfield with selected text");
// Tap the textfield to invoke touch selection.
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), details);
textfield_->OnGestureEvent(&tap);
textfield_->SetSelectedRange(gfx::Range(3, 7));
gfx::Point textfield_origin;
textfield_->ConvertPointToScreen(&textfield_origin);
EXPECT_EQ("tfie", UTF16ToUTF8(textfield_->GetSelectedText()));
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 2 to right by 3 chars.
const gfx::FontList& font_list = textfield_->GetFontList();
int x = gfx::Canvas::GetStringWidth(u"ld ", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 2);
EXPECT_EQ("tfield ", UTF16ToUTF8(textfield_->GetSelectedText()));
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 1 to the left by a large amount (selection should
// just stick to the beginning of the textfield).
SimulateSelectionHandleDrag(gfx::Vector2d(-50, 0), 1);
EXPECT_EQ("textfield ", UTF16ToUTF8(textfield_->GetSelectedText()));
VerifyHandlePositions(true, true, FROM_HERE);
// Drag selection handle 1 across selection handle 2.
x = gfx::Canvas::GetStringWidth(u"textfield with ", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 1);
EXPECT_EQ("with ", UTF16ToUTF8(textfield_->GetSelectedText()));
VerifyHandlePositions(true, true, FROM_HERE);
// Drag selection handle 2 across selection handle 1.
x = gfx::Canvas::GetStringWidth(u"with selected ", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 2);
EXPECT_EQ("selected ", UTF16ToUTF8(textfield_->GetSelectedText()));
VerifyHandlePositions(false, true, FROM_HERE);
}
TEST_F(TouchSelectionControllerImplTest, SelectionUpdateInBidiCallbackTest) {
CreateTextfield();
textfield_->SetText(
u"abc\x05e1\x05e2\x05e3"
u"def");
// Tap the textfield to invoke touch selection.
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), details);
textfield_->OnGestureEvent(&tap);
// Select [c] from left to right.
textfield_->SetSelectedRange(gfx::Range(2, 3));
EXPECT_EQ(u"c", textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 2 to right by 1 char.
const gfx::FontList& font_list = textfield_->GetFontList();
int x = gfx::Canvas::GetStringWidth(u"\x05e3", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 2);
EXPECT_EQ(u"c\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 1 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"b", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 1);
EXPECT_EQ(u"bc\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(true, true, FROM_HERE);
// Select [c] from right to left.
textfield_->SetSelectedRange(gfx::Range(3, 2));
EXPECT_EQ(u"c", textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 1 to right by 1 char.
x = gfx::Canvas::GetStringWidth(u"\x05e3", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 1);
EXPECT_EQ(u"c\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(true, true, FROM_HERE);
// Drag selection handle 2 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"b", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 2);
EXPECT_EQ(u"bc\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Select [\x5e1] from right to left.
textfield_->SetSelectedRange(gfx::Range(3, 4));
EXPECT_EQ(u"\x05e1", textfield_->GetSelectedText());
// TODO(mfomitchev): crbug.com/429705
// The correct behavior for handles in mixed ltr/rtl text line is not known,
// so passing false for |check_direction| in some of these tests.
VerifyHandlePositions(false, false, FROM_HERE);
/* TODO(xji): for bidi text "abcDEF" whose display is "abcFEDhij", when click
right of 'D' and select [D] then move the left selection handle to left
by one character, it should select [ED], instead it selects [F].
Reason: click right of 'D' and left of 'h' return the same x-axis position,
pass this position to FindCursorPosition() returns index of 'h'. which
means the selection start changed from 3 to 6.
Need further investigation on whether this is a bug in Pango and how to
work around it.
// Drag selection handle 2 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"\x05e2", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 2);
EXPECT_EQ(u"\x05e1\x05e2", textfield_->GetSelectedText());
VERIFY_HANDLE_POSITIONS(false);
*/
// Drag selection handle 1 to right by 1 char.
x = gfx::Canvas::GetStringWidth(u"d", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 1);
EXPECT_EQ(
u"\x05e2\x05e3"
u"d",
textfield_->GetSelectedText());
VerifyHandlePositions(true, true, FROM_HERE);
// Select [\x5e1] from left to right.
textfield_->SetSelectedRange(gfx::Range(4, 3));
EXPECT_EQ(u"\x05e1", textfield_->GetSelectedText());
VerifyHandlePositions(false, false, FROM_HERE);
/* TODO(xji): see detail of above commented out test case.
// Drag selection handle 1 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"\x05e2", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 1);
EXPECT_EQ(u"\x05e1\x05e2", textfield_->GetSelectedText());
VERIFY_HANDLE_POSITIONS(true);
*/
// Drag selection handle 2 to right by 1 char.
x = gfx::Canvas::GetStringWidth(u"d", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 2);
EXPECT_EQ(
u"\x05e2\x05e3"
u"d",
textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Select [\x05r3] from right to left.
textfield_->SetSelectedRange(gfx::Range(5, 6));
EXPECT_EQ(u"\x05e3", textfield_->GetSelectedText());
VerifyHandlePositions(false, false, FROM_HERE);
// Drag selection handle 2 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"c", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 2);
EXPECT_EQ(u"c\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(false, true, FROM_HERE);
// Drag selection handle 1 to right by 1 char.
x = gfx::Canvas::GetStringWidth(u"\x05e2", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 1);
EXPECT_EQ(u"c\x05e1", textfield_->GetSelectedText());
VerifyHandlePositions(true, true, FROM_HERE);
// Select [\x05r3] from left to right.
textfield_->SetSelectedRange(gfx::Range(6, 5));
EXPECT_EQ(u"\x05e3", textfield_->GetSelectedText());
VerifyHandlePositions(false, false, FROM_HERE);
// Drag selection handle 1 to left by 1 char.
x = gfx::Canvas::GetStringWidth(u"c", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(-x, 0), 1);
EXPECT_EQ(u"c\x05e1\x05e2", textfield_->GetSelectedText());
VerifyHandlePositions(true, true, FROM_HERE);
// Drag selection handle 2 to right by 1 char.
x = gfx::Canvas::GetStringWidth(u"\x05e2", font_list);
SimulateSelectionHandleDrag(gfx::Vector2d(x, 0), 2);
EXPECT_EQ(u"c\x05e1", textfield_->GetSelectedText());
VerifyHandlePositions(false, false, FROM_HERE);
}
TEST_F(TouchSelectionControllerImplTest,
HiddenSelectionHandleRetainsCursorPosition) {
static const uint32_t selection_start = 10u;
SetupSelectionInvisibleHandle(selection_start);
// Drag the visible handle around and make sure the selection end point of the
// invisible handle does not change.
size_t visible_handle_position = textfield_->GetSelectedRange().end();
for (int i = 0; i < 10; ++i) {
static const int drag_diff = -10;
SimulateSelectionHandleDrag(gfx::Vector2d(drag_diff, 0), 2);
// Make sure that the visible handle is being dragged.
EXPECT_NE(visible_handle_position, textfield_->GetSelectedRange().end());
visible_handle_position = textfield_->GetSelectedRange().end();
EXPECT_EQ(10u, textfield_->GetSelectedRange().start());
}
}
// Tests that we can handle the hidden handle getting exposed as a result of a
// drag and that it maintains the correct orientation when exposed.
TEST_F(TouchSelectionControllerImplTest, HiddenSelectionHandleExposed) {
static const uint32_t selection_start = 0u;
SetupSelectionInvisibleHandle(selection_start);
// Drag the handle until the selection shrinks such that the other handle
// becomes visible.
while (!IsSelectionHandle1Visible()) {
static const int drag_diff = -10;
SimulateSelectionHandleDrag(gfx::Vector2d(drag_diff, 0), 2);
}
// Confirm that the exposed handle maintains the LEFT orientation
// (and does not reset to gfx::SelectionBound::Type::CENTER).
EXPECT_EQ(gfx::SelectionBound::Type::LEFT, GetSelectionHandle1Type());
}
TEST_F(TouchSelectionControllerImplTest,
DoubleTapInTextfieldWithCursorHandleShouldSelectText) {
CreateTextfield();
textfield_->SetText(u"some text");
ui::test::EventGenerator generator(
textfield_->GetWidget()->GetNativeView()->GetRootWindow());
// Tap the textfield to invoke touch selection.
generator.GestureTapAt(gfx::Point(10, 10));
// Cursor handle should be visible.
EXPECT_FALSE(textfield_->HasSelection());
VerifyHandlePositions(false, true, FROM_HERE);
// Double tap on the cursor handle position. We want to check that the cursor
// handle is not eating the event and that the event is falling through to the
// textfield.
gfx::Point cursor_pos = GetCursorHandleBounds().origin();
cursor_pos.Offset(GetCursorHandleBounds().width() / 2, 0);
generator.GestureTapAt(cursor_pos);
generator.GestureTapAt(cursor_pos);
EXPECT_TRUE(textfield_->HasSelection());
}
TEST_F(TouchSelectionControllerImplTest,
MenuAppearsAfterDraggingSelectionHandles) {
CreateTextfield();
textfield_->SetText(u"some text in a textfield");
textfield_->SetSelectedRange(gfx::Range(2, 15));
ui::test::EventGenerator generator(
textfield_->GetWidget()->GetNativeView()->GetRootWindow());
EXPECT_FALSE(IsQuickMenuVisible());
// Tap on the selected text to make selection handles appear, menu should also
// appear.
generator.GestureTapAt(gfx::Point(30, 15));
EXPECT_TRUE(IsQuickMenuVisible());
// Drag the selection handles, menu should appear after each drag ends.
SimulateSelectionHandleDrag(gfx::Vector2d(3, 0), 1);
EXPECT_TRUE(IsQuickMenuVisible());
SimulateSelectionHandleDrag(gfx::Vector2d(-5, 0), 2);
EXPECT_TRUE(IsQuickMenuVisible());
// Lose focus, menu should disappear.
textfield_widget_->GetFocusManager()->ClearFocus();
EXPECT_FALSE(IsQuickMenuVisible());
}
#if BUILDFLAG(IS_CHROMEOS)
TEST_F(TouchSelectionControllerImplTest, TapOnHandleTogglesMenu) {
base::test::ScopedFeatureList feature_list;
feature_list.InitWithFeatures(
/*enabled_features=*/{::features::kTouchTextEditingRedesign},
/*disabled_features=*/{});
CreateTextfield();
textfield_->SetText(u"some text in a textfield");
ui::test::EventGenerator generator(
textfield_->GetWidget()->GetNativeView()->GetRootWindow());
// Tap the textfield to invoke touch selection. Cursor handle should be
// shown, but not the quick menu.
generator.GestureTapAt(gfx::Point(10, 10));
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_FALSE(IsQuickMenuVisible());
// Tap the touch handle, the quick menu should appear.
gfx::Point handle_pos = GetCursorHandleBounds().CenterPoint();
generator.GestureTapAt(handle_pos);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_TRUE(IsQuickMenuVisible());
// Tap the touch handle again, the quick menu should disappear.
generator.GestureTapAt(handle_pos);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_FALSE(IsQuickMenuVisible());
// Tap the touch handle again, the quick menu should appear.
generator.GestureTapAt(handle_pos);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_TRUE(IsQuickMenuVisible());
// Tap a different spot in the textfield, handle should remain visible but the
// quick menu should disappear.
generator.GestureTapAt(gfx::Point(60, 10));
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_FALSE(IsQuickMenuVisible());
}
TEST_F(TouchSelectionControllerImplTest, TapOnCursorTogglesMenu) {
base::test::ScopedFeatureList feature_list;
feature_list.InitWithFeatures(
/*enabled_features=*/{::features::kTouchTextEditingRedesign},
/*disabled_features=*/{});
CreateTextfield();
textfield_->SetText(u"some text in a textfield");
textfield_->SetSelectedRange(gfx::Range(7, 7));
const gfx::Point cursor_position =
GetCursorRect(textfield_->GetSelectionModel()).CenterPoint();
ui::test::EventGenerator generator(
textfield_->GetWidget()->GetNativeView()->GetRootWindow());
// Tap the cursor. Cursor handle and quick menu should appear.
generator.GestureTapAt(cursor_position);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_TRUE(IsQuickMenuVisible());
// Tap the cursor, the quick menu should disappear. We advance the clock
// before tapping again to avoid the tap being treated as a double tap.
generator.AdvanceClock(base::Milliseconds(1000));
generator.GestureTapAt(cursor_position);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_FALSE(IsQuickMenuVisible());
// Tap the cursor, the quick menu should appear.
generator.AdvanceClock(base::Milliseconds(1000));
generator.GestureTapAt(cursor_position);
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_TRUE(IsQuickMenuVisible());
// Tap a different spot in the textfield to move the cursor. The handle should
// remain visible but the quick menu should disappear.
generator.AdvanceClock(base::Milliseconds(1000));
generator.GestureTapAt(gfx::Point(100, 10));
EXPECT_TRUE(IsCursorHandleVisible());
EXPECT_FALSE(IsQuickMenuVisible());
}
TEST_F(TouchSelectionControllerImplTest, SelectCommands) {
base::test::ScopedFeatureList feature_list;
feature_list.InitWithFeatures(
/*enabled_features=*/{::features::kTouchTextEditingRedesign},
/*disabled_features=*/{});
CreateTextfield();
textfield_->SetText(u"some text");
ui::test::EventGenerator generator(
textfield_->GetWidget()->GetNativeView()->GetRootWindow());
// Tap the textfield to invoke touch selection.
generator.GestureTapAt(gfx::Point(10, 10));
// Select all and select word options should be enabled after initial tap.
ui::TouchSelectionMenuClient* menu_client = GetSelectionController();
ASSERT_TRUE(menu_client);
EXPECT_TRUE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectAll));
EXPECT_TRUE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectWord));
// Select word at current position. Select word command should now be disabled
// since there is already a selection.
menu_client->ExecuteCommand(ui::TouchEditable::kSelectWord,
ui::EF_FROM_TOUCH);
EXPECT_EQ("some", UTF16ToUTF8(textfield_->GetSelectedText()));
menu_client = GetSelectionController();
ASSERT_TRUE(menu_client);
EXPECT_TRUE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectAll));
EXPECT_FALSE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectWord));
// Select all text. Select all and select word commands should now be
// disabled.
menu_client->ExecuteCommand(ui::TouchEditable::kSelectAll, ui::EF_FROM_TOUCH);
EXPECT_EQ("some text", UTF16ToUTF8(textfield_->GetSelectedText()));
menu_client = GetSelectionController();
ASSERT_TRUE(menu_client);
EXPECT_FALSE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectAll));
EXPECT_FALSE(menu_client->IsCommandIdEnabled(ui::TouchEditable::kSelectWord));
}
#endif
// A simple implementation of TouchEditable that allows faking cursor position
// inside its boundaries.
class TestTouchEditable : public ui::TouchEditable {
public:
explicit TestTouchEditable(aura::Window* window) : window_(window) {
DCHECK(window);
}
void set_bounds(const gfx::Rect& bounds) { bounds_ = bounds; }
void set_cursor_rect(const gfx::RectF& cursor_rect) {
cursor_bound_.SetEdge(cursor_rect.origin(), cursor_rect.bottom_left());
cursor_bound_.set_type(gfx::SelectionBound::Type::CENTER);
}
TestTouchEditable(const TestTouchEditable&) = delete;
TestTouchEditable& operator=(const TestTouchEditable&) = delete;
~TestTouchEditable() override = default;
private:
// Overridden from ui::TouchEditable.
void MoveCaret(const gfx::Point& position) override { NOTREACHED_NORETURN(); }
void MoveRangeSelectionExtent(const gfx::Point& extent) override {
NOTREACHED_NORETURN();
}
void SelectBetweenCoordinates(const gfx::Point& base,
const gfx::Point& extent) override {
NOTREACHED_NORETURN();
}
void GetSelectionEndPoints(gfx::SelectionBound* anchor,
gfx::SelectionBound* focus) override {
*anchor = *focus = cursor_bound_;
}
gfx::Rect GetBounds() override { return gfx::Rect(bounds_.size()); }
gfx::NativeView GetNativeView() const override { return window_; }
void ConvertPointToScreen(gfx::Point* point) override {
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(window_->GetRootWindow());
if (screen_position_client)
screen_position_client->ConvertPointToScreen(window_, point);
}
void ConvertPointFromScreen(gfx::Point* point) override {
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(window_->GetRootWindow());
if (screen_position_client)
screen_position_client->ConvertPointFromScreen(window_, point);
}
void OpenContextMenu(const gfx::Point& anchor) override {
NOTREACHED_NORETURN();
}
void DestroyTouchSelection() override { NOTREACHED_NORETURN(); }
// Overridden from ui::SimpleMenuModel::Delegate.
bool IsCommandIdChecked(int command_id) const override {
NOTREACHED_NORETURN();
}
bool IsCommandIdEnabled(int command_id) const override {
NOTREACHED_NORETURN();
}
void ExecuteCommand(int command_id, int event_flags) override {
NOTREACHED_NORETURN();
}
raw_ptr<aura::Window> window_;
// Boundaries of the client view.
gfx::Rect bounds_;
// Cursor position inside the client view.
gfx::SelectionBound cursor_bound_;
};
// Tests if the touch editing handle is shown or hidden properly according to
// the cursor position relative to the client boundaries.
TEST_F(TouchSelectionControllerImplTest,
VisibilityOfHandleRegardingClientBounds) {
CreateWidget();
TestTouchEditable touch_editable(widget_->GetNativeView());
std::unique_ptr<ui::TouchEditingControllerDeprecated>
touch_selection_controller(
ui::TouchEditingControllerDeprecated::Create(&touch_editable));
touch_editable.set_bounds(gfx::Rect(0, 0, 100, 20));
// Put the cursor completely inside the client bounds. Handle should be
// visible.
touch_editable.set_cursor_rect(gfx::RectF(2.f, 0.f, 1.f, 20.f));
touch_selection_controller->SelectionChanged();
EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get()));
// Move the cursor up such that |kBarMinHeight| pixels are still in the client
// bounds. Handle should still be visible.
touch_editable.set_cursor_rect(
gfx::RectF(2.f, kBarMinHeight - 20.f, 1.f, 20.f));
touch_selection_controller->SelectionChanged();
EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get()));
// Move the cursor up such that less than |kBarMinHeight| pixels are in the
// client bounds. Handle should be hidden.
touch_editable.set_cursor_rect(
gfx::RectF(2.f, kBarMinHeight - 20.f - 1.f, 1.f, 20.f));
touch_selection_controller->SelectionChanged();
EXPECT_FALSE(IsCursorHandleVisibleFor(touch_selection_controller.get()));
// Move the Cursor down such that |kBarBottomAllowance| pixels are out of the
// client bounds. Handle should be visible.
touch_editable.set_cursor_rect(
gfx::RectF(2.f, kBarBottomAllowance, 1.f, 20.f));
touch_selection_controller->SelectionChanged();
EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get()));
// Move the cursor down such that more than |kBarBottomAllowance| pixels are
// out of the client bounds. Handle should be hidden.
touch_editable.set_cursor_rect(
gfx::RectF(2.f, kBarBottomAllowance + 1.f, 1.f, 20.f));
touch_selection_controller->SelectionChanged();
EXPECT_FALSE(IsCursorHandleVisibleFor(touch_selection_controller.get()));
touch_selection_controller.reset();
}
TEST_F(TouchSelectionControllerImplTest, HandlesStackAboveParent) {
aura::Window* root = GetContext();
ui::EventTargeter* targeter =
root->GetHost()->dispatcher()->GetDefaultEventTargeter();
// Create the first window containing a Views::Textfield.
CreateTextfield();
aura::Window* window1 = textfield_widget_->GetNativeView();
// Start touch editing, check that the handle is above the first window, and
// end touch editing.
StartTouchEditing();
gfx::Point test_point = GetCursorHandleDragPoint();
ui::MouseEvent test_event1(ui::ET_MOUSE_MOVED, test_point, test_point,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
EXPECT_EQ(GetCursorHandleNativeView(),
targeter->FindTargetForEvent(root, &test_event1));
EndTouchEditing();
// Create the second (empty) window over the first one.
CreateWidget();
aura::Window* window2 = widget_->GetNativeView();
// Start touch editing (in the first window) and check that the handle is not
// above the second window.
StartTouchEditing();
ui::MouseEvent test_event2(ui::ET_MOUSE_MOVED, test_point, test_point,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
EXPECT_EQ(window2, targeter->FindTargetForEvent(root, &test_event2));
// Move the first window to top and check that the handle is kept above the
// first window.
window1->GetRootWindow()->StackChildAtTop(window1);
ui::MouseEvent test_event3(ui::ET_MOUSE_MOVED, test_point, test_point,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
EXPECT_EQ(GetCursorHandleNativeView(),
targeter->FindTargetForEvent(root, &test_event3));
}
TEST_F(TouchSelectionControllerImplTest, MouseEventDeactivatesTouchSelection) {
CreateTextfield();
EXPECT_FALSE(GetSelectionController());
ui::test::EventGenerator generator(
textfield_widget_->GetNativeView()->GetRootWindow());
generator.set_current_screen_location(gfx::Point(5, 5));
RunPendingMessages();
// Start touch editing; then move mouse over the textfield and ensure it
// deactivates touch selection.
StartTouchEditing();
EXPECT_TRUE(GetSelectionController());
generator.MoveMouseTo(gfx::Point(5, 10));
RunPendingMessages();
EXPECT_FALSE(GetSelectionController());
generator.MoveMouseTo(gfx::Point(5, 50));
RunPendingMessages();
// Start touch editing; then move mouse out of the textfield, but inside the
// winow and ensure it deactivates touch selection.
StartTouchEditing();
EXPECT_TRUE(GetSelectionController());
generator.MoveMouseTo(gfx::Point(5, 55));
RunPendingMessages();
EXPECT_FALSE(GetSelectionController());
generator.MoveMouseTo(gfx::Point(5, 500));
RunPendingMessages();
// Start touch editing; then move mouse out of the textfield and window and
// ensure it deactivates touch selection.
StartTouchEditing();
EXPECT_TRUE(GetSelectionController());
generator.MoveMouseTo(5, 505);
RunPendingMessages();
EXPECT_FALSE(GetSelectionController());
}
TEST_F(TouchSelectionControllerImplTest, MouseCaptureChangedEventIgnored) {
CreateTextfield();
EXPECT_FALSE(GetSelectionController());
ui::test::EventGenerator generator(
textfield_widget_->GetNativeView()->GetRootWindow());
RunPendingMessages();
// Start touch editing; then generate a mouse-capture-changed event and ensure
// it does not deactivate touch selection.
StartTouchEditing();
EXPECT_TRUE(GetSelectionController());
ui::MouseEvent capture_changed(ui::ET_MOUSE_CAPTURE_CHANGED, gfx::Point(5, 5),
gfx::Point(5, 5), base::TimeTicks(), 0, 0);
generator.Dispatch(&capture_changed);
RunPendingMessages();
EXPECT_TRUE(GetSelectionController());
}
TEST_F(TouchSelectionControllerImplTest, KeyEventDeactivatesTouchSelection) {
CreateTextfield();
EXPECT_FALSE(GetSelectionController());
ui::test::EventGenerator generator(
textfield_widget_->GetNativeView()->GetRootWindow());
RunPendingMessages();
// Start touch editing; then press a key and ensure it deactivates touch
// selection.
StartTouchEditing();
EXPECT_TRUE(GetSelectionController());
generator.PressKey(ui::VKEY_A, 0);
RunPendingMessages();
EXPECT_FALSE(GetSelectionController());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_controller_impl_unittest.cc | C++ | unknown | 40,829 |
// 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/touchui/touch_selection_menu_runner_views.h"
#include <stddef.h>
#include "ui/aura/window.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/touchui/touch_selection_menu_views.h"
namespace views {
TouchSelectionMenuRunnerViews::TestApi::TestApi(
TouchSelectionMenuRunnerViews* menu_runner)
: menu_runner_(menu_runner) {
DCHECK(menu_runner_);
}
TouchSelectionMenuRunnerViews::TestApi::~TestApi() = default;
int TouchSelectionMenuRunnerViews::TestApi::GetMenuWidth() const {
TouchSelectionMenuViews* menu = menu_runner_->menu_;
return menu ? menu->width() : 0;
}
gfx::Rect TouchSelectionMenuRunnerViews::TestApi::GetAnchorRect() const {
TouchSelectionMenuViews* menu = menu_runner_->menu_;
return menu ? menu->GetAnchorRect() : gfx::Rect();
}
LabelButton* TouchSelectionMenuRunnerViews::TestApi::GetFirstButton() {
TouchSelectionMenuViews* menu = menu_runner_->menu_;
return menu ? static_cast<LabelButton*>(menu->children().front()) : nullptr;
}
Widget* TouchSelectionMenuRunnerViews::TestApi::GetWidget() {
TouchSelectionMenuViews* menu = menu_runner_->menu_;
return menu ? menu->GetWidget() : nullptr;
}
void TouchSelectionMenuRunnerViews::TestApi::ShowMenu(
TouchSelectionMenuViews* menu,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size) {
menu_runner_->ShowMenu(menu, anchor_rect, handle_image_size);
}
TouchSelectionMenuRunnerViews::TouchSelectionMenuRunnerViews() = default;
TouchSelectionMenuRunnerViews::~TouchSelectionMenuRunnerViews() {
CloseMenu();
}
void TouchSelectionMenuRunnerViews::ShowMenu(
TouchSelectionMenuViews* menu,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size) {
CloseMenu();
menu_ = menu;
menu_->ShowMenu(anchor_rect, handle_image_size);
}
bool TouchSelectionMenuRunnerViews::IsMenuAvailable(
const ui::TouchSelectionMenuClient* client) const {
return TouchSelectionMenuViews::IsMenuAvailable(client);
}
void TouchSelectionMenuRunnerViews::OpenMenu(
base::WeakPtr<ui::TouchSelectionMenuClient> client,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size,
aura::Window* context) {
DCHECK(client);
CloseMenu();
if (!TouchSelectionMenuViews::IsMenuAvailable(client.get()))
return;
menu_ = new TouchSelectionMenuViews(this, client, context);
menu_->ShowMenu(anchor_rect, handle_image_size);
}
void TouchSelectionMenuRunnerViews::CloseMenu() {
if (!menu_)
return;
// Closing the menu sets |menu_| to nullptr and eventually deletes the object.
menu_->CloseMenu();
DCHECK(!menu_);
}
bool TouchSelectionMenuRunnerViews::IsRunning() const {
return menu_ != nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_menu_runner_views.cc | C++ | unknown | 2,940 |
// 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_TOUCHUI_TOUCH_SELECTION_MENU_RUNNER_VIEWS_H_
#define UI_VIEWS_TOUCHUI_TOUCH_SELECTION_MENU_RUNNER_VIEWS_H_
#include "base/memory/raw_ptr.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/views_export.h"
namespace views {
class LabelButton;
class TouchSelectionMenuViews;
class Widget;
// Views implementation for TouchSelectionMenuRunner.
class VIEWS_EXPORT TouchSelectionMenuRunnerViews
: public ui::TouchSelectionMenuRunner {
public:
// Test API to access internal state in tests.
class VIEWS_EXPORT TestApi {
public:
explicit TestApi(TouchSelectionMenuRunnerViews* menu_runner);
TestApi(const TestApi&) = delete;
TestApi& operator=(const TestApi&) = delete;
~TestApi();
int GetMenuWidth() const;
gfx::Rect GetAnchorRect() const;
LabelButton* GetFirstButton();
Widget* GetWidget();
void ShowMenu(TouchSelectionMenuViews* menu,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size);
private:
raw_ptr<TouchSelectionMenuRunnerViews> menu_runner_;
};
TouchSelectionMenuRunnerViews();
TouchSelectionMenuRunnerViews(const TouchSelectionMenuRunnerViews&) = delete;
TouchSelectionMenuRunnerViews& operator=(
const TouchSelectionMenuRunnerViews&) = delete;
~TouchSelectionMenuRunnerViews() override;
protected:
// Sets the menu as the currently runner menu and shows it.
void ShowMenu(TouchSelectionMenuViews* menu,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size);
// ui::TouchSelectionMenuRunner:
bool IsMenuAvailable(
const ui::TouchSelectionMenuClient* client) const override;
void CloseMenu() override;
void OpenMenu(base::WeakPtr<ui::TouchSelectionMenuClient> client,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size,
aura::Window* context) override;
bool IsRunning() const override;
private:
friend class TouchSelectionMenuViews;
// A pointer to the currently running menu, or |nullptr| if no menu is
// running. The menu manages its own lifetime and deletes itself when closed.
raw_ptr<TouchSelectionMenuViews> menu_ = nullptr;
};
} // namespace views
#endif // UI_VIEWS_TOUCHUI_TOUCH_SELECTION_MENU_RUNNER_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_menu_runner_views.h | C++ | unknown | 2,535 |
// 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/touchui/touch_selection_menu_runner_views.h"
#include "ui/events/event_utils.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/touchui/touch_selection_menu_views.h"
namespace views {
namespace {
class TouchSelectionMenuRunnerViewsTest : public ViewsTestBase,
public ui::TouchSelectionMenuClient {
public:
TouchSelectionMenuRunnerViewsTest() = default;
TouchSelectionMenuRunnerViewsTest(const TouchSelectionMenuRunnerViewsTest&) =
delete;
TouchSelectionMenuRunnerViewsTest& operator=(
const TouchSelectionMenuRunnerViewsTest&) = delete;
~TouchSelectionMenuRunnerViewsTest() override = default;
protected:
void SetUp() override {
ViewsTestBase::SetUp();
// These tests expect NativeWidgetAura and so aren't applicable to
// aura-mus-client. http://crbug.com/663561.
}
void set_no_commmand_available(bool no_command) {
no_command_available_ = no_command;
}
int last_executed_command_id() const { return last_executed_command_id_; }
private:
// ui::TouchSelectionMenuClient:
bool IsCommandIdEnabled(int command_id) const override {
return !no_command_available_;
}
void ExecuteCommand(int command_id, int event_flags) override {
last_executed_command_id_ = command_id;
}
void RunContextMenu() override {}
std::u16string GetSelectedText() override { return std::u16string(); }
bool ShouldShowQuickMenu() override { return false; }
// When set to true, no command would be available and menu should not be
// shown.
bool no_command_available_ = false;
int last_executed_command_id_ = 0;
};
// Tests that the default touch selection menu runner is installed and opening
// and closing the menu works properly.
TEST_F(TouchSelectionMenuRunnerViewsTest, InstalledAndWorksProperly) {
gfx::Rect menu_anchor(0, 0, 10, 10);
gfx::Size handle_size(10, 10);
// Menu runner instance should be installed, but no menu should be running.
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance());
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Run menu. Since commands are available, this should bring up menus.
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), menu_anchor, handle_size, GetContext());
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Close menu.
ui::TouchSelectionMenuRunner::GetInstance()->CloseMenu();
RunPendingMessages();
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Try running menu when no commands is available. Menu should not be shown.
set_no_commmand_available(true);
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), menu_anchor, handle_size, GetContext());
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
}
// Tests that the anchor rect for the quick menu is adjusted to account for the
// handles. When the width of the anchor rect is too small to fit the quick
// menu, the bottom of the anchor rect should be expanded so that the quick menu
// will not overlap with the handles.
TEST_F(TouchSelectionMenuRunnerViewsTest, QuickMenuAdjustsAnchorRect) {
gfx::Size handle_size(10, 10);
TouchSelectionMenuRunnerViews::TestApi test_api(
static_cast<TouchSelectionMenuRunnerViews*>(
ui::TouchSelectionMenuRunner::GetInstance()));
// When the provided anchor rect has zero width (e.g. when an insertion handle
// is visible), the bottom should be adjusted to include the handle height.
gfx::Rect anchor_rect(0, 0, 0, 20);
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), anchor_rect, handle_size, GetContext());
anchor_rect.Outset(gfx::Outsets::TLBR(0, 0, handle_size.height(), 0));
EXPECT_EQ(anchor_rect, test_api.GetAnchorRect());
// When the provided anchor rect's width is slightly greater than the quick
// menu width plus the handle width, the anchor rect should not be adjusted.
anchor_rect =
gfx::Rect(0, 0, test_api.GetMenuWidth() + handle_size.width() + 10, 20);
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), anchor_rect, handle_size, GetContext());
EXPECT_EQ(anchor_rect, test_api.GetAnchorRect());
// When the provided anchor rect's width is slightly less than the quick
// menu width plus the handle width, the anchor rect should be adjusted.
anchor_rect =
gfx::Rect(0, 0, test_api.GetMenuWidth() + handle_size.width() - 10, 20);
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), anchor_rect, handle_size, GetContext());
anchor_rect.Outset(gfx::Outsets::TLBR(0, 0, handle_size.height(), 0));
EXPECT_EQ(anchor_rect, test_api.GetAnchorRect());
ui::TouchSelectionMenuRunner::GetInstance()->CloseMenu();
RunPendingMessages();
}
// Tests that running one of menu actions closes the menu properly.
TEST_F(TouchSelectionMenuRunnerViewsTest, RunningActionClosesProperly) {
gfx::Rect menu_anchor(0, 0, 10, 10);
gfx::Size handle_size(10, 10);
TouchSelectionMenuRunnerViews::TestApi test_api(
static_cast<TouchSelectionMenuRunnerViews*>(
ui::TouchSelectionMenuRunner::GetInstance()));
// Initially, no menu should be running.
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Run menu. Since commands are available, this should bring up menus.
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), menu_anchor, handle_size, GetContext());
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Tap the first action on the menu and check that the menu is closed
// properly.
LabelButton* button = test_api.GetFirstButton();
DCHECK(button);
gfx::Point button_center = button->bounds().CenterPoint();
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
ui::GestureEvent tap(button_center.x(), button_center.y(), 0,
ui::EventTimeForNow(), details);
button->OnGestureEvent(&tap);
RunPendingMessages();
EXPECT_NE(0, last_executed_command_id());
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
}
// Tests that closing the menu widget cleans up the menu runner state properly.
TEST_F(TouchSelectionMenuRunnerViewsTest, ClosingWidgetClosesProperly) {
gfx::Rect menu_anchor(0, 0, 10, 10);
gfx::Size handle_size(10, 10);
TouchSelectionMenuRunnerViews::TestApi test_api(
static_cast<TouchSelectionMenuRunnerViews*>(
ui::TouchSelectionMenuRunner::GetInstance()));
// Initially, no menu should be running.
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Run menu. Since commands are available, this should bring up menus.
ui::TouchSelectionMenuRunner::GetInstance()->OpenMenu(
GetWeakPtr(), menu_anchor, handle_size, GetContext());
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
// Close the menu widget and check that menu runner correctly knows that menu
// is not running anymore.
Widget* widget = test_api.GetWidget();
DCHECK(widget);
widget->Close();
RunPendingMessages();
EXPECT_FALSE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
}
// Regression test for shutdown crash. https://crbug.com/1146270
TEST_F(TouchSelectionMenuRunnerViewsTest, ShowMenuTwiceOpensOneMenu) {
gfx::Rect menu_anchor(0, 0, 10, 10);
gfx::Size handle_size(10, 10);
auto* menu_runner = static_cast<TouchSelectionMenuRunnerViews*>(
ui::TouchSelectionMenuRunner::GetInstance());
TouchSelectionMenuRunnerViews::TestApi test_api(menu_runner);
// Call ShowMenu() twice in a row. The menus manage their own lifetimes.
auto* menu1 =
new TouchSelectionMenuViews(menu_runner, GetWeakPtr(), GetContext());
test_api.ShowMenu(menu1, menu_anchor, handle_size);
auto* widget1 = test_api.GetWidget();
auto* menu2 =
new TouchSelectionMenuViews(menu_runner, GetWeakPtr(), GetContext());
test_api.ShowMenu(menu2, menu_anchor, handle_size);
auto* widget2 = test_api.GetWidget();
// Showing the second menu triggers a close of the first menu.
EXPECT_TRUE(widget1->IsClosed());
EXPECT_FALSE(widget2->IsClosed());
// Closing the second menu does not crash or CHECK.
widget2->Close();
RunPendingMessages();
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_menu_runner_views_unittest.cc | C++ | unknown | 8,648 |
// 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/touchui/touch_selection_menu_views.h"
#include <memory>
#include <utility>
#include "base/check.h"
#include "base/feature_list.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/aura/window.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/pointer/touch_editing_controller.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/text_utils.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/views_features.h"
namespace views {
namespace {
struct MenuCommand {
int command_id;
int message_id;
};
MenuCommand kMenuCommands[] = {
{ui::TouchEditable::kCut, IDS_APP_CUT},
{ui::TouchEditable::kCopy, IDS_APP_COPY},
{ui::TouchEditable::kPaste, IDS_APP_PASTE},
};
MenuCommand kMenuSelectCommands[] = {
{ui::TouchEditable::kSelectWord, IDS_APP_SELECT},
{ui::TouchEditable::kSelectAll, IDS_APP_SELECT_ALL},
};
constexpr int kSpacingBetweenButtons = 2;
} // namespace
TouchSelectionMenuViews::TouchSelectionMenuViews(
TouchSelectionMenuRunnerViews* owner,
base::WeakPtr<ui::TouchSelectionMenuClient> client,
aura::Window* context)
: BubbleDialogDelegateView(nullptr, BubbleBorder::BOTTOM_CENTER),
owner_(owner),
client_(client) {
DCHECK(owner_);
DCHECK(client_);
DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE);
set_shadow(BubbleBorder::STANDARD_SHADOW);
set_parent_window(context);
constexpr gfx::Insets kMenuMargins = gfx::Insets(1);
set_margins(kMenuMargins);
SetCanActivate(false);
set_adjust_if_offscreen(true);
SetFlipCanvasOnPaintForRTLUI(true);
SetLayoutManager(
std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal,
gfx::Insets(), kSpacingBetweenButtons));
}
void TouchSelectionMenuViews::ShowMenu(const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size) {
CreateButtons();
// After buttons are created, check if there is enough room between handles to
// show the menu and adjust anchor rect properly if needed, just in case the
// menu is needed to be shown under the selection.
gfx::Rect adjusted_anchor_rect(anchor_rect);
int menu_width = GetPreferredSize().width();
// TODO(mfomitchev): This assumes that the handles are center-aligned to the
// |achor_rect| edges, which is not true. We should fix this, perhaps by
// passing down the cumulative width occupied by the handles within
// |anchor_rect| plus the handle image height instead of |handle_image_size|.
// Perhaps we should also allow for some minimum padding.
if (menu_width > anchor_rect.width() - handle_image_size.width())
adjusted_anchor_rect.Inset(
gfx::Insets::TLBR(0, 0, -handle_image_size.height(), 0));
SetAnchorRect(adjusted_anchor_rect);
BubbleDialogDelegateView::CreateBubble(this);
Widget* widget = GetWidget();
gfx::Rect bounds = widget->GetWindowBoundsInScreen();
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestPoint(bounds.origin())
.work_area();
if (!work_area.IsEmpty()) {
bounds.AdjustToFit(work_area);
widget->SetBounds(bounds);
}
// Using BubbleDialogDelegateView engages its CreateBubbleWidget() which
// invokes widget->StackAbove(context). That causes the bubble to stack
// _immediately_ above |context|; below any already-existing bubbles. That
// doesn't make sense for a menu, so put it back on top.
if (base::FeatureList::IsEnabled(features::kWidgetLayering))
widget->SetZOrderLevel(ui::ZOrderLevel::kFloatingWindow);
else
widget->StackAtTop();
widget->Show();
}
bool TouchSelectionMenuViews::IsMenuAvailable(
const ui::TouchSelectionMenuClient* client) {
DCHECK(client);
const auto is_enabled = [client](MenuCommand command) {
return client->IsCommandIdEnabled(command.command_id);
};
bool is_available = base::ranges::any_of(kMenuCommands, is_enabled);
is_available |= ::features::IsTouchTextEditingRedesignEnabled() &&
base::ranges::any_of(kMenuSelectCommands, is_enabled);
return is_available;
}
void TouchSelectionMenuViews::CloseMenu() {
if (owner_)
DisconnectOwner();
// Closing the widget will self-destroy this object.
Widget* widget = GetWidget();
if (widget && !widget->IsClosed())
widget->Close();
}
TouchSelectionMenuViews::~TouchSelectionMenuViews() = default;
void TouchSelectionMenuViews::CreateButtons() {
DCHECK(client_);
for (const auto& command : kMenuCommands) {
if (client_->IsCommandIdEnabled(command.command_id)) {
CreateButton(
l10n_util::GetStringUTF16(command.message_id),
base::BindRepeating(&TouchSelectionMenuViews::ButtonPressed,
base::Unretained(this), command.command_id));
}
}
if (::features::IsTouchTextEditingRedesignEnabled()) {
for (const auto& command : kMenuSelectCommands) {
if (client_->IsCommandIdEnabled(command.command_id)) {
CreateButton(
l10n_util::GetStringUTF16(command.message_id),
base::BindRepeating(&TouchSelectionMenuViews::ButtonPressed,
base::Unretained(this), command.command_id));
}
}
}
// Finally, add ellipsis button.
CreateButton(u"...",
base::BindRepeating(&TouchSelectionMenuViews::EllipsisPressed,
base::Unretained(this)))
->SetID(ButtonViewId::kEllipsisButton);
InvalidateLayout();
}
LabelButton* TouchSelectionMenuViews::CreateButton(
const std::u16string& title,
Button::PressedCallback callback) {
std::u16string label = gfx::RemoveAccelerator(title);
auto* button = AddChildView(std::make_unique<LabelButton>(
std::move(callback), label, style::CONTEXT_TOUCH_MENU));
constexpr gfx::Size kMenuButtonMinSize = gfx::Size(63, 38);
button->SetMinSize(kMenuButtonMinSize);
button->SetHorizontalAlignment(gfx::ALIGN_CENTER);
return button;
}
void TouchSelectionMenuViews::DisconnectOwner() {
DCHECK(owner_);
owner_->menu_ = nullptr;
owner_ = nullptr;
}
void TouchSelectionMenuViews::OnPaint(gfx::Canvas* canvas) {
BubbleDialogDelegateView::OnPaint(canvas);
if (children().empty())
return;
// Draw separator bars.
for (auto i = children().cbegin(); i != std::prev(children().cend()); ++i) {
const View* child = *i;
int x = child->bounds().right() + kSpacingBetweenButtons / 2;
canvas->FillRect(gfx::Rect(x, 0, 1, child->height()),
GetColorProvider()->GetColor(ui::kColorSeparator));
}
}
void TouchSelectionMenuViews::WindowClosing() {
DCHECK(!owner_ || owner_->menu_ == this);
BubbleDialogDelegateView::WindowClosing();
if (owner_)
DisconnectOwner();
}
void TouchSelectionMenuViews::ButtonPressed(int command,
const ui::Event& event) {
DCHECK(client_);
CloseMenu();
client_->ExecuteCommand(command, event.flags());
}
void TouchSelectionMenuViews::EllipsisPressed(const ui::Event& event) {
DCHECK(client_);
CloseMenu();
client_->RunContextMenu();
}
BEGIN_METADATA(TouchSelectionMenuViews, BubbleDialogDelegateView)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_menu_views.cc | C++ | unknown | 7,882 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TOUCHUI_TOUCH_SELECTION_MENU_VIEWS_H_
#define UI_VIEWS_TOUCHUI_TOUCH_SELECTION_MENU_VIEWS_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/touchui/touch_selection_menu_runner_views.h"
namespace ui {
class TouchSelectionMenuClient;
} // namespace ui
namespace views {
class LabelButton;
// A bubble that contains actions available for the selected text. An object of
// this type, as a BubbleDialogDelegateView, manages its own lifetime.
class VIEWS_EXPORT TouchSelectionMenuViews : public BubbleDialogDelegateView {
public:
METADATA_HEADER(TouchSelectionMenuViews);
enum ButtonViewId : int { kEllipsisButton = 1 };
TouchSelectionMenuViews(TouchSelectionMenuRunnerViews* owner,
base::WeakPtr<ui::TouchSelectionMenuClient> client,
aura::Window* context);
TouchSelectionMenuViews(const TouchSelectionMenuViews&) = delete;
TouchSelectionMenuViews& operator=(const TouchSelectionMenuViews&) = delete;
void ShowMenu(const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size);
// Checks whether there is any command available to show in the menu.
static bool IsMenuAvailable(const ui::TouchSelectionMenuClient* client);
// Closes the menu. This will eventually self-destroy the object.
void CloseMenu();
protected:
~TouchSelectionMenuViews() override;
// Queries the |client_| for what commands to show in the menu and sizes the
// menu appropriately.
virtual void CreateButtons();
// Helper method to create a single button.
LabelButton* CreateButton(const std::u16string& title,
Button::PressedCallback callback);
private:
friend class TouchSelectionMenuRunnerViews::TestApi;
void ButtonPressed(int command, const ui::Event& event);
void EllipsisPressed(const ui::Event& event);
// Helper to disconnect this menu object from its owning menu runner.
void DisconnectOwner();
// BubbleDialogDelegateView:
void OnPaint(gfx::Canvas* canvas) override;
void WindowClosing() override;
raw_ptr<TouchSelectionMenuRunnerViews> owner_;
const base::WeakPtr<ui::TouchSelectionMenuClient> client_;
};
} // namespace views
#endif // UI_VIEWS_TOUCHUI_TOUCH_SELECTION_MENU_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/touchui/touch_selection_menu_views.h | C++ | unknown | 2,465 |
// 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/view.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/functional/callback_helpers.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/observer_list.h"
#include "base/ranges/algorithm.h"
#include "base/scoped_observation.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkRect.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_id_forward.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_provider_manager.h"
#include "ui/compositor/clip_recorder.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/paint_context.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/compositor/transform_recorder.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event_target_iterator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/angle_conversions.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/interpolated_transform.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/accessibility/accessibility_paint_checks.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/buildflags.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/drag_controller.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_observer.h"
#include "ui/views/view_tracker.h"
#include "ui/views/view_utils.h"
#include "ui/views/views_features.h"
#include "ui/views/views_switches.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "ui/native_theme/native_theme_win.h"
#endif
namespace views {
namespace {
#if BUILDFLAG(IS_WIN)
constexpr bool kContextMenuOnMousePress = false;
#else
constexpr bool kContextMenuOnMousePress = true;
#endif
// Having UseDefaultFillLayout true by default wreaks a bit of havoc right now,
// so it is false for the time being. Once the various sites which currently use
// FillLayout are converted to using this and the other places that either
// override Layout() or do nothing are also validated, this can be switched to
// true.
constexpr bool kUseDefaultFillLayout = false;
// Default horizontal drag threshold in pixels.
// Same as what gtk uses.
constexpr int kDefaultHorizontalDragThreshold = 8;
// Default vertical drag threshold in pixels.
// Same as what gtk uses.
constexpr int kDefaultVerticalDragThreshold = 8;
// The following are used to offset the keys for the callbacks associated with
// the bounds element callbacks.
constexpr int kXChangedKey = sizeof(int) * 0;
constexpr int kYChangedKey = sizeof(int) * 1;
constexpr int kWidthChangedKey = sizeof(int) * 2;
constexpr int kHeightChangedKey = sizeof(int) * 3;
// Returns the top view in |view|'s hierarchy.
const View* GetHierarchyRoot(const View* view) {
const View* root = view;
while (root && root->parent())
root = root->parent();
return root;
}
} // namespace
namespace internal {
#if DCHECK_IS_ON()
class ScopedChildrenLock {
public:
explicit ScopedChildrenLock(const View* view)
: reset_(&view->iterating_, true) {}
ScopedChildrenLock(const ScopedChildrenLock&) = delete;
ScopedChildrenLock& operator=(const ScopedChildrenLock&) = delete;
~ScopedChildrenLock() = default;
private:
base::AutoReset<bool> reset_;
};
#else
class ScopedChildrenLock {
public:
explicit ScopedChildrenLock(const View* view) {}
~ScopedChildrenLock() {}
};
#endif
} // namespace internal
////////////////////////////////////////////////////////////////////////////////
// ViewMaskLayer
// This class is responsible for creating a masking layer for a view that paints
// to a layer. It tracks the size of the layer it is masking.
class VIEWS_EXPORT ViewMaskLayer : public ui::LayerDelegate,
public ViewObserver {
public:
// Note that |observed_view| must outlive the ViewMaskLayer instance.
ViewMaskLayer(const SkPath& path, View* observed_view);
ViewMaskLayer(const ViewMaskLayer& mask_layer) = delete;
ViewMaskLayer& operator=(const ViewMaskLayer& mask_layer) = delete;
~ViewMaskLayer() override;
ui::Layer* layer() { return &layer_; }
private:
// ui::LayerDelegate:
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
void OnPaintLayer(const ui::PaintContext& context) override;
// views::ViewObserver:
void OnViewBoundsChanged(View* observed_view) override;
base::ScopedObservation<View, ViewObserver> observed_view_{this};
SkPath path_;
ui::Layer layer_;
};
ViewMaskLayer::ViewMaskLayer(const SkPath& path, View* observed_view)
: path_{path} {
layer_.set_delegate(this);
layer_.SetFillsBoundsOpaquely(false);
layer_.SetName("ViewMaskLayer");
observed_view_.Observe(observed_view);
OnViewBoundsChanged(observed_view);
}
ViewMaskLayer::~ViewMaskLayer() {
layer_.set_delegate(nullptr);
}
void ViewMaskLayer::OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {}
void ViewMaskLayer::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);
}
void ViewMaskLayer::OnViewBoundsChanged(View* observed_view) {
layer_.SetBounds(observed_view->GetLocalBounds());
}
////////////////////////////////////////////////////////////////////////////////
// View, public:
// Creation and lifetime -------------------------------------------------------
View::View() {
SetTargetHandler(this);
if (kUseDefaultFillLayout)
default_fill_layout_.emplace(DefaultFillLayout());
static bool capture_stack_trace =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kViewStackTraces);
if (capture_stack_trace) {
SetProperty(kViewStackTraceKey,
std::make_unique<base::debug::StackTrace>());
}
ax_node_data_ = std::make_unique<ui::AXNodeData>();
}
View::~View() {
life_cycle_state_ = LifeCycleState::kDestroying;
if (parent_)
parent_->RemoveChildView(this);
// This view should have been removed from the focus list by now.
DCHECK_EQ(next_focusable_view_, nullptr);
DCHECK_EQ(previous_focusable_view_, nullptr);
// Need to remove layout manager before deleting children because if we do not
// it is possible for layout-related calls (e.g. CalculatePreferredSize()) to
// be called on this view during one of the callbacks below. Since most
// layout managers access child view properties, this would result in a
// use-after-free error.
layout_manager_.reset();
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
child->parent_ = nullptr;
// Remove any references to |child| to avoid holding a dangling ptr.
if (child->previous_focusable_view_)
child->previous_focusable_view_->next_focusable_view_ = nullptr;
if (child->next_focusable_view_)
child->next_focusable_view_->previous_focusable_view_ = nullptr;
// Since all children are removed here, it is safe to set
// |child|'s focus list pointers to null and expect any references
// to |child| will be removed subsequently.
child->next_focusable_view_ = nullptr;
child->previous_focusable_view_ = nullptr;
if (!child->owned_by_client_)
delete child;
}
// Clear `children_` to prevent UAFs from observers and properties that may
// end up looking at children(), directly or indirectly, before ~View() goes
// out of scope.
children_.clear();
}
for (ViewObserver& observer : observers_)
observer.OnViewIsDeleting(this);
for (ui::Layer* layer : GetLayersInOrder(ViewLayer::kExclude)) {
layer->RemoveObserver(this);
}
// Clearing properties explicitly here lets us guarantee that properties
// outlive |this| (at least the View part of |this|). This is intentionally
// called at the end so observers can examine properties inside
// OnViewIsDeleting(), for instance.
ClearProperties();
life_cycle_state_ = LifeCycleState::kDestroyed;
}
// Tree operations -------------------------------------------------------------
const Widget* View::GetWidget() const {
// The root view holds a reference to this view hierarchy's Widget.
return parent_ ? parent_->GetWidget() : nullptr;
}
Widget* View::GetWidget() {
return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
}
void View::ReorderChildView(View* view, size_t index) {
DCHECK_EQ(view->parent_, this);
const auto i = base::ranges::find(children_, view);
DCHECK(i != children_.end());
// If |view| is already at the desired position, there's nothing to do.
const auto pos =
std::next(children_.begin(),
static_cast<ptrdiff_t>(std::min(index, children_.size() - 1)));
if (i == pos)
return;
// Rotate |view| to be at the desired position.
#if DCHECK_IS_ON()
DCHECK(!iterating_);
#endif
if (pos < i)
std::rotate(pos, i, std::next(i));
else
std::rotate(i, std::next(i), std::next(pos));
// Update focus siblings. Unhook |view| from the focus cycle first so
// SetFocusSiblings() won't traverse through it.
view->RemoveFromFocusList();
SetFocusSiblings(view, pos);
for (ViewObserver& observer : observers_)
observer.OnChildViewReordered(this, view);
ReorderLayers();
InvalidateLayout();
}
void View::RemoveChildView(View* view) {
DoRemoveChildView(view, true, false, nullptr);
}
void View::RemoveAllChildViews() {
while (!children_.empty())
DoRemoveChildView(children_.front(), false, true, nullptr);
UpdateTooltip();
}
void View::RemoveAllChildViewsWithoutDeleting() {
while (!children_.empty())
DoRemoveChildView(children_.front(), false, false, nullptr);
UpdateTooltip();
}
bool View::Contains(const View* view) const {
for (const View* v = view; v; v = v->parent_) {
if (v == this)
return true;
}
return false;
}
View::Views::const_iterator View::FindChild(const View* view) const {
return base::ranges::find(children_, view);
}
absl::optional<size_t> View::GetIndexOf(const View* view) const {
const auto i = FindChild(view);
return i == children_.cend() ? absl::nullopt
: absl::make_optional(static_cast<size_t>(
std::distance(children_.cbegin(), i)));
}
// Size and disposition --------------------------------------------------------
void View::SetBounds(int x, int y, int width, int height) {
SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
}
void View::SetBoundsRect(const gfx::Rect& bounds) {
if (bounds == bounds_) {
if (needs_layout_) {
needs_layout_ = false;
TRACE_EVENT1("views", "View::Layout(set_bounds)", "class",
GetClassName());
Layout();
}
return;
}
bool is_size_changed = bounds_.size() != bounds.size();
// Paint where the view is currently.
SchedulePaintBoundsChanged(is_size_changed);
gfx::Rect prev = bounds_;
bounds_ = bounds;
// Paint the new bounds.
SchedulePaintBoundsChanged(is_size_changed);
if (layer()) {
if (parent_) {
LayerOffsetData offset_data(
parent_->CalculateOffsetToAncestorWithLayer(nullptr));
offset_data += GetMirroredPosition().OffsetFromOrigin();
SetLayerBounds(size(), offset_data);
} else {
SetLayerBounds(bounds_.size(),
LayerOffsetData() + bounds_.OffsetFromOrigin());
}
// In RTL mode, if our width has changed, our children's mirrored bounds
// will have changed. Update the child's layer bounds, or if it is not a
// layer, the bounds of any layers inside the child.
if (GetMirrored() && bounds_.width() != prev.width()) {
for (View* child : children_) {
child->UpdateChildLayerBounds(
LayerOffsetData(layer()->device_scale_factor(),
child->GetMirroredPosition().OffsetFromOrigin()));
}
}
} else {
// If our bounds have changed, then any descendant layer bounds may have
// changed. Update them accordingly.
UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(nullptr));
}
OnBoundsChanged(prev);
NotifyAccessibilityEvent(ax::mojom::Event::kLocationChanged, false);
if (needs_layout_ || is_size_changed) {
needs_layout_ = false;
TRACE_EVENT1("views", "View::Layout(bounds_changed)", "class",
GetClassName());
Layout();
}
if (GetNeedsNotificationWhenVisibleBoundsChange())
OnVisibleBoundsChanged();
// Notify interested Views that visible bounds within the root view may have
// changed.
if (descendants_to_notify_) {
for (auto* i : *descendants_to_notify_) {
i->OnVisibleBoundsChanged();
}
}
for (ViewObserver& observer : observers_)
observer.OnViewBoundsChanged(this);
// The property effects have already been taken into account above. No need to
// redo them here.
if (prev.x() != bounds_.x())
OnPropertyChanged(&bounds_ + kXChangedKey, kPropertyEffectsNone);
if (prev.y() != bounds_.y())
OnPropertyChanged(&bounds_ + kYChangedKey, kPropertyEffectsNone);
if (prev.width() != bounds_.width())
OnPropertyChanged(&bounds_ + kWidthChangedKey, kPropertyEffectsNone);
if (prev.height() != bounds_.height())
OnPropertyChanged(&bounds_ + kHeightChangedKey, kPropertyEffectsNone);
}
void View::SetSize(const gfx::Size& size) {
SetBounds(x(), y(), size.width(), size.height());
}
void View::SetPosition(const gfx::Point& position) {
SetBounds(position.x(), position.y(), width(), height());
}
void View::SetX(int x) {
SetBounds(x, y(), width(), height());
}
void View::SetY(int y) {
SetBounds(x(), y, width(), height());
}
gfx::Rect View::GetContentsBounds() const {
gfx::Rect contents_bounds(GetLocalBounds());
contents_bounds.Inset(GetInsets());
return contents_bounds;
}
gfx::Rect View::GetLocalBounds() const {
return gfx::Rect(size());
}
gfx::Insets View::GetInsets() const {
return border_ ? border_->GetInsets() : gfx::Insets();
}
gfx::Rect View::GetVisibleBounds() const {
if (!IsDrawn())
return gfx::Rect();
gfx::Rect vis_bounds(GetLocalBounds());
gfx::Rect ancestor_bounds;
const View* view = this;
gfx::Transform transform;
while (view != nullptr && !vis_bounds.IsEmpty()) {
transform.PostConcat(view->GetTransform());
gfx::Transform translation;
translation.Translate(static_cast<float>(view->GetMirroredX()),
static_cast<float>(view->y()));
transform.PostConcat(translation);
vis_bounds = view->ConvertRectToParent(vis_bounds);
const View* ancestor = view->parent_;
if (ancestor != nullptr) {
ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
vis_bounds.Intersect(ancestor_bounds);
} else if (!view->GetWidget()) {
// If the view has no Widget, we're not visible. Return an empty rect.
return gfx::Rect();
}
view = ancestor;
}
if (vis_bounds.IsEmpty())
return vis_bounds;
// Convert back to this views coordinate system. This mapping returns the
// enclosing rect, which is good because partially visible pixels should
// be considered visible.
return transform.InverseMapRect(vis_bounds).value_or(vis_bounds);
}
gfx::Rect View::GetBoundsInScreen() const {
gfx::Point origin;
View::ConvertPointToScreen(this, &origin);
return gfx::Rect(origin, size());
}
gfx::Rect View::GetAnchorBoundsInScreen() const {
return GetBoundsInScreen();
}
gfx::Size View::GetPreferredSize() const {
if (preferred_size_)
return *preferred_size_;
return CalculatePreferredSize();
}
gfx::Size View::GetPreferredSize(const SizeBounds& available_size) const {
if (preferred_size_)
return *preferred_size_;
return CalculatePreferredSize(available_size);
}
int View::GetBaseline() const {
return -1;
}
void View::SetPreferredSize(absl::optional<gfx::Size> size) {
if (preferred_size_ == size)
return;
preferred_size_ = std::move(size);
PreferredSizeChanged();
}
void View::SizeToPreferredSize() {
SetSize(GetPreferredSize());
}
gfx::Size View::GetMinimumSize() const {
if (HasLayoutManager())
return GetLayoutManager()->GetMinimumSize(this);
return GetPreferredSize();
}
gfx::Size View::GetMaximumSize() const {
return gfx::Size();
}
int View::GetHeightForWidth(int w) const {
if (HasLayoutManager())
return GetLayoutManager()->GetPreferredHeightForWidth(this, w);
return GetPreferredSize().height();
}
SizeBounds View::GetAvailableSize(const View* child) const {
if (HasLayoutManager())
return GetLayoutManager()->GetAvailableSize(this, child);
return SizeBounds();
}
bool View::GetVisible() const {
return visible_;
}
void View::SetVisible(bool visible) {
const bool was_visible = visible_;
if (was_visible != visible) {
// If the View was visible, schedule paint to refresh parent.
// TODO(beng): not sure we should be doing this if we have a layer.
if (was_visible)
SchedulePaint();
visible_ = visible;
AdvanceFocusIfNecessary();
// Notify the parent.
if (parent_) {
parent_->ChildVisibilityChanged(this);
if (!view_accessibility_ || !view_accessibility_->IsIgnored()) {
parent_->NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged,
true);
}
}
// This notifies all sub-views recursively.
PropagateVisibilityNotifications(this, visible_);
UpdateLayerVisibility();
// Notify all other subscriptions of the change.
OnPropertyChanged(&visible_, kPropertyEffectsPaint);
if (was_visible)
UpdateTooltip();
}
if (parent_) {
LayoutManager* const layout_manager = parent_->GetLayoutManager();
if (layout_manager && layout_manager->view_setting_visibility_on_ != this)
layout_manager->ViewVisibilitySet(parent_, this, was_visible, visible);
}
}
base::CallbackListSubscription View::AddVisibleChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&visible_, std::move(callback));
}
bool View::IsDrawn() const {
return visible_ && parent_ ? parent_->IsDrawn() : false;
}
bool View::GetIsDrawn() const {
return IsDrawn();
}
bool View::GetEnabled() const {
return enabled_;
}
void View::SetEnabled(bool enabled) {
if (enabled_ == enabled)
return;
enabled_ = enabled;
AdvanceFocusIfNecessary();
// TODO(crbug.com/1421682): We need a specific enabled-changed event for this.
// Some platforms have specific state-changed events and this generic event
// does not suggest what changed.
NotifyAccessibilityEvent(ax::mojom::Event::kStateChanged, true);
OnPropertyChanged(&enabled_, kPropertyEffectsPaint);
}
base::CallbackListSubscription View::AddEnabledChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&enabled_, std::move(callback));
}
View::Views View::GetChildrenInZOrder() {
if (HasLayoutManager()) {
const auto result = GetLayoutManager()->GetChildViewsInPaintOrder(this);
DCHECK_EQ(children_.size(), result.size());
return result;
}
return children_;
}
// Transformations -------------------------------------------------------------
gfx::Transform View::GetTransform() const {
if (!layer())
return gfx::Transform();
gfx::Transform transform = layer()->transform();
gfx::PointF scroll_offset = layer()->CurrentScrollOffset();
// Offsets for layer-based scrolling are never negative, but the horizontal
// scroll direction is reversed in RTL via canvas flipping.
transform.Translate((GetMirrored() ? 1 : -1) * scroll_offset.x(),
-scroll_offset.y());
return transform;
}
void View::SetClipPath(const SkPath& path) {
clip_path_ = path;
if (layer())
CreateMaskLayer();
}
void View::SetTransform(const gfx::Transform& transform) {
if (transform.IsIdentity()) {
if (layer())
layer()->SetTransform(transform);
paint_to_layer_for_transform_ = false;
CreateOrDestroyLayer();
} else {
paint_to_layer_for_transform_ = true;
CreateOrDestroyLayer();
DCHECK_NE(layer(), nullptr);
layer()->SetTransform(transform);
layer()->ScheduleDraw();
}
for (ui::Layer* layer : GetLayersInOrder(ViewLayer::kExclude)) {
layer->SetTransform(transform);
}
}
void View::SetPaintToLayer(ui::LayerType layer_type) {
// Avoid re-creating the layer if unnecessary.
if (paint_to_layer_explicitly_set_) {
DCHECK_NE(layer(), nullptr);
if (layer()->type() == layer_type)
return;
}
DestroyLayerImpl(LayerChangeNotifyBehavior::DONT_NOTIFY);
paint_to_layer_explicitly_set_ = true;
// We directly call |CreateLayer()| here to pass |layer_type|. A call to
// |CreateOrDestroyLayer()| is therefore not necessary.
CreateLayer(layer_type);
if (!clip_path_.isEmpty() && !mask_layer_)
CreateMaskLayer();
// Notify the parent chain about the layer change.
NotifyParentsOfLayerChange();
}
void View::DestroyLayer() {
paint_to_layer_explicitly_set_ = false;
CreateOrDestroyLayer();
}
void View::AddLayerToRegion(ui::Layer* new_layer, LayerRegion region) {
AddLayerToRegionImpl(
new_layer, region == LayerRegion::kAbove ? layers_above_ : layers_below_);
}
void View::RemoveLayerFromRegions(ui::Layer* old_layer) {
RemoveLayerFromRegionsKeepInLayerTree(old_layer);
// Note that |old_layer| may have already been removed from its parent.
ui::Layer* parent_layer = layer()->parent();
if (parent_layer && parent_layer == old_layer->parent())
parent_layer->Remove(old_layer);
CreateOrDestroyLayer();
}
void View::RemoveLayerFromRegionsKeepInLayerTree(ui::Layer* old_layer) {
auto remove_layer = [old_layer, this](std::vector<ui::Layer*>& layer_vector) {
auto layer_pos = base::ranges::find(layer_vector, old_layer);
if (layer_pos == layer_vector.end()) {
return false;
}
layer_vector.erase(layer_pos);
old_layer->RemoveObserver(this);
return true;
};
const bool layer_removed =
remove_layer(layers_below_) || remove_layer(layers_above_);
DCHECK(layer_removed) << "Attempted to remove a layer that was never added.";
}
std::vector<ui::Layer*> View::GetLayersInOrder(ViewLayer view_layer) {
// If not painting to a layer, there are no layers immediately related to this
// view.
if (!layer()) {
// If there is no View layer, there should be no layers above or below.
DCHECK(layers_above_.empty() && layers_below_.empty());
return {};
}
std::vector<ui::Layer*> result;
for (ui::Layer* layer_below : layers_below_) {
result.push_back(layer_below);
}
if (view_layer == ViewLayer::kInclude) {
result.push_back(layer());
}
for (auto* layer_above : layers_above_) {
result.push_back(layer_above);
}
return result;
}
void View::LayerDestroyed(ui::Layer* layer) {
// Only layers added with |AddLayerToRegion()| or |AddLayerAboveView()|
// are observed so |layer| can safely be removed.
RemoveLayerFromRegions(layer);
}
std::unique_ptr<ui::Layer> View::RecreateLayer() {
std::unique_ptr<ui::Layer> old_layer = LayerOwner::RecreateLayer();
Widget* widget = GetWidget();
if (widget)
widget->LayerTreeChanged();
return old_layer;
}
// RTL positioning -------------------------------------------------------------
gfx::Rect View::GetMirroredBounds() const {
gfx::Rect bounds(bounds_);
bounds.set_x(GetMirroredX());
return bounds;
}
gfx::Rect View::GetMirroredContentsBounds() const {
gfx::Rect bounds(bounds_);
bounds.Inset(GetInsets());
bounds.set_x(GetMirroredX());
return bounds;
}
gfx::Point View::GetMirroredPosition() const {
return gfx::Point(GetMirroredX(), y());
}
int View::GetMirroredX() const {
return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
}
int View::GetMirroredXForRect(const gfx::Rect& rect) const {
return GetMirrored() ? (width() - rect.x() - rect.width()) : rect.x();
}
gfx::Rect View::GetMirroredRect(const gfx::Rect& rect) const {
gfx::Rect mirrored_rect = rect;
mirrored_rect.set_x(GetMirroredXForRect(rect));
return mirrored_rect;
}
int View::GetMirroredXInView(int x) const {
return GetMirrored() ? width() - x : x;
}
int View::GetMirroredXWithWidthInView(int x, int w) const {
return GetMirrored() ? width() - x - w : x;
}
// Layout ----------------------------------------------------------------------
void View::Layout() {
needs_layout_ = false;
// If we have a layout manager, let it handle the layout for us.
if (HasLayoutManager())
GetLayoutManager()->Layout(this);
// Make sure to propagate the Layout() call to any children that haven't
// received it yet through the layout manager and need to be laid out. This
// is needed for the case when the child requires a layout but its bounds
// weren't changed by the layout manager. If there is no layout manager, we
// just propagate the Layout() call down the hierarchy, so whoever receives
// the call can take appropriate action.
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
if (child->needs_layout_ || !HasLayoutManager()) {
TRACE_EVENT1("views", "View::LayoutChildren", "class",
child->GetClassName());
child->needs_layout_ = false;
child->Layout();
}
}
}
void View::InvalidateLayout() {
// Always invalidate up. This is needed to handle the case of us already being
// valid, but not our parent.
needs_layout_ = true;
if (HasLayoutManager())
GetLayoutManager()->InvalidateLayout();
if (parent_) {
parent_->InvalidateLayout();
} else {
Widget* widget = GetWidget();
if (widget)
widget->ScheduleLayout();
}
}
LayoutManager* View::GetLayoutManager() const {
if (layout_manager_)
return layout_manager_.get();
if (default_fill_layout_.has_value())
return &const_cast<View*>(this)->default_fill_layout_.value();
return nullptr;
}
void View::SetLayoutManager(std::nullptr_t) {
SetLayoutManagerImpl(nullptr);
}
bool View::GetUseDefaultFillLayout() const {
if (layout_manager_)
return false;
return default_fill_layout_.has_value();
}
void View::SetUseDefaultFillLayout(bool value) {
if (value == default_fill_layout_.has_value())
return;
if (value) {
default_fill_layout_.emplace(DefaultFillLayout());
// Kill the currently assigned layout manager if one had been assigned.
layout_manager_.reset();
} else {
default_fill_layout_.reset();
}
OnPropertyChanged(&default_fill_layout_, kPropertyEffectsLayout);
}
// Attributes ------------------------------------------------------------------
const View* View::GetViewByID(int id) const {
if (id == id_)
return const_cast<View*>(this);
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
const View* view = child->GetViewByID(id);
if (view)
return view;
}
return nullptr;
}
View* View::GetViewByID(int id) {
return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
}
void View::SetID(int id) {
if (id == id_)
return;
id_ = id;
OnPropertyChanged(&id_, kPropertyEffectsNone);
}
base::CallbackListSubscription View::AddIDChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&id_, callback);
}
void View::SetGroup(int gid) {
// Don't change the group id once it's set.
DCHECK(group_ == -1 || group_ == gid);
if (group_ != gid) {
group_ = gid;
OnPropertyChanged(&group_, kPropertyEffectsNone);
}
}
int View::GetGroup() const {
return group_;
}
base::CallbackListSubscription View::AddGroupChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&group_, callback);
}
bool View::IsGroupFocusTraversable() const {
return true;
}
void View::GetViewsInGroup(int group, Views* views) {
if (group_ == group)
views->push_back(this);
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->GetViewsInGroup(group, views);
}
View* View::GetSelectedViewForGroup(int group) {
Views views;
GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
return views.empty() ? nullptr : views[0];
}
// Coordinate conversion -------------------------------------------------------
// static
void View::ConvertPointToTarget(const View* source,
const View* target,
gfx::Point* point) {
DCHECK(source);
DCHECK(target);
if (source == target)
return;
const View* root = GetHierarchyRoot(target);
#if BUILDFLAG(IS_MAC)
// If the root views don't match make sure we are in the same widget tree.
// Full screen in macOS creates a child widget that hosts top chrome.
// TODO(bur): Remove this check when top chrome can be composited into its own
// NSView without the need for a new widget.
if (GetHierarchyRoot(source) != root) {
const Widget* source_top_level_widget =
source->GetWidget()->GetTopLevelWidget();
const Widget* target_top_level_widget =
target->GetWidget()->GetTopLevelWidget();
CHECK_EQ(source_top_level_widget, target_top_level_widget);
}
#else // IS_MAC
CHECK_EQ(GetHierarchyRoot(source), root);
#endif
if (source != root)
source->ConvertPointForAncestor(root, point);
if (target != root)
target->ConvertPointFromAncestor(root, point);
}
// static
gfx::Point View::ConvertPointToTarget(const View* source,
const View* target,
const gfx::Point& point) {
gfx::Point local_point = point;
ConvertPointToTarget(source, target, &local_point);
return local_point;
}
// static
void View::ConvertRectToTarget(const View* source,
const View* target,
gfx::RectF* rect) {
DCHECK(source);
DCHECK(target);
if (source == target)
return;
const View* root = GetHierarchyRoot(target);
CHECK_EQ(GetHierarchyRoot(source), root);
if (source != root)
source->ConvertRectForAncestor(root, rect);
if (target != root)
target->ConvertRectFromAncestor(root, rect);
}
// static
gfx::RectF View::ConvertRectToTarget(const View* source,
const View* target,
const gfx::RectF& rect) {
gfx::RectF local_rect = rect;
ConvertRectToTarget(source, target, &local_rect);
return local_rect;
}
// static
gfx::Rect View::ConvertRectToTarget(const View* source,
const View* target,
gfx::Rect& rect) {
constexpr float kDefaultAllowedConversionError = 0.00001f;
return gfx::ToEnclosedRectIgnoringError(
ConvertRectToTarget(source, target, gfx::RectF(rect)),
kDefaultAllowedConversionError);
}
// static
void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
DCHECK(src);
DCHECK(p);
src->ConvertPointForAncestor(nullptr, p);
}
// static
void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
DCHECK(dest);
DCHECK(p);
dest->ConvertPointFromAncestor(nullptr, p);
}
// static
void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
DCHECK(src);
DCHECK(p);
// If the view is not connected to a tree, there's nothing we can do.
const Widget* widget = src->GetWidget();
if (widget) {
ConvertPointToWidget(src, p);
*p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
}
}
// static
gfx::Point View::ConvertPointToScreen(const View* src, const gfx::Point& p) {
gfx::Point screen_pt = p;
ConvertPointToScreen(src, &screen_pt);
return screen_pt;
}
// static
void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
DCHECK(dst);
DCHECK(p);
const views::Widget* widget = dst->GetWidget();
if (!widget)
return;
*p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
ConvertPointFromWidget(dst, p);
}
// static
gfx::Point View::ConvertPointFromScreen(const View* src, const gfx::Point& p) {
gfx::Point local_pt = p;
ConvertPointFromScreen(src, &local_pt);
return local_pt;
}
// static
void View::ConvertRectToScreen(const View* src, gfx::Rect* rect) {
DCHECK(src);
DCHECK(rect);
gfx::Point new_origin = rect->origin();
views::View::ConvertPointToScreen(src, &new_origin);
rect->set_origin(new_origin);
}
gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
// This mapping returns the enclosing rect, which is good because pixels that
// partially occupy in the parent should be included.
gfx::Rect x_rect = GetTransform().MapRect(rect);
x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
return x_rect;
}
gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
gfx::Rect x_rect = rect;
for (const View* v = this; v; v = v->parent_)
x_rect = v->ConvertRectToParent(x_rect);
return x_rect;
}
// Painting --------------------------------------------------------------------
void View::SchedulePaint() {
SchedulePaintInRect(GetLocalBounds());
}
void View::SchedulePaintInRect(const gfx::Rect& rect) {
needs_paint_ = true;
SchedulePaintInRectImpl(rect);
}
void View::Paint(const PaintInfo& parent_paint_info) {
CHECK_EQ(life_cycle_state_, LifeCycleState::kAlive);
if (!ShouldPaint())
return;
if (!has_run_accessibility_paint_checks_) {
RunAccessibilityPaintChecks(this);
has_run_accessibility_paint_checks_ = true;
}
const gfx::Rect& parent_bounds =
!parent() ? GetMirroredBounds() : parent()->GetMirroredBounds();
PaintInfo paint_info = PaintInfo::CreateChildPaintInfo(
parent_paint_info, GetMirroredBounds(), parent_bounds.size(),
GetPaintScaleType(), !!layer(), needs_paint_);
needs_paint_ = false;
const ui::PaintContext& context = paint_info.context();
bool is_invalidated = true;
if (paint_info.context().CanCheckInvalid() ||
base::FeatureList::IsEnabled(features::kEnableViewPaintOptimization)) {
// For View paint optimization, do not default to repainting every View in
// the View hierarchy if the invalidation rect is empty. Repainting does not
// depend on the invalidation rect for View paint optimization.
#if DCHECK_IS_ON()
if (!context.is_pixel_canvas()) {
gfx::Vector2d offset;
context.Visited(this);
View* view = this;
while (view->parent() && !view->layer()) {
DCHECK(view->GetTransform().IsIdentity());
offset += view->GetMirroredPosition().OffsetFromOrigin();
view = view->parent();
}
// The offset in the PaintContext should be the offset up to the paint
// root, which we compute and verify here.
DCHECK_EQ(context.PaintOffset().x(), offset.x());
DCHECK_EQ(context.PaintOffset().y(), offset.y());
// The above loop will stop when |view| is the paint root, which should be
// the root of the current paint walk, as verified by storing the root in
// the PaintContext.
DCHECK_EQ(context.RootVisited(), view);
}
#endif
// If the View wasn't invalidated, don't waste time painting it, the output
// would be culled.
is_invalidated = paint_info.ShouldPaint();
}
TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
// If the view is backed by a layer, it should paint with itself as the origin
// rather than relative to its parent.
// TODO(danakj): Rework clip and transform recorder usage here to use
// std::optional once we can do so.
ui::ClipRecorder clip_recorder(parent_paint_info.context());
if (!layer()) {
// Set the clip rect to the bounds of this View, or |clip_path_| if it's
// been set. Note that the X (or left) position we pass to ClipRect takes
// into consideration whether or not the View uses a right-to-left layout so
// that we paint the View in its mirrored position if need be.
if (clip_path_.isEmpty()) {
clip_recorder.ClipRect(gfx::Rect(paint_info.paint_recording_size()) +
paint_info.offset_from_parent());
} else {
SkPath clip_path_in_parent = clip_path_;
// Transform |clip_path_| from local space to parent recording space.
gfx::Transform to_parent_recording_space;
to_parent_recording_space.Translate(paint_info.offset_from_parent());
to_parent_recording_space.Scale(
SkFloatToScalar(paint_info.paint_recording_scale_x()),
SkFloatToScalar(paint_info.paint_recording_scale_y()));
clip_path_in_parent.transform(
gfx::TransformToFlattenedSkMatrix(to_parent_recording_space));
clip_recorder.ClipPathWithAntiAliasing(clip_path_in_parent);
}
}
ui::TransformRecorder transform_recorder(context);
SetUpTransformRecorderForPainting(paint_info.offset_from_parent(),
&transform_recorder);
// Note that the cache is not aware of the offset of the view
// relative to the parent since painting is always done relative to
// the top left of the individual view.
if (is_invalidated ||
!paint_cache_.UseCache(context, paint_info.paint_recording_size())) {
ui::PaintRecorder recorder(context, paint_info.paint_recording_size(),
paint_info.paint_recording_scale_x(),
paint_info.paint_recording_scale_y(),
&paint_cache_);
gfx::Canvas* canvas = recorder.canvas();
gfx::ScopedCanvas scoped_canvas(canvas);
if (flip_canvas_on_paint_for_rtl_ui_)
scoped_canvas.FlipIfRTL(width());
// Delegate painting the contents of the View to the virtual OnPaint method.
OnPaint(canvas);
}
CHECK_EQ(life_cycle_state_, LifeCycleState::kAlive);
// View::Paint() recursion over the subtree.
PaintChildren(paint_info);
}
void View::SetBackground(std::unique_ptr<Background> b) {
background_ = std::move(b);
if (background_ && GetWidget())
background_->OnViewThemeChanged(this);
SchedulePaint();
}
Background* View::GetBackground() const {
return background_.get();
}
void View::SetBorder(std::unique_ptr<Border> b) {
const gfx::Rect old_contents_bounds = GetContentsBounds();
border_ = std::move(b);
if (border_ && GetWidget())
border_->OnViewThemeChanged(this);
// Conceptually, this should be PreferredSizeChanged(), but for some view
// hierarchies that triggers synchronous add/remove operations that are unsafe
// in some contexts where SetBorder is called.
//
// InvalidateLayout() still triggers a re-layout of the view, which should
// include re-querying its preferred size so in practice this is both safe and
// has the intended effect.
if (old_contents_bounds != GetContentsBounds())
InvalidateLayout();
SchedulePaint();
}
Border* View::GetBorder() const {
return border_.get();
}
const ui::ThemeProvider* View::GetThemeProvider() const {
const auto* widget = GetWidget();
return widget ? widget->GetThemeProvider() : nullptr;
}
const LayoutProvider* View::GetLayoutProvider() const {
if (!GetWidget())
return nullptr;
// TODO(pbos): Ask the widget for a layout provider.
return LayoutProvider::Get();
}
const ui::ColorProvider* View::GetColorProvider() const {
const auto* widget = GetWidget();
return widget ? widget->GetColorProvider() : nullptr;
}
const ui::NativeTheme* View::GetNativeTheme() const {
if (native_theme_)
return native_theme_;
if (parent())
return parent()->GetNativeTheme();
const Widget* widget = GetWidget();
if (widget)
return widget->GetNativeTheme();
static bool has_crashed_reported = false;
// Crash on debug builds and dump without crashing on release builds to ensure
// we catch fallthrough to the global NativeTheme instance on all Chromium
// builds (crbug.com/1056756).
if (!has_crashed_reported) {
DCHECK(false);
base::debug::DumpWithoutCrashing();
has_crashed_reported = true;
}
return ui::NativeTheme::GetInstanceForNativeUi();
}
void View::SetNativeThemeForTesting(ui::NativeTheme* theme) {
ui::NativeTheme* original_native_theme = GetNativeTheme();
native_theme_ = theme;
if (native_theme_ != original_native_theme)
PropagateThemeChanged();
}
// RTL painting ----------------------------------------------------------------
bool View::GetFlipCanvasOnPaintForRTLUI() const {
return flip_canvas_on_paint_for_rtl_ui_;
}
void View::SetFlipCanvasOnPaintForRTLUI(bool enable) {
if (enable == flip_canvas_on_paint_for_rtl_ui_)
return;
flip_canvas_on_paint_for_rtl_ui_ = enable;
OnPropertyChanged(&flip_canvas_on_paint_for_rtl_ui_, kPropertyEffectsPaint);
}
base::CallbackListSubscription
View::AddFlipCanvasOnPaintForRTLUIChangedCallback(
PropertyChangedCallback callback) {
return AddPropertyChangedCallback(&flip_canvas_on_paint_for_rtl_ui_,
std::move(callback));
}
void View::SetMirrored(bool is_mirrored) {
if (is_mirrored_ && is_mirrored_.value() == is_mirrored)
return;
is_mirrored_ = is_mirrored;
OnPropertyChanged(&is_mirrored_, kPropertyEffectsPaint);
}
bool View::GetMirrored() const {
return is_mirrored_.value_or(base::i18n::IsRTL());
}
// Input -----------------------------------------------------------------------
View* View::GetEventHandlerForPoint(const gfx::Point& point) {
return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
}
View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
return GetEffectiveViewTargeter()->TargetForRect(this, rect);
}
bool View::GetCanProcessEventsWithinSubtree() const {
return can_process_events_within_subtree_;
}
void View::SetCanProcessEventsWithinSubtree(bool can_process) {
if (can_process_events_within_subtree_ == can_process)
return;
can_process_events_within_subtree_ = can_process;
OnPropertyChanged(&can_process_events_within_subtree_, kPropertyEffectsNone);
}
View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
// TODO(tdanderson): Move this implementation into ViewTargetDelegate.
if (!HitTestPoint(point) || !GetCanProcessEventsWithinSubtree())
return nullptr;
// Walk the child Views recursively looking for the View that most
// tightly encloses the specified point.
View::Views children = GetChildrenInZOrder();
DCHECK_EQ(children_.size(), children.size());
for (auto* child : base::Reversed(children)) {
if (!child->GetVisible())
continue;
gfx::Point point_in_child_coords(point);
ConvertPointToTarget(this, child, &point_in_child_coords);
View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
if (handler)
return handler;
}
return this;
}
ui::Cursor View::GetCursor(const ui::MouseEvent& event) {
return ui::Cursor();
}
bool View::HitTestPoint(const gfx::Point& point) const {
return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
}
bool View::HitTestRect(const gfx::Rect& rect) const {
return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
}
bool View::IsMouseHovered() const {
// If we haven't yet been placed in an onscreen view hierarchy, we can't be
// hovered.
if (!GetWidget())
return false;
// If mouse events are disabled, then the mouse cursor is invisible and
// is therefore not hovering over this button.
if (!GetWidget()->IsMouseEventsEnabled())
return false;
gfx::Point cursor_pos(display::Screen::GetScreen()->GetCursorScreenPoint());
ConvertPointFromScreen(this, &cursor_pos);
return HitTestPoint(cursor_pos);
}
bool View::OnMousePressed(const ui::MouseEvent& event) {
return false;
}
bool View::OnMouseDragged(const ui::MouseEvent& event) {
return false;
}
void View::OnMouseReleased(const ui::MouseEvent& event) {}
void View::OnMouseCaptureLost() {}
void View::OnMouseMoved(const ui::MouseEvent& event) {}
void View::OnMouseEntered(const ui::MouseEvent& event) {}
void View::OnMouseExited(const ui::MouseEvent& event) {}
void View::SetMouseAndGestureHandler(View* new_handler) {
// |new_handler| may be nullptr.
if (parent_)
parent_->SetMouseAndGestureHandler(new_handler);
}
void View::SetMouseHandler(View* new_handler) {
if (parent_)
parent_->SetMouseHandler(new_handler);
}
bool View::OnKeyPressed(const ui::KeyEvent& event) {
return false;
}
bool View::OnKeyReleased(const ui::KeyEvent& event) {
return false;
}
bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
return false;
}
void View::OnKeyEvent(ui::KeyEvent* event) {
bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event)
: OnKeyReleased(*event);
if (consumed)
event->StopPropagation();
}
void View::OnMouseEvent(ui::MouseEvent* event) {
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
if (ProcessMousePressed(*event))
event->SetHandled();
return;
case ui::ET_MOUSE_MOVED:
if ((event->flags() &
(ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON |
ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
OnMouseMoved(*event);
return;
}
[[fallthrough]];
case ui::ET_MOUSE_DRAGGED:
ProcessMouseDragged(event);
return;
case ui::ET_MOUSE_RELEASED:
ProcessMouseReleased(*event);
return;
case ui::ET_MOUSEWHEEL:
if (OnMouseWheel(*event->AsMouseWheelEvent()))
event->SetHandled();
break;
case ui::ET_MOUSE_ENTERED:
if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
NotifyAccessibilityEvent(ax::mojom::Event::kHover, true);
OnMouseEntered(*event);
break;
case ui::ET_MOUSE_EXITED:
OnMouseExited(*event);
break;
default:
return;
}
}
void View::OnScrollEvent(ui::ScrollEvent* event) {}
void View::OnTouchEvent(ui::TouchEvent* event) {
NOTREACHED_NORETURN() << "Views should not receive touch events.";
}
void View::OnGestureEvent(ui::GestureEvent* event) {}
base::StringPiece View::GetLogContext() const {
return GetClassName();
}
void View::SetNotifyEnterExitOnChild(bool notify) {
notify_enter_exit_on_child_ = notify;
}
bool View::GetNotifyEnterExitOnChild() const {
return notify_enter_exit_on_child_;
}
const ui::InputMethod* View::GetInputMethod() const {
Widget* widget = const_cast<Widget*>(GetWidget());
return widget ? const_cast<const ui::InputMethod*>(widget->GetInputMethod())
: nullptr;
}
std::unique_ptr<ViewTargeter> View::SetEventTargeter(
std::unique_ptr<ViewTargeter> targeter) {
std::unique_ptr<ViewTargeter> old_targeter = std::move(targeter_);
targeter_ = std::move(targeter);
return old_targeter;
}
ViewTargeter* View::GetEffectiveViewTargeter() const {
DCHECK(GetWidget());
ViewTargeter* view_targeter = targeter();
if (!view_targeter)
view_targeter = GetWidget()->GetRootView()->targeter();
CHECK(view_targeter);
return view_targeter;
}
WordLookupClient* View::GetWordLookupClient() {
return nullptr;
}
bool View::CanAcceptEvent(const ui::Event& event) {
return IsDrawn();
}
ui::EventTarget* View::GetParentTarget() {
return parent_;
}
std::unique_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
return std::make_unique<ui::EventTargetIteratorPtrImpl<View>>(children_);
}
ui::EventTargeter* View::GetEventTargeter() {
return targeter_.get();
}
void View::ConvertEventToTarget(const ui::EventTarget* target,
ui::LocatedEvent* event) const {
event->ConvertLocationToTarget(this, static_cast<const View*>(target));
}
gfx::PointF View::GetScreenLocationF(const ui::LocatedEvent& event) const {
DCHECK_EQ(this, event.target());
gfx::Point screen_location(event.location());
ConvertPointToScreen(this, &screen_location);
return gfx::PointF(screen_location);
}
// Accelerators ----------------------------------------------------------------
void View::AddAccelerator(const ui::Accelerator& accelerator) {
if (!accelerators_)
accelerators_ = std::make_unique<std::vector<ui::Accelerator>>();
if (!base::Contains(*accelerators_, accelerator))
accelerators_->push_back(accelerator);
RegisterPendingAccelerators();
}
void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
CHECK(accelerators_) << "Removing non-existent accelerator";
auto i(base::ranges::find(*accelerators_, accelerator));
CHECK(i != accelerators_->end()) << "Removing non-existent accelerator";
auto index = static_cast<size_t>(i - accelerators_->begin());
accelerators_->erase(i);
if (index >= registered_accelerator_count_) {
// The accelerator is not registered to FocusManager.
return;
}
--registered_accelerator_count_;
// Providing we are attached to a Widget and registered with a focus manager,
// we should de-register from that focus manager now.
if (GetWidget() && accelerator_focus_manager_)
accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
}
void View::ResetAccelerators() {
if (accelerators_)
UnregisterAccelerators(false);
}
bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
return false;
}
bool View::CanHandleAccelerators() const {
const Widget* widget = GetWidget();
if (!GetEnabled() || !IsDrawn() || !widget || !widget->IsVisible())
return false;
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// Non-ChromeOS aura windows have an associated FocusManagerEventHandler which
// adds currently focused view as an event PreTarget (see
// DesktopNativeWidgetAura::InitNativeWidget). However, the focused view isn't
// always the right view to handle accelerators: It should only handle them
// when active. Only top level widgets can be active, so for child widgets
// check if they are focused instead. ChromeOS also behaves different than
// Linux when an extension popup is about to handle the accelerator.
bool child = widget && widget->GetTopLevelWidget() != widget;
bool focus_in_child = widget && widget->GetRootView()->Contains(
GetFocusManager()->GetFocusedView());
if ((child && !focus_in_child) || (!child && !widget->IsActive()))
return false;
#endif
return true;
}
// Focus -----------------------------------------------------------------------
bool View::HasFocus() const {
const FocusManager* focus_manager = GetFocusManager();
return focus_manager && (focus_manager->GetFocusedView() == this);
}
View* View::GetNextFocusableView() {
return next_focusable_view_;
}
const View* View::GetNextFocusableView() const {
return next_focusable_view_;
}
View* View::GetPreviousFocusableView() {
return previous_focusable_view_;
}
void View::RemoveFromFocusList() {
View* const old_prev = previous_focusable_view_;
View* const old_next = next_focusable_view_;
previous_focusable_view_ = nullptr;
next_focusable_view_ = nullptr;
if (old_prev)
old_prev->next_focusable_view_ = old_next;
if (old_next)
old_next->previous_focusable_view_ = old_prev;
}
void View::InsertBeforeInFocusList(View* view) {
DCHECK(view);
DCHECK_EQ(parent_, view->parent_);
if (view == next_focusable_view_)
return;
RemoveFromFocusList();
next_focusable_view_ = view;
previous_focusable_view_ = view->previous_focusable_view_;
if (previous_focusable_view_)
previous_focusable_view_->next_focusable_view_ = this;
next_focusable_view_->previous_focusable_view_ = this;
}
void View::InsertAfterInFocusList(View* view) {
DCHECK(view);
DCHECK_EQ(parent_, view->parent_);
if (view == previous_focusable_view_)
return;
RemoveFromFocusList();
if (view->next_focusable_view_) {
InsertBeforeInFocusList(view->next_focusable_view_);
return;
}
view->next_focusable_view_ = this;
previous_focusable_view_ = view;
}
View::Views View::GetChildrenFocusList() {
View* starting_focus_view = nullptr;
Views children_views = children();
for (View* child : children_views) {
if (child->GetPreviousFocusableView() == nullptr) {
starting_focus_view = child;
break;
}
}
if (starting_focus_view == nullptr)
return {};
Views result;
// Tracks the views traversed so far. Used to check for cycles.
base::flat_set<View*> seen_views;
View* cur = starting_focus_view;
while (cur != nullptr) {
// Views are not supposed to have focus cycles, but just in case, fail
// gracefully to avoid a crash.
if (seen_views.contains(cur)) {
LOG(ERROR) << "View focus cycle detected.";
return {};
}
seen_views.insert(cur);
result.push_back(cur);
cur = cur->GetNextFocusableView();
}
return result;
}
View::FocusBehavior View::GetFocusBehavior() const {
return focus_behavior_;
}
void View::SetFocusBehavior(FocusBehavior focus_behavior) {
if (GetFocusBehavior() == focus_behavior)
return;
focus_behavior_ = focus_behavior;
AdvanceFocusIfNecessary();
OnPropertyChanged(&focus_behavior_, kPropertyEffectsNone);
}
bool View::IsFocusable() const {
return GetFocusBehavior() == FocusBehavior::ALWAYS && GetEnabled() &&
IsDrawn();
}
bool View::IsAccessibilityFocusable() const {
return GetViewAccessibility().IsAccessibilityFocusable();
}
FocusManager* View::GetFocusManager() {
Widget* widget = GetWidget();
return widget ? widget->GetFocusManager() : nullptr;
}
const FocusManager* View::GetFocusManager() const {
const Widget* widget = GetWidget();
return widget ? widget->GetFocusManager() : nullptr;
}
void View::RequestFocus() {
FocusManager* focus_manager = GetFocusManager();
if (focus_manager) {
bool focusable = focus_manager->keyboard_accessible()
? IsAccessibilityFocusable()
: IsFocusable();
if (focusable)
focus_manager->SetFocusedView(this);
}
}
bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
return false;
}
FocusTraversable* View::GetFocusTraversable() {
return nullptr;
}
FocusTraversable* View::GetPaneFocusTraversable() {
return nullptr;
}
// Tooltips --------------------------------------------------------------------
std::u16string View::GetTooltipText(const gfx::Point& p) const {
return std::u16string();
}
// Context menus ---------------------------------------------------------------
void View::ShowContextMenu(const gfx::Point& p,
ui::MenuSourceType source_type) {
if (!context_menu_controller_)
return;
context_menu_controller_->ShowContextMenuForView(this, p, source_type);
}
gfx::Point View::GetKeyboardContextMenuLocation() {
gfx::Rect vis_bounds = GetVisibleBounds();
gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
vis_bounds.y() + vis_bounds.height() / 2);
ConvertPointToScreen(this, &screen_point);
return screen_point;
}
// Drag and drop ---------------------------------------------------------------
bool View::GetDropFormats(int* formats,
std::set<ui::ClipboardFormatType>* format_types) {
return false;
}
bool View::AreDropTypesRequired() {
return false;
}
bool View::CanDrop(const OSExchangeData& data) {
// TODO(sky): when I finish up migration, this should default to true.
return false;
}
void View::OnDragEntered(const ui::DropTargetEvent& event) {}
int View::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_NONE;
}
void View::OnDragExited() {}
void View::OnDragDone() {}
View::DropCallback View::GetDropCallback(const ui::DropTargetEvent& event) {
return base::NullCallback();
}
// static
bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
return (abs(delta.x()) > GetHorizontalDragThreshold() ||
abs(delta.y()) > GetVerticalDragThreshold());
}
// Accessibility----------------------------------------------------------------
ViewAccessibility& View::GetViewAccessibility() const {
if (!view_accessibility_)
view_accessibility_ = ViewAccessibility::Create(const_cast<View*>(this));
return *view_accessibility_;
}
void View::GetAccessibleNodeData(ui::AXNodeData* node_data) {
// `ViewAccessibility::GetAccessibleNodeData` populates the id and classname
// values prior to asking the View for its data. We don't want to stomp on
// those values.
ax_node_data_->id = node_data->id;
ax_node_data_->AddStringAttribute(
ax::mojom::StringAttribute::kClassName,
node_data->GetStringAttribute(ax::mojom::StringAttribute::kClassName));
// Copy everything set by the property setters.
*node_data = *ax_node_data_;
}
void View::SetAccessibilityProperties(
absl::optional<ax::mojom::Role> role,
absl::optional<std::u16string> name,
absl::optional<std::u16string> description,
absl::optional<std::u16string> role_description,
absl::optional<ax::mojom::NameFrom> name_from,
absl::optional<ax::mojom::DescriptionFrom> description_from) {
base::AutoReset<bool> initializing(&pause_accessibility_events_, true);
if (role.has_value()) {
if (role_description.has_value()) {
SetAccessibleRole(role.value(), role_description.value());
} else {
SetAccessibleRole(role.value());
}
}
// Defining the NameFrom value without specifying the name doesn't make much
// sense. The only exception might be if the NameFrom is setting the name to
// explicitly empty. In order to prevent surprising/confusing behavior, we
// only use the NameFrom value if we have an explicit name. As a result, any
// caller setting the name to explicitly empty must set the name to an empty
// string.
if (name.has_value()) {
if (name_from.has_value()) {
SetAccessibleName(name.value(), name_from.value());
} else {
SetAccessibleName(name.value());
}
}
// See the comment above regarding the NameFrom value.
if (description.has_value()) {
if (description_from.has_value()) {
SetAccessibleDescription(description.value(), description_from.value());
} else {
SetAccessibleDescription(description.value());
}
}
}
void View::SetAccessibleName(const std::u16string& name) {
SetAccessibleName(
name, static_cast<ax::mojom::NameFrom>(ax_node_data_->GetIntAttribute(
ax::mojom::IntAttribute::kNameFrom)));
}
void View::SetAccessibleName(std::u16string name,
ax::mojom::NameFrom name_from) {
// Allow subclasses to adjust the name.
AdjustAccessibleName(name, name_from);
// Ensure we have a current `name_from` value. For instance, the name might
// still be an empty string, but a view is now indicating that this is by
// design by setting `NameFrom::kAttributeExplicitlyEmpty`.
ax_node_data_->SetNameFrom(name_from);
if (name == accessible_name_) {
return;
}
if (name.empty()) {
ax_node_data_->RemoveStringAttribute(ax::mojom::StringAttribute::kName);
} else if (ax_node_data_->role != ax::mojom::Role::kUnknown &&
ax_node_data_->role != ax::mojom::Role::kNone) {
// TODO(accessibility): This is to temporarily work around the DCHECK
// in `AXNodeData` that wants to have a role to calculate a name-from.
// If we don't have a role yet, don't add it to the data until we do.
// See `SetAccessibleRole` where we check for and handle this condition.
// Also note that the `SetAccessibilityProperties` function allows view
// authors to set the role and name at once, if all views use it, we can
// remove this workaround.
ax_node_data_->SetName(name);
}
accessible_name_ = name;
OnPropertyChanged(&accessible_name_, kPropertyEffectsNone);
OnAccessibleNameChanged(name);
NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged, true);
}
void View::SetAccessibleName(View* naming_view) {
DCHECK(naming_view);
DCHECK_NE(this, naming_view);
const std::u16string& name = naming_view->GetAccessibleName();
DCHECK(!name.empty());
SetAccessibleName(name, ax::mojom::NameFrom::kRelatedElement);
ax_node_data_->AddIntListAttribute(
ax::mojom::IntListAttribute::kLabelledbyIds,
{naming_view->GetViewAccessibility().GetUniqueId().Get()});
}
const std::u16string& View::GetAccessibleName() const {
return accessible_name_;
}
void View::SetAccessibleRole(const ax::mojom::Role role) {
if (role == accessible_role_) {
return;
}
ax_node_data_->role = role;
if (role != ax::mojom::Role::kUnknown && role != ax::mojom::Role::kNone) {
if (ax_node_data_->GetStringAttribute(ax::mojom::StringAttribute::kName)
.empty() &&
!accessible_name_.empty()) {
// TODO(accessibility): This is to temporarily work around the DCHECK
// that wants to have a role to calculate a name-from. If we have a
// name in our properties but not in our `AXNodeData`, the name was
// set prior to the role. Now that we have a valid role, we can set
// the name. See `SetAccessibleName` for where we delayed setting it.
ax_node_data_->SetName(accessible_name_);
}
}
accessible_role_ = role;
OnPropertyChanged(&accessible_role_, kPropertyEffectsNone);
}
void View::SetAccessibleRole(const ax::mojom::Role role,
const std::u16string& role_description) {
if (!role_description.empty()) {
ax_node_data_->AddStringAttribute(
ax::mojom::StringAttribute::kRoleDescription,
base::UTF16ToUTF8(role_description));
} else {
ax_node_data_->RemoveStringAttribute(
ax::mojom::StringAttribute::kRoleDescription);
}
SetAccessibleRole(role);
}
ax::mojom::Role View::GetAccessibleRole() const {
return accessible_role_;
}
void View::SetAccessibleDescription(const std::u16string& description) {
if (description.empty()) {
ax_node_data_->RemoveStringAttribute(
ax::mojom::StringAttribute::kDescription);
ax_node_data_->RemoveIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom);
accessible_description_ = description;
return;
}
SetAccessibleDescription(description,
ax::mojom::DescriptionFrom::kAriaDescription);
}
void View::SetAccessibleDescription(
const std::u16string& description,
ax::mojom::DescriptionFrom description_from) {
// Ensure we have a current `description_from` value. For instance, the
// description might still be an empty string, but a view is now indicating
// that this is by design by setting
// `DescriptionFrom::kAttributeExplicitlyEmpty`.
ax_node_data_->SetDescriptionFrom(description_from);
if (description == accessible_description_) {
return;
}
// `AXNodeData::SetDescription` DCHECKs that the description is not empty
// unless it has `DescriptionFrom::kAttributeExplicitlyEmpty`.
if (!description.empty() ||
ax_node_data_->GetDescriptionFrom() ==
ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty) {
ax_node_data_->SetDescription(description);
}
accessible_description_ = description;
OnPropertyChanged(&accessible_description_, kPropertyEffectsNone);
}
void View::SetAccessibleDescription(View* describing_view) {
DCHECK(describing_view);
DCHECK_NE(this, describing_view);
const std::u16string& name = describing_view->GetAccessibleName();
DCHECK(!name.empty());
SetAccessibleDescription(name, ax::mojom::DescriptionFrom::kRelatedElement);
ax_node_data_->AddIntListAttribute(
ax::mojom::IntListAttribute::kDescribedbyIds,
{describing_view->GetViewAccessibility().GetUniqueId().Get()});
}
const std::u16string& View::GetAccessibleDescription() const {
return accessible_description_;
}
bool View::HandleAccessibleAction(const ui::AXActionData& action_data) {
switch (action_data.action) {
case ax::mojom::Action::kBlur:
if (HasFocus()) {
GetFocusManager()->ClearFocus();
return true;
}
break;
case ax::mojom::Action::kDoDefault: {
const gfx::Point center = GetLocalBounds().CenterPoint();
ui::MouseEvent press(ui::ET_MOUSE_PRESSED, center, center,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
OnEvent(&press);
ui::MouseEvent release(ui::ET_MOUSE_RELEASED, center, center,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
OnEvent(&release);
return true;
}
case ax::mojom::Action::kFocus:
if (IsAccessibilityFocusable()) {
RequestFocus();
return true;
}
break;
case ax::mojom::Action::kScrollToMakeVisible:
ScrollRectToVisible(GetLocalBounds());
return true;
case ax::mojom::Action::kShowContextMenu:
ShowContextMenu(GetBoundsInScreen().CenterPoint(),
ui::MENU_SOURCE_KEYBOARD);
return true;
default:
// Some actions are handled by subclasses of View.
break;
}
return false;
}
gfx::NativeViewAccessible View::GetNativeViewAccessible() {
return GetViewAccessibility().GetNativeObject();
}
void View::NotifyAccessibilityEvent(ax::mojom::Event event_type,
bool send_native_event) {
// If it belongs to a widget but its native widget is already destructed, do
// not send such accessibility event as it's unexpected to send such events
// during destruction, and is likely to lead to crashes/problems.
if (GetWidget() && !GetWidget()->GetNativeView())
return;
// If `pause_accessibility_events_` is true, it means we are initializing
// property values. In this specific case, we do not want to notify platform
// assistive technologies that a property has changed.
if (pause_accessibility_events_) {
return;
}
AXEventManager::Get()->NotifyViewEvent(this, event_type);
if (send_native_event && GetWidget())
GetViewAccessibility().NotifyAccessibilityEvent(event_type);
OnAccessibilityEvent(event_type);
}
void View::OnAccessibilityEvent(ax::mojom::Event event_type) {}
// Scrolling -------------------------------------------------------------------
void View::ScrollRectToVisible(const gfx::Rect& rect) {
if (parent_)
parent_->ScrollRectToVisible(rect + bounds().OffsetFromOrigin());
}
void View::ScrollViewToVisible() {
ScrollRectToVisible(GetLocalBounds());
}
void View::AddObserver(ViewObserver* observer) {
CHECK(observer);
observers_.AddObserver(observer);
}
void View::RemoveObserver(ViewObserver* observer) {
observers_.RemoveObserver(observer);
}
bool View::HasObserver(const ViewObserver* observer) const {
return observers_.HasObserver(observer);
}
////////////////////////////////////////////////////////////////////////////////
// View, protected:
// Size and disposition --------------------------------------------------------
gfx::Size View::CalculatePreferredSize() const {
if (HasLayoutManager())
return GetLayoutManager()->GetPreferredSize(this);
return gfx::Size();
}
gfx::Size View::CalculatePreferredSize(const SizeBounds& available_size) const {
return CalculatePreferredSize();
}
void View::PreferredSizeChanged() {
if (parent_)
parent_->ChildPreferredSizeChanged(this);
// Since some layout managers (specifically AnimatingLayoutManager) can react
// to InvalidateLayout() by doing calculations and since the parent can
// potentially change preferred size, etc. as a result of calling
// ChildPreferredSizeChanged(), postpone invalidation until the events have
// run all the way up the hierarchy.
InvalidateLayout();
for (ViewObserver& observer : observers_)
observer.OnViewPreferredSizeChanged(this);
}
bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
return false;
}
void View::OnVisibleBoundsChanged() {}
// Tree operations -------------------------------------------------------------
void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {}
void View::VisibilityChanged(View* starting_from, bool is_visible) {}
void View::NativeViewHierarchyChanged() {
FocusManager* focus_manager = GetFocusManager();
if (accelerator_focus_manager_ != focus_manager) {
UnregisterAccelerators(true);
if (focus_manager)
RegisterPendingAccelerators();
}
}
void View::AddedToWidget() {}
void View::RemovedFromWidget() {}
// Painting --------------------------------------------------------------------
void View::OnDidSchedulePaint(const gfx::Rect& rect) {}
void View::PaintChildren(const PaintInfo& paint_info) {
TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
RecursivePaintHelper(&View::Paint, paint_info);
}
void View::OnPaint(gfx::Canvas* canvas) {
TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
OnPaintBackground(canvas);
OnPaintBorder(canvas);
}
void View::OnPaintBackground(gfx::Canvas* canvas) {
if (background_) {
TRACE_EVENT0("views", "View::OnPaintBackground");
background_->Paint(canvas, this);
}
}
void View::OnPaintBorder(gfx::Canvas* canvas) {
if (border_) {
TRACE_EVENT0("views", "View::OnPaintBorder");
border_->Paint(*this, canvas);
}
}
// Accelerated Painting --------------------------------------------------------
View::LayerOffsetData View::CalculateOffsetToAncestorWithLayer(
ui::Layer** layer_parent) {
if (layer()) {
if (layer_parent)
*layer_parent = layer();
return LayerOffsetData(layer()->device_scale_factor());
}
if (!parent_)
return LayerOffsetData();
LayerOffsetData offset_data =
parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
return offset_data + GetMirroredPosition().OffsetFromOrigin();
}
void View::UpdateParentLayer() {
if (!layer())
return;
ui::Layer* parent_layer = nullptr;
if (parent_)
parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
ReparentLayer(parent_layer);
}
void View::MoveLayerToParent(ui::Layer* parent_layer,
const LayerOffsetData& offset_data) {
LayerOffsetData local_offset_data(offset_data);
if (parent_layer != layer())
local_offset_data += GetMirroredPosition().OffsetFromOrigin();
if (layer() && parent_layer != layer()) {
SetLayerParent(parent_layer);
SetLayerBounds(size(), local_offset_data);
} else {
internal::ScopedChildrenLock lock(this);
for (auto* child : GetChildrenInZOrder())
child->MoveLayerToParent(parent_layer, local_offset_data);
}
}
void View::UpdateLayerVisibility() {
bool visible = visible_;
for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
visible = v->GetVisible();
UpdateChildLayerVisibility(visible);
}
void View::UpdateChildLayerVisibility(bool ancestor_visible) {
const bool layers_visible = ancestor_visible && visible_;
if (layer()) {
for (ui::Layer* layer : GetLayersInOrder()) {
layer->SetVisible(layers_visible);
}
}
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->UpdateChildLayerVisibility(layers_visible);
}
}
void View::DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents) {
// Normally, adding layers above or below will trigger painting to a layer.
// It would leave this view in an inconsistent state if its layer were
// destroyed while layers beneath were still present. So, assume this doesn't
// happen.
DCHECK(layers_below_.empty() && layers_above_.empty());
if (!layer())
return;
// Copy children(), since the loop below will mutate its result.
std::vector<ui::Layer*> children = layer()->children();
ui::Layer* new_parent = layer()->parent();
for (auto* child : children) {
layer()->Remove(child);
if (new_parent)
new_parent->Add(child);
}
mask_layer_.reset();
LayerOwner::DestroyLayer();
if (new_parent)
ReorderLayers();
UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(nullptr));
SchedulePaint();
// Notify the parent chain about the layer change.
if (notify_parents == LayerChangeNotifyBehavior::NOTIFY)
NotifyParentsOfLayerChange();
Widget* widget = GetWidget();
if (widget)
widget->LayerTreeChanged();
}
void View::NotifyParentsOfLayerChange() {
// Notify the parent chain about the layer change.
View* view_parent = parent();
while (view_parent) {
view_parent->OnChildLayerChanged(this);
view_parent = view_parent->parent();
}
}
void View::UpdateChildLayerBounds(const LayerOffsetData& offset_data) {
if (layer()) {
SetLayerBounds(size(), offset_data);
} else {
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
child->UpdateChildLayerBounds(
offset_data + child->GetMirroredPosition().OffsetFromOrigin());
}
}
}
void View::OnPaintLayer(const ui::PaintContext& context) {
PaintFromPaintRoot(context);
}
void View::OnLayerTransformed(const gfx::Transform& old_transform,
ui::PropertyChangeReason reason) {
NotifyAccessibilityEvent(ax::mojom::Event::kLocationChanged, false);
for (ViewObserver& observer : observers_)
observer.OnViewLayerTransformed(this);
}
void View::OnLayerClipRectChanged(const gfx::Rect& old_rect,
ui::PropertyChangeReason reason) {
for (ViewObserver& observer : observers_)
observer.OnViewLayerClipRectChanged(this);
}
void View::OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
snap_layer_to_pixel_boundary_ =
(new_device_scale_factor - std::floor(new_device_scale_factor)) != 0.0f;
if (!layer())
return;
// There can be no subpixel offset if the layer has no parent.
if (!parent() || !layer()->parent())
return;
if (layer()->parent() && layer()->GetCompositor() &&
layer()->GetCompositor()->is_pixel_canvas()) {
LayerOffsetData offset_data(
parent()->CalculateOffsetToAncestorWithLayer(nullptr));
offset_data += GetMirroredPosition().OffsetFromOrigin();
SnapLayerToPixelBoundary(offset_data);
} else {
SnapLayerToPixelBoundary(LayerOffsetData());
}
}
void View::CreateOrDestroyLayer() {
if (paint_to_layer_explicitly_set_ || paint_to_layer_for_transform_ ||
!layers_below_.empty() || !layers_above_.empty()) {
// If we need to paint to a layer, make sure we have one.
if (!layer())
CreateLayer(ui::LAYER_TEXTURED);
} else if (layer()) {
// If we don't, make sure we delete our layer.
DestroyLayerImpl(LayerChangeNotifyBehavior::NOTIFY);
}
}
void View::ReorderLayers() {
View* v = this;
while (v && !v->layer())
v = v->parent();
Widget* widget = GetWidget();
if (!v) {
if (widget) {
ui::Layer* layer = widget->GetLayer();
if (layer)
widget->GetRootView()->ReorderChildLayers(layer);
}
} else {
v->ReorderChildLayers(v->layer());
}
if (widget) {
// Reorder the widget's child NativeViews in case a child NativeView is
// associated with a view (e.g. via a NativeViewHost). Always do the
// reordering because the associated NativeView's layer (if it has one)
// is parented to the widget's layer regardless of whether the host view has
// an ancestor with a layer.
widget->ReorderNativeViews();
}
}
void View::AddLayerToRegionImpl(ui::Layer* new_layer,
std::vector<ui::Layer*>& layer_vector) {
DCHECK(new_layer);
DCHECK(!base::Contains(layer_vector, new_layer)) << "Layer already added.";
new_layer->AddObserver(this);
new_layer->SetVisible(GetVisible());
layer_vector.push_back(new_layer);
// If painting to a layer already, ensure |new_layer| gets added and stacked
// correctly. If not, this will happen on layer creation.
if (layer()) {
ui::Layer* const parent_layer = layer()->parent();
// Note that |new_layer| may have already been added to the parent, for
// example when the layer of a LayerOwner is recreated.
if (parent_layer && parent_layer != new_layer->parent()) {
parent_layer->Add(new_layer);
}
new_layer->SetBounds(gfx::Rect(new_layer->size()) +
layer()->bounds().OffsetFromOrigin());
if (parent()) {
parent()->ReorderLayers();
}
}
CreateOrDestroyLayer();
layer()->SetFillsBoundsOpaquely(false);
}
void View::SetLayerParent(ui::Layer* parent_layer) {
// Adding the main layer can trigger a call to |SnapLayerToPixelBoundary()|.
// That method assumes layers beneath have already been added. Therefore
// layers above and below must be added first here. See crbug.com/961212.
for (ui::Layer* extra_layer : GetLayersInOrder(ViewLayer::kExclude)) {
parent_layer->Add(extra_layer);
}
parent_layer->Add(layer());
// After adding the main layer, it's relative position in the stack needs
// to be adjusted. This will ensure the layer is between any of the layers
// above and below the main layer.
if (!layers_below_.empty()) {
parent_layer->StackAbove(layer(), layers_below_.back());
} else if (!layers_above_.empty()) {
parent_layer->StackBelow(layer(), layers_above_.front());
}
}
void View::ReorderChildLayers(ui::Layer* parent_layer) {
if (layer() && layer() != parent_layer) {
DCHECK_EQ(parent_layer, layer()->parent());
for (ui::Layer* layer_above : layers_above_) {
parent_layer->StackAtBottom(layer_above);
}
parent_layer->StackAtBottom(layer());
for (ui::Layer* layer_below : layers_below_) {
parent_layer->StackAtBottom(layer_below);
}
} else {
// Iterate backwards through the children so that a child with a layer
// which is further to the back is stacked above one which is further to
// the front.
View::Views children = GetChildrenInZOrder();
DCHECK_EQ(children_.size(), children.size());
for (auto* child : base::Reversed(children))
child->ReorderChildLayers(parent_layer);
}
}
void View::OnChildLayerChanged(View* child) {}
// Input -----------------------------------------------------------------------
View::DragInfo* View::GetDragInfo() {
return parent_ ? parent_->GetDragInfo() : nullptr;
}
// Focus -----------------------------------------------------------------------
void View::OnFocus() {}
void View::OnBlur() {}
void View::Focus() {
OnFocus();
// TODO(pbos): Investigate if parts of this can run unconditionally.
if (!suppress_default_focus_handling_) {
// Clear the native focus. This ensures that no visible native view has the
// focus and that we still receive keyboard inputs.
FocusManager* focus_manager = GetFocusManager();
if (focus_manager)
focus_manager->ClearNativeFocus();
// Notify assistive technologies of the focus change.
AXVirtualView* const focused_virtual_child =
view_accessibility_ ? view_accessibility_->FocusedVirtualChild()
: nullptr;
if (focused_virtual_child) {
focused_virtual_child->NotifyAccessibilityEvent(ax::mojom::Event::kFocus);
} else {
NotifyAccessibilityEvent(ax::mojom::Event::kFocus, true);
}
}
// If this is the contents root of a |ScrollView|, focus should bring the
// |ScrollView| to visible rather than resetting its content scroll position.
ScrollView* const scroll_view = ScrollView::GetScrollViewForContents(this);
if (scroll_view) {
scroll_view->ScrollViewToVisible();
} else {
ScrollViewToVisible();
}
for (ViewObserver& observer : observers_)
observer.OnViewFocused(this);
}
void View::Blur() {
ViewTracker tracker(this);
OnBlur();
if (tracker.view()) {
for (ViewObserver& observer : observers_)
observer.OnViewBlurred(this);
}
}
// System events ---------------------------------------------------------------
void View::OnThemeChanged() {
#if DCHECK_IS_ON()
on_theme_changed_called_ = true;
#endif
}
// Tooltips --------------------------------------------------------------------
void View::TooltipTextChanged() {
Widget* widget = GetWidget();
// TooltipManager may be null if there is a problem creating it.
if (widget && widget->GetTooltipManager())
widget->GetTooltipManager()->TooltipTextChanged(this);
}
// Drag and drop ---------------------------------------------------------------
int View::GetDragOperations(const gfx::Point& press_pt) {
return drag_controller_
? drag_controller_->GetDragOperationsForView(this, press_pt)
: ui::DragDropTypes::DRAG_NONE;
}
void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
DCHECK(drag_controller_);
drag_controller_->WriteDragDataForView(this, press_pt, data);
}
bool View::InDrag() const {
const Widget* widget = GetWidget();
return widget ? widget->dragged_view() == this : false;
}
int View::GetHorizontalDragThreshold() {
// TODO(jennyz): This value may need to be adjusted for different platforms
// and for different display density.
return kDefaultHorizontalDragThreshold;
}
int View::GetVerticalDragThreshold() {
// TODO(jennyz): This value may need to be adjusted for different platforms
// and for different display density.
return kDefaultVerticalDragThreshold;
}
PaintInfo::ScaleType View::GetPaintScaleType() const {
return PaintInfo::ScaleType::kScaleWithEdgeSnapping;
}
void View::HandlePropertyChangeEffects(PropertyEffects effects) {
if (effects & kPropertyEffectsPreferredSizeChanged)
PreferredSizeChanged();
if (effects & kPropertyEffectsLayout)
InvalidateLayout();
if (effects & kPropertyEffectsPaint)
SchedulePaint();
}
void View::AfterPropertyChange(const void* key, int64_t old_value) {
if (key == kElementIdentifierKey) {
const ui::ElementIdentifier old_element_id =
ui::ElementIdentifier::FromRawValue(
base::checked_cast<intptr_t>(old_value));
if (old_element_id) {
views::ElementTrackerViews::GetInstance()->UnregisterView(old_element_id,
this);
}
const ui::ElementIdentifier new_element_id =
GetProperty(kElementIdentifierKey);
if (new_element_id) {
views::ElementTrackerViews::GetInstance()->RegisterView(new_element_id,
this);
}
}
}
void View::OnPropertyChanged(ui::metadata::PropertyKey property,
PropertyEffects property_effects) {
if (property_effects != kPropertyEffectsNone)
HandlePropertyChangeEffects(property_effects);
TriggerChangedCallback(property);
}
int View::GetX() const {
return x();
}
int View::GetY() const {
return y();
}
int View::GetWidth() const {
return width();
}
int View::GetHeight() const {
return height();
}
void View::SetWidth(int width) {
SetBounds(x(), y(), width, height());
}
void View::SetHeight(int height) {
SetBounds(x(), y(), width(), height);
}
std::u16string View::GetTooltip() const {
return GetTooltipText(gfx::Point());
}
////////////////////////////////////////////////////////////////////////////////
// View, private:
// DropInfo --------------------------------------------------------------------
void View::DragInfo::Reset() {
possible_drag = false;
start_pt = gfx::Point();
}
void View::DragInfo::PossibleDrag(const gfx::Point& p) {
possible_drag = true;
start_pt = p;
}
// Painting --------------------------------------------------------------------
void View::SchedulePaintInRectImpl(const gfx::Rect& rect) {
OnDidSchedulePaint(rect);
if (!visible_)
return;
if (layer()) {
layer()->SchedulePaint(rect);
} else if (parent_) {
// Translate the requested paint rect to the parent's coordinate system
// then pass this notification up to the parent.
parent_->SchedulePaintInRectImpl(ConvertRectToParent(rect));
}
}
void View::SchedulePaintBoundsChanged(bool size_changed) {
if (!visible_)
return;
// If we have a layer and the View's size did not change, we do not need to
// schedule any paints since the layer will be redrawn at its new location
// during the next Draw() cycle in the compositor.
if (!layer() || size_changed) {
// Otherwise, if the size changes or we don't have a layer then we need to
// use SchedulePaint to invalidate the area occupied by the View.
SchedulePaint();
} else {
// The compositor doesn't Draw() until something on screen changes, so
// if our position changes but nothing is being animated on screen, then
// tell the compositor to redraw the scene. We know layer() exists due to
// the above if clause.
layer()->ScheduleDraw();
}
}
void View::SchedulePaintOnParent() {
if (parent_) {
// Translate the requested paint rect to the parent's coordinate system
// then pass this notification up to the parent.
parent_->SchedulePaintInRect(ConvertRectToParent(GetLocalBounds()));
}
}
bool View::ShouldPaint() const {
return visible_ && !size().IsEmpty();
}
void View::SetUpTransformRecorderForPainting(
const gfx::Vector2d& offset_from_parent,
ui::TransformRecorder* recorder) const {
// If the view is backed by a layer, it should paint with itself as the origin
// rather than relative to its parent.
if (layer())
return;
// Translate the graphics such that 0,0 corresponds to where this View is
// located relative to its parent.
gfx::Transform transform_from_parent;
transform_from_parent.Translate(offset_from_parent.x(),
offset_from_parent.y());
recorder->Transform(transform_from_parent);
}
void View::RecursivePaintHelper(void (View::*func)(const PaintInfo&),
const PaintInfo& info) {
View::Views children = GetChildrenInZOrder();
DCHECK_EQ(children_.size(), children.size());
for (auto* child : children) {
if (!child->layer())
(child->*func)(info);
}
}
void View::PaintFromPaintRoot(const ui::PaintContext& parent_context) {
PaintInfo paint_info = PaintInfo::CreateRootPaintInfo(
parent_context, layer() ? layer()->size() : size());
Paint(paint_info);
static bool draw_view_bounds_rects =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDrawViewBoundsRects);
if (draw_view_bounds_rects)
PaintDebugRects(paint_info);
}
void View::PaintDebugRects(const PaintInfo& parent_paint_info) {
if (!ShouldPaint())
return;
const gfx::Rect& parent_bounds = (layer() || !parent())
? GetMirroredBounds()
: parent()->GetMirroredBounds();
PaintInfo paint_info = PaintInfo::CreateChildPaintInfo(
parent_paint_info, GetMirroredBounds(), parent_bounds.size(),
GetPaintScaleType(), !!layer());
const ui::PaintContext& context = paint_info.context();
ui::TransformRecorder transform_recorder(context);
SetUpTransformRecorderForPainting(paint_info.offset_from_parent(),
&transform_recorder);
RecursivePaintHelper(&View::PaintDebugRects, paint_info);
// Draw outline rects for debugging.
ui::PaintRecorder recorder(context, paint_info.paint_recording_size(),
paint_info.paint_recording_scale_x(),
paint_info.paint_recording_scale_y(),
&paint_cache_);
gfx::Canvas* canvas = recorder.canvas();
const float scale = canvas->UndoDeviceScaleFactor();
gfx::RectF outline_rect(ScaleToEnclosedRect(GetLocalBounds(), scale));
gfx::RectF content_outline_rect(
ScaleToEnclosedRect(GetContentsBounds(), scale));
const auto* color_provider = GetColorProvider();
if (content_outline_rect != outline_rect) {
content_outline_rect.Inset(0.5f);
canvas->DrawRect(content_outline_rect,
color_provider->GetColor(ui::kColorDebugContentOutline));
}
outline_rect.Inset(0.5f);
canvas->DrawRect(outline_rect,
color_provider->GetColor(ui::kColorDebugBoundsOutline));
}
// Tree operations -------------------------------------------------------------
void View::AddChildViewAtImpl(View* view, size_t index) {
CHECK_NE(view, this) << "You cannot add a view as its own child";
DCHECK_LE(index, children_.size());
// TODO(https://crbug.com/942298): Should just DCHECK(!view->parent_);.
View* parent = view->parent_;
if (parent == this) {
ReorderChildView(view, index);
return;
}
// Remove |view| from its parent, if any.
Widget* old_widget = view->GetWidget();
ui::NativeTheme* old_theme = old_widget ? view->GetNativeTheme() : nullptr;
if (parent)
parent->DoRemoveChildView(view, true, false, this);
view->parent_ = this;
#if DCHECK_IS_ON()
DCHECK(!iterating_);
#endif
const auto pos = children_.insert(
std::next(children_.cbegin(), static_cast<ptrdiff_t>(index)), view);
view->RemoveFromFocusList();
SetFocusSiblings(view, pos);
// Ensure the layer tree matches the view tree before calling to any client
// code. This way if client code further modifies the view tree we are in a
// sane state.
const bool did_reparent_any_layers = view->UpdateParentLayers();
Widget* widget = GetWidget();
if (did_reparent_any_layers && widget)
widget->LayerTreeChanged();
ReorderLayers();
// Make sure the visibility of the child layers are correct.
// If any of the parent View is hidden, then the layers of the subtree
// rooted at |this| should be hidden. Otherwise, all the child layers should
// inherit the visibility of the owner View.
view->UpdateLayerVisibility();
// Need to notify the layout manager because one of the callbacks below might
// want to know the view's new preferred size, minimum size, etc.
if (HasLayoutManager())
GetLayoutManager()->ViewAdded(this, view);
if (widget && (view->GetNativeTheme() != old_theme))
view->PropagateThemeChanged();
ViewHierarchyChangedDetails details(true, this, view, parent);
for (View* v = this; v; v = v->parent_)
v->ViewHierarchyChangedImpl(details);
view->PropagateAddNotifications(details, widget && widget != old_widget);
UpdateTooltip();
if (widget) {
RegisterChildrenForVisibleBoundsNotification(view);
if (view->GetVisible())
view->SchedulePaint();
}
for (ViewObserver& observer : observers_)
observer.OnChildViewAdded(this, view);
}
void View::DoRemoveChildView(View* view,
bool update_tool_tip,
bool delete_removed_view,
View* new_parent) {
DCHECK(view);
const auto i = FindChild(view);
if (i == children_.cend())
return;
std::unique_ptr<View> view_to_be_deleted;
view->RemoveFromFocusList();
Widget* widget = GetWidget();
bool is_removed_from_widget = false;
if (widget) {
UnregisterChildrenForVisibleBoundsNotification(view);
if (view->GetVisible())
view->SchedulePaint();
is_removed_from_widget = !new_parent || new_parent->GetWidget() != widget;
if (is_removed_from_widget)
widget->NotifyWillRemoveView(view);
}
// Make sure the layers belonging to the subtree rooted at |view| get
// removed.
view->OrphanLayers();
if (widget)
widget->LayerTreeChanged();
// Need to notify the layout manager because one of the callbacks below might
// want to know the view's new preferred size, minimum size, etc.
if (HasLayoutManager())
GetLayoutManager()->ViewRemoved(this, view);
view->PropagateRemoveNotifications(this, new_parent, is_removed_from_widget);
view->parent_ = nullptr;
if (delete_removed_view && !view->owned_by_client_)
view_to_be_deleted.reset(view);
#if DCHECK_IS_ON()
DCHECK(!iterating_);
#endif
children_.erase(i);
if (update_tool_tip)
UpdateTooltip();
for (ViewObserver& observer : observers_)
observer.OnChildViewRemoved(this, view);
}
void View::PropagateRemoveNotifications(View* old_parent,
View* new_parent,
bool is_removed_from_widget) {
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
child->PropagateRemoveNotifications(old_parent, new_parent,
is_removed_from_widget);
}
}
// When a view is removed from a hierarchy, UnregisterAccelerators() is called
// for the removed view and all descendant views in post-order.
UnregisterAccelerators(true);
ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
for (View* v = this; v; v = v->parent_)
v->ViewHierarchyChangedImpl(details);
if (is_removed_from_widget) {
RemovedFromWidget();
for (ViewObserver& observer : observers_)
observer.OnViewRemovedFromWidget(this);
}
}
void View::PropagateAddNotifications(const ViewHierarchyChangedDetails& details,
bool is_added_to_widget) {
// When a view is added to a Widget hierarchy, RegisterPendingAccelerators()
// will be called for the added view and all its descendants in pre-order.
// This means that descendant views will register their accelerators after
// their parents. This allows children to override accelerators registered by
// their parents as accelerators registered later take priority over those
// registered earlier.
if (GetFocusManager())
RegisterPendingAccelerators();
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->PropagateAddNotifications(details, is_added_to_widget);
}
ViewHierarchyChangedImpl(details);
if (is_added_to_widget) {
AddedToWidget();
for (ViewObserver& observer : observers_)
observer.OnViewAddedToWidget(this);
}
}
void View::PropagateNativeViewHierarchyChanged() {
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->PropagateNativeViewHierarchyChanged();
}
NativeViewHierarchyChanged();
}
void View::ViewHierarchyChangedImpl(
const ViewHierarchyChangedDetails& details) {
ViewHierarchyChanged(details);
for (ViewObserver& observer : observers_)
observer.OnViewHierarchyChanged(this, details);
details.parent->needs_layout_ = true;
}
// Size and disposition --------------------------------------------------------
void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->PropagateVisibilityNotifications(start, is_visible);
}
VisibilityChangedImpl(start, is_visible);
}
void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
VisibilityChanged(starting_from, is_visible);
for (ViewObserver& observer : observers_)
observer.OnViewVisibilityChanged(this, starting_from);
}
void View::SnapLayerToPixelBoundary(const LayerOffsetData& offset_data) {
if (!layer())
return;
#if DCHECK_IS_ON()
// We rely on our layers above and below being parented correctly at this
// point.
for (ui::Layer* layer_above_below : GetLayersInOrder(ViewLayer::kExclude)) {
DCHECK_EQ(layer()->parent(), layer_above_below->parent());
}
#endif // DCHECK_IS_ON()
if (layer()->GetCompositor() && layer()->GetCompositor()->is_pixel_canvas()) {
gfx::Vector2dF offset = snap_layer_to_pixel_boundary_ && layer()->parent()
? offset_data.GetSubpixelOffset()
: gfx::Vector2dF();
layer()->SetSubpixelPositionOffset(offset);
for (ui::Layer* layer : GetLayersInOrder(ViewLayer::kExclude)) {
layer->SetSubpixelPositionOffset(offset);
}
}
}
// static
void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
if (view->GetNeedsNotificationWhenVisibleBoundsChange())
view->RegisterForVisibleBoundsNotification();
for (View* child : view->children_)
RegisterChildrenForVisibleBoundsNotification(child);
}
// static
void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
if (view->GetNeedsNotificationWhenVisibleBoundsChange())
view->UnregisterForVisibleBoundsNotification();
for (View* child : view->children_)
UnregisterChildrenForVisibleBoundsNotification(child);
}
void View::RegisterForVisibleBoundsNotification() {
if (registered_for_visible_bounds_notification_)
return;
registered_for_visible_bounds_notification_ = true;
for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
ancestor->AddDescendantToNotify(this);
}
void View::UnregisterForVisibleBoundsNotification() {
if (!registered_for_visible_bounds_notification_)
return;
registered_for_visible_bounds_notification_ = false;
for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
ancestor->RemoveDescendantToNotify(this);
}
void View::AddDescendantToNotify(View* view) {
DCHECK(view);
if (!descendants_to_notify_)
descendants_to_notify_ = std::make_unique<Views>();
descendants_to_notify_->push_back(view);
}
void View::RemoveDescendantToNotify(View* view) {
DCHECK(view && descendants_to_notify_);
auto i = base::ranges::find(*descendants_to_notify_, view);
DCHECK(i != descendants_to_notify_->end());
descendants_to_notify_->erase(i);
if (descendants_to_notify_->empty())
descendants_to_notify_.reset();
}
void View::SetLayoutManagerImpl(std::unique_ptr<LayoutManager> layout_manager) {
// Some code keeps a bare pointer to the layout manager for calling
// derived-class-specific-functions. It's an easy mistake to create a new
// unique_ptr and re-set the layout manager with a new unique_ptr, which
// will cause a crash. Re-setting to nullptr is OK.
CHECK(!layout_manager || layout_manager_ != layout_manager);
layout_manager_ = std::move(layout_manager);
if (layout_manager_)
layout_manager_->Installed(this);
// Only reset |default_fill_layout_| if it's already been set and there is a
// layout manager.
if (default_fill_layout_.has_value() && layout_manager_)
default_fill_layout_.reset();
else if (kUseDefaultFillLayout)
default_fill_layout_.emplace(DefaultFillLayout());
}
void View::SetLayerBounds(const gfx::Size& size,
const LayerOffsetData& offset_data) {
const gfx::Rect bounds = gfx::Rect(size) + offset_data.offset();
const bool bounds_changed = (bounds != layer()->GetTargetBounds());
layer()->SetBounds(bounds);
for (ui::Layer* layer : GetLayersInOrder(ViewLayer::kExclude)) {
layer->SetBounds(gfx::Rect(layer->size()) + bounds.OffsetFromOrigin());
}
SnapLayerToPixelBoundary(offset_data);
if (bounds_changed) {
for (ViewObserver& observer : observers_)
observer.OnLayerTargetBoundsChanged(this);
}
}
// Transformations -------------------------------------------------------------
bool View::GetTransformRelativeTo(const View* ancestor,
gfx::Transform* transform) const {
const View* p = this;
while (p && p != ancestor) {
transform->PostConcat(p->GetTransform());
gfx::Transform translation;
translation.Translate(static_cast<float>(p->GetMirroredX()),
static_cast<float>(p->y()));
transform->PostConcat(translation);
p = p->parent_;
}
return p == ancestor;
}
// Coordinate conversion -------------------------------------------------------
bool View::ConvertPointForAncestor(const View* ancestor,
gfx::Point* point) const {
gfx::Transform trans;
// TODO(sad): Have some way of caching the transformation results.
bool result = GetTransformRelativeTo(ancestor, &trans);
*point = gfx::ToFlooredPoint(trans.MapPoint(gfx::PointF(*point)));
return result;
}
bool View::ConvertPointFromAncestor(const View* ancestor,
gfx::Point* point) const {
gfx::Transform trans;
bool result = GetTransformRelativeTo(ancestor, &trans);
if (const absl::optional<gfx::PointF> transformed_point =
trans.InverseMapPoint(gfx::PointF(*point))) {
*point = gfx::ToFlooredPoint(transformed_point.value());
}
return result;
}
bool View::ConvertRectForAncestor(const View* ancestor,
gfx::RectF* rect) const {
gfx::Transform trans;
// TODO(sad): Have some way of caching the transformation results.
bool result = GetTransformRelativeTo(ancestor, &trans);
*rect = trans.MapRect(*rect);
return result;
}
bool View::ConvertRectFromAncestor(const View* ancestor,
gfx::RectF* rect) const {
gfx::Transform trans;
bool result = GetTransformRelativeTo(ancestor, &trans);
*rect = trans.InverseMapRect(*rect).value_or(*rect);
return result;
}
// Accelerated painting --------------------------------------------------------
void View::CreateLayer(ui::LayerType layer_type) {
// A new layer is being created for the view. So all the layers of the
// sub-tree can inherit the visibility of the corresponding view.
{
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->UpdateChildLayerVisibility(true);
}
SetLayer(std::make_unique<ui::Layer>(layer_type));
layer()->set_delegate(this);
layer()->SetName(GetClassName());
UpdateParentLayers();
UpdateLayerVisibility();
// The new layer needs to be ordered in the layer tree according
// to the view tree. Children of this layer were added in order
// in UpdateParentLayers().
if (parent())
parent()->ReorderLayers();
Widget* widget = GetWidget();
if (widget)
widget->LayerTreeChanged();
// Before having its own Layer, this View may have painted in to a Layer owned
// by an ancestor View. Scheduling a paint on the parent View will erase this
// View's painting effects on the ancestor View's Layer.
// (See crbug.com/551492)
SchedulePaintOnParent();
}
bool View::UpdateParentLayers() {
// Attach all top-level un-parented layers.
if (layer()) {
if (!layer()->parent()) {
UpdateParentLayer();
return true;
}
// The layers of any child views are already in place, so we can stop
// iterating here.
return false;
}
bool result = false;
internal::ScopedChildrenLock lock(this);
for (auto* child : children_) {
if (child->UpdateParentLayers())
result = true;
}
return result;
}
void View::OrphanLayers() {
if (layer()) {
ui::Layer* parent = layer()->parent();
if (parent) {
for (ui::Layer* layer : GetLayersInOrder()) {
parent->Remove(layer);
}
}
// The layer belonging to this View has already been orphaned. It is not
// necessary to orphan the child layers.
return;
}
internal::ScopedChildrenLock lock(this);
for (auto* child : children_)
child->OrphanLayers();
}
void View::ReparentLayer(ui::Layer* parent_layer) {
DCHECK_NE(layer(), parent_layer);
if (parent_layer) {
SetLayerParent(parent_layer);
}
// Update the layer bounds; this needs to be called after this layer is added
// to the new parent layer since snapping to pixel boundary will be affected
// by the layer hierarchy.
LayerOffsetData offset =
parent_ ? parent_->CalculateOffsetToAncestorWithLayer(nullptr)
: LayerOffsetData(layer()->device_scale_factor());
SetLayerBounds(size(), offset + GetMirroredBounds().OffsetFromOrigin());
layer()->SchedulePaint(GetLocalBounds());
MoveLayerToParent(layer(), LayerOffsetData(layer()->device_scale_factor()));
}
void View::CreateMaskLayer() {
DCHECK(layer());
mask_layer_ = std::make_unique<views::ViewMaskLayer>(clip_path_, this);
layer()->SetMaskLayer(mask_layer_->layer());
}
// Layout ----------------------------------------------------------------------
bool View::HasLayoutManager() const {
return ((default_fill_layout_.has_value() && !children_.empty()) ||
layout_manager_);
}
// Input -----------------------------------------------------------------------
bool View::ProcessMousePressed(const ui::MouseEvent& event) {
int drag_operations = (enabled_ && event.IsOnlyLeftMouseButton() &&
HitTestPoint(event.location()))
? GetDragOperations(event.location())
: 0;
ContextMenuController* context_menu_controller =
event.IsRightMouseButton() ? context_menu_controller_.get() : nullptr;
View::DragInfo* drag_info = GetDragInfo();
const bool was_enabled = GetEnabled();
const bool result = OnMousePressed(event);
if (!was_enabled)
return result;
if (event.IsOnlyRightMouseButton() && context_menu_controller &&
kContextMenuOnMousePress) {
// Assume that if there is a context menu controller we won't be deleted
// from mouse pressed.
if (HitTestPoint(event.location())) {
gfx::Point location(event.location());
ConvertPointToScreen(this, &location);
ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
return true;
}
}
// WARNING: we may have been deleted, don't use any View variables.
if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
drag_info->PossibleDrag(event.location());
return true;
}
return !!context_menu_controller || result;
}
void View::ProcessMouseDragged(ui::MouseEvent* event) {
// Copy the field, that way if we're deleted after drag and drop no harm is
// done.
ContextMenuController* context_menu_controller = context_menu_controller_;
const bool possible_drag = GetDragInfo()->possible_drag;
if (possible_drag &&
ExceededDragThreshold(GetDragInfo()->start_pt - event->location()) &&
(!drag_controller_ ||
drag_controller_->CanStartDragForView(this, GetDragInfo()->start_pt,
event->location()))) {
if (DoDrag(*event, GetDragInfo()->start_pt,
ui::mojom::DragEventSource::kMouse)) {
event->StopPropagation();
return;
}
} else {
if (OnMouseDragged(*event)) {
event->SetHandled();
return;
}
// Fall through to return value based on context menu controller.
}
// WARNING: we may have been deleted.
if ((context_menu_controller != nullptr) || possible_drag)
event->SetHandled();
}
void View::ProcessMouseReleased(const ui::MouseEvent& event) {
if (!kContextMenuOnMousePress && context_menu_controller_ &&
event.IsOnlyRightMouseButton()) {
// Assume that if there is a context menu controller we won't be deleted
// from mouse released.
gfx::Point location(event.location());
OnMouseReleased(event);
if (HitTestPoint(location)) {
ConvertPointToScreen(this, &location);
ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
}
} else {
OnMouseReleased(event);
}
// WARNING: we may have been deleted.
}
// Accelerators ----------------------------------------------------------------
void View::RegisterPendingAccelerators() {
if (!accelerators_ ||
registered_accelerator_count_ == accelerators_->size()) {
// No accelerators are waiting for registration.
return;
}
if (!GetWidget()) {
// The view is not yet attached to a widget, defer registration until then.
return;
}
accelerator_focus_manager_ = GetFocusManager();
CHECK(accelerator_focus_manager_);
for (std::vector<ui::Accelerator>::const_iterator i =
accelerators_->begin() +
static_cast<ptrdiff_t>(registered_accelerator_count_);
i != accelerators_->end(); ++i) {
accelerator_focus_manager_->RegisterAccelerator(
*i, ui::AcceleratorManager::kNormalPriority, this);
}
registered_accelerator_count_ = accelerators_->size();
}
void View::UnregisterAccelerators(bool leave_data_intact) {
if (!accelerators_)
return;
if (GetWidget()) {
if (accelerator_focus_manager_) {
accelerator_focus_manager_->UnregisterAccelerators(this);
accelerator_focus_manager_ = nullptr;
}
if (!leave_data_intact) {
accelerators_->clear();
accelerators_.reset();
}
registered_accelerator_count_ = 0;
}
}
// Focus -----------------------------------------------------------------------
void View::SetFocusSiblings(View* view, Views::const_iterator pos) {
// |view| was just inserted at |pos|, so all of these conditions must hold.
DCHECK(!children_.empty());
DCHECK(pos != children_.cend());
DCHECK_EQ(view, *pos);
if (children_.size() > 1) {
if (std::next(pos) == children_.cend()) {
// |view| was inserted at the end, but the end of the child list may not
// be the last focusable element. Try to hook in after the last focusable
// child.
View* const old_last = *base::ranges::find_if_not(
children_.cbegin(), pos, &View::next_focusable_view_);
DCHECK_NE(old_last, view);
view->InsertAfterInFocusList(old_last);
} else {
// |view| was inserted somewhere other than the end. Hook in before the
// subsequent child.
view->InsertBeforeInFocusList(*std::next(pos));
}
}
}
void View::AdvanceFocusIfNecessary() {
// Focus should only be advanced if this is the focused view and has become
// unfocusable. If the view is still focusable or is not focused, we can
// return early avoiding further unnecessary checks. Focusability check is
// performed first as it tends to be faster.
if (IsAccessibilityFocusable() || !HasFocus())
return;
FocusManager* focus_manager = GetFocusManager();
if (focus_manager)
focus_manager->AdvanceFocusIfNecessary();
}
// System events ---------------------------------------------------------------
void View::PropagateThemeChanged() {
{
internal::ScopedChildrenLock lock(this);
for (auto* child : base::Reversed(children_))
child->PropagateThemeChanged();
}
OnThemeChanged();
if (border_)
border_->OnViewThemeChanged(this);
if (background_)
background_->OnViewThemeChanged(this);
#if DCHECK_IS_ON()
DCHECK(on_theme_changed_called_)
<< "views::View::OnThemeChanged() has not been called. This means that "
"some class in the hierarchy is not calling their direct parent's "
"OnThemeChanged(). Please fix this by adding the missing call. Do not "
"call views::View::OnThemeChanged() directly unless views::View is "
"the direct parent class.";
on_theme_changed_called_ = false;
#endif
for (ViewObserver& observer : observers_)
observer.OnViewThemeChanged(this);
}
void View::PropagateDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
{
internal::ScopedChildrenLock lock(this);
for (auto* child : base::Reversed(children_)) {
child->PropagateDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
}
// If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
// through LayerDelegate callback.
if (!layer())
OnDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
// Tooltips --------------------------------------------------------------------
void View::UpdateTooltip() {
Widget* widget = GetWidget();
// TODO(beng): The TooltipManager nullptr check can be removed when we
// consolidate Init() methods and make views_unittests Init() all
// Widgets that it uses.
if (widget && widget->GetTooltipManager())
widget->GetTooltipManager()->UpdateTooltip();
}
// Drag and drop ---------------------------------------------------------------
bool View::DoDrag(const ui::LocatedEvent& event,
const gfx::Point& press_pt,
ui::mojom::DragEventSource source) {
int drag_operations = GetDragOperations(press_pt);
if (drag_operations == ui::DragDropTypes::DRAG_NONE)
return false;
Widget* widget = GetWidget();
// We should only start a drag from an event, implying we have a widget.
DCHECK(widget);
// Don't attempt to start a drag while in the process of dragging. This is
// especially important on X where we can get multiple mouse move events when
// we start the drag.
if (widget->dragged_view())
return false;
std::unique_ptr<OSExchangeData> data(std::make_unique<OSExchangeData>());
WriteDragData(press_pt, data.get());
// Message the RootView to do the drag and drop. That way if we're removed
// the RootView can detect it and avoid calling us back.
gfx::Point widget_location(event.location());
ConvertPointToWidget(this, &widget_location);
widget->RunShellDrag(this, std::move(data), widget_location, drag_operations,
source);
// WARNING: we may have been deleted.
return true;
}
View::DefaultFillLayout::DefaultFillLayout() = default;
View::DefaultFillLayout::~DefaultFillLayout() = default;
void View::DefaultFillLayout::Layout(View* host) {
const gfx::Rect contents_bounds = host->GetContentsBounds();
for (auto* child : host->children()) {
if (!child->GetProperty(kViewIgnoredByLayoutKey))
child->SetBoundsRect(contents_bounds);
}
}
gfx::Size View::DefaultFillLayout::GetPreferredSize(const View* host) const {
gfx::Size preferred_size;
for (auto* child : host->children()) {
if (!child->GetProperty(kViewIgnoredByLayoutKey))
preferred_size.SetToMax(child->GetPreferredSize());
}
return preferred_size;
}
int View::DefaultFillLayout::GetPreferredHeightForWidth(const View* host,
int width) const {
const gfx::Insets insets = host->GetInsets();
int preferred_height = 0;
for (auto* child : host->children()) {
if (!child->GetProperty(kViewIgnoredByLayoutKey)) {
preferred_height = std::max(
preferred_height,
child->GetHeightForWidth(width - insets.width()) + insets.height());
}
}
return preferred_height;
}
// This block requires the existence of METADATA_HEADER(View) in the class
// declaration for View.
BEGIN_METADATA_BASE(View)
ADD_PROPERTY_METADATA(std::unique_ptr<Background>, Background)
ADD_PROPERTY_METADATA(std::unique_ptr<Border>, Border)
ADD_READONLY_PROPERTY_METADATA(const char*, ClassName)
ADD_PROPERTY_METADATA(bool, Enabled)
ADD_PROPERTY_METADATA(View::FocusBehavior, FocusBehavior)
ADD_PROPERTY_METADATA(bool, FlipCanvasOnPaintForRTLUI)
ADD_PROPERTY_METADATA(int, Group)
ADD_PROPERTY_METADATA(int, Height)
ADD_PROPERTY_METADATA(int, ID)
ADD_READONLY_PROPERTY_METADATA(bool, IsDrawn);
ADD_READONLY_PROPERTY_METADATA(gfx::Size, MaximumSize)
ADD_READONLY_PROPERTY_METADATA(gfx::Size, MinimumSize)
ADD_PROPERTY_METADATA(bool, Mirrored)
ADD_PROPERTY_METADATA(bool, NotifyEnterExitOnChild)
ADD_READONLY_PROPERTY_METADATA(std::u16string, Tooltip)
ADD_PROPERTY_METADATA(bool, Visible)
ADD_PROPERTY_METADATA(bool, CanProcessEventsWithinSubtree)
ADD_PROPERTY_METADATA(bool, UseDefaultFillLayout)
ADD_PROPERTY_METADATA(int, Width)
ADD_PROPERTY_METADATA(int, X)
ADD_PROPERTY_METADATA(int, Y)
ADD_CLASS_PROPERTY_METADATA(gfx::Insets, kMarginsKey)
ADD_CLASS_PROPERTY_METADATA(gfx::Insets, kInternalPaddingKey)
ADD_CLASS_PROPERTY_METADATA(LayoutAlignment, kCrossAxisAlignmentKey)
ADD_CLASS_PROPERTY_METADATA(bool, kViewIgnoredByLayoutKey)
END_METADATA
} // namespace views
DEFINE_ENUM_CONVERTERS(views::View::FocusBehavior,
{views::View::FocusBehavior::ACCESSIBLE_ONLY,
u"ACCESSIBLE_ONLY"},
{views::View::FocusBehavior::ALWAYS, u"ALWAYS"},
{views::View::FocusBehavior::NEVER, u"NEVER"})
| Zhao-PengFei35/chromium_src_4 | ui/views/view.cc | C++ | unknown | 117,507 |
// 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_VIEW_H_
#define UI_VIEWS_VIEW_H_
#include <stddef.h>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/callback_list.h"
#include "base/containers/contains.h"
#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/strings/string_piece.h"
#include "base/supports_user_data.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/class_property.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/compositor/layer_observer.h"
#include "ui/compositor/layer_owner.h"
#include "ui/compositor/layer_type.h"
#include "ui/compositor/paint_cache.h"
#include "ui/events/event.h"
#include "ui/events/event_target.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/paint_info.h"
#include "ui/views/view_targeter.h"
#include "ui/views/views_export.h"
using ui::OSExchangeData;
namespace gfx {
class Canvas;
class Insets;
} // namespace gfx
namespace ui {
struct AXActionData;
class ColorProvider;
class Compositor;
class InputMethod;
class Layer;
class LayerTreeOwner;
class NativeTheme;
class PaintContext;
class ThemeProvider;
class TransformRecorder;
} // namespace ui
namespace views {
class Background;
class Border;
class ContextMenuController;
class DragController;
class FocusManager;
class FocusTraversable;
class LayoutProvider;
class ScrollView;
class SizeBounds;
class ViewAccessibility;
class ViewMaskLayer;
class ViewObserver;
class Widget;
class WordLookupClient;
namespace internal {
class PreEventDispatchHandler;
class PostEventDispatchHandler;
class RootView;
class ScopedChildrenLock;
} // namespace internal
// Struct used to describe how a View hierarchy has changed. See
// View::ViewHierarchyChanged.
// TODO(pbos): Move to a separate view_hierarchy_changed_details.h header.
struct VIEWS_EXPORT ViewHierarchyChangedDetails {
ViewHierarchyChangedDetails() = default;
ViewHierarchyChangedDetails(bool is_add,
View* parent,
View* child,
View* move_view)
: is_add(is_add), parent(parent), child(child), move_view(move_view) {}
bool is_add = false;
// New parent if |is_add| is true, old parent if |is_add| is false.
raw_ptr<View> parent = nullptr;
// The view being added or removed.
raw_ptr<View> child = nullptr;
// If this is a move (reparent), meaning AddChildViewAt() is invoked with an
// existing parent, then a notification for the remove is sent first,
// followed by one for the add. This case can be distinguished by a
// non-null |move_view|.
// For the remove part of move, |move_view| is the new parent of the View
// being removed.
// For the add part of move, |move_view| is the old parent of the View being
// added.
raw_ptr<View> move_view = nullptr;
};
using PropertyChangedCallback = ui::metadata::PropertyChangedCallback;
// The elements in PropertyEffects represent bits which define what effect(s) a
// changed Property has on the containing class. Additional elements should
// use the next most significant bit.
enum PropertyEffects {
kPropertyEffectsNone = 0,
// Any changes to the property should cause the container to invalidate the
// current layout state.
kPropertyEffectsLayout = 0x00000001,
// Changes to the property should cause the container to schedule a painting
// update.
kPropertyEffectsPaint = 0x00000002,
// Changes to the property should cause the preferred size to change. This
// implies kPropertyEffectsLayout.
kPropertyEffectsPreferredSizeChanged = 0x00000004,
};
// When adding layers to the view, this indicates the region into which the
// layer is placed, in the region above or beneath the view.
enum class LayerRegion {
kAbove,
kBelow,
};
// When calling |GetLayersInOrder|, this will indicate whether the View's
// own layer should be included in the returned vector or not.
enum class ViewLayer {
kInclude,
kExclude,
};
/////////////////////////////////////////////////////////////////////////////
//
// View class
//
// A View is a rectangle within the views View hierarchy. It is the base
// class for all Views.
//
// A View is a container of other Views (there is no such thing as a Leaf
// View - makes code simpler, reduces type conversion headaches, design
// mistakes etc)
//
// The View contains basic properties for sizing (bounds), layout (flex,
// orientation, etc), painting of children and event dispatch.
//
// The View also uses a simple Box Layout Manager similar to XUL's
// SprocketLayout system. Alternative Layout Managers implementing the
// LayoutManager interface can be used to lay out children if required.
//
// It is up to the subclass to implement Painting and storage of subclass -
// specific properties and functionality.
//
// Unless otherwise documented, views is not thread safe and should only be
// accessed from the main thread.
//
// Properties ------------------
//
// Properties which are intended to be dynamically visible through metadata to
// other subsystems, such as dev-tools must adhere to a naming convention,
// usage and implementation patterns.
//
// Properties start with their base name, such as "Frobble" (note the
// capitalization). The method to set the property must be called SetXXXX and
// the method to retrieve the value is called GetXXXX. For the aforementioned
// Frobble property, this would be SetFrobble and GetFrobble.
//
// void SetFrobble(bool is_frobble);
// bool GetFrobble() const;
//
// In the SetXXXX method, after the value storage location has been updated,
// OnPropertyChanged() must be called using the address of the storage
// location as a key. Additionally, any combination of PropertyEffects are
// also passed in. This will ensure that any desired side effects are properly
// invoked.
//
// void View::SetFrobble(bool is_frobble) {
// if (is_frobble == frobble_)
// return;
// frobble_ = is_frobble;
// OnPropertyChanged(&frobble_, kPropertyEffectsPaint);
// }
//
// Each property should also have a way to "listen" to changes by registering
// a callback.
//
// base::CallbackListSubscription AddFrobbleChangedCallback(
// PropertyChangedCallback callback);
//
// Each callback uses the the existing base::Bind mechanisms which allow for
// various kinds of callbacks; object methods, normal functions and lambdas.
//
// Example:
//
// class FrobbleView : public View {
// ...
// private:
// void OnFrobbleChanged();
// base::CallbackListSubscription frobble_changed_subscription_;
// }
//
// ...
// frobble_changed_subscription_ = AddFrobbleChangedCallback(
// base::BindRepeating(&FrobbleView::OnFrobbleChanged,
// base::Unretained(this)));
//
// Example:
//
// void MyView::ValidateFrobbleChanged() {
// bool frobble_changed = false;
// base::CallbackListSubscription subscription =
// frobble_view_->AddFrobbleChangedCallback(
// base::BindRepeating([](bool* frobble_changed_ptr) {
// *frobble_changed_ptr = true;
// }, &frobble_changed));
// frobble_view_->SetFrobble(!frobble_view_->GetFrobble());
// LOG() << frobble_changed ? "Frobble changed" : "Frobble NOT changed!";
// }
//
// Property metadata -----------
//
// For Views that expose properties which are intended to be dynamically
// discoverable by other subsystems, each View and its descendants must
// include metadata. These other subsystems, such as dev tools or a delarative
// layout system, can then enumerate the properties on any given instance or
// class. Using the enumerated information, the actual values of the
// properties can be read or written. This will be done by getting and setting
// the values using string representations. The metadata can also be used to
// instantiate and initialize a View (or descendant) class from a declarative
// "script".
//
// For each View class in their respective header declaration, place the macro
// METADATA_HEADER(<classname>) in the public section.
//
// In the implementing .cc file, add the following macros to the same
// namespace in which the class resides.
//
// BEGIN_METADATA(View, ParentView)
// ADD_PROPERTY_METADATA(bool, Frobble)
// END_METADATA
//
// For each property, add a definition using ADD_PROPERTY_METADATA() between
// the begin and end macros.
//
// Descendant classes must specify the parent class as a macro parameter.
//
// BEGIN_METADATA(MyView, views::View)
// ADD_PROPERTY_METADATA(int, Bobble)
// END_METADATA
/////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT View : public ui::LayerDelegate,
public ui::LayerObserver,
public ui::LayerOwner,
public ui::AcceleratorTarget,
public ui::EventTarget,
public ui::EventHandler,
public ui::PropertyHandler,
public ui::metadata::MetaDataProvider,
public base::SupportsUserData {
public:
using Views = std::vector<View*>;
// TODO(crbug.com/1289902): The |event| parameter is being removed. Do not add
// new callers.
using DropCallback = base::OnceCallback<void(
const ui::DropTargetEvent& event,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner)>;
METADATA_HEADER_BASE(View);
enum class FocusBehavior {
// Use when the View is never focusable. Default.
NEVER,
// Use when the View is to be focusable both in regular and accessibility
// mode.
ALWAYS,
// Use when the View is focusable only during accessibility mode.
ACCESSIBLE_ONLY,
};
// During paint, the origin of each view in physical pixel is calculated by
// view_origin_pixel = ROUND(view.origin() * device_scale_factor)
//
// Thus in a view hierarchy, the offset between two views, view_i and view_j,
// is calculated by:
// view_offset_ij_pixel = SUM [view_origin_pixel.OffsetFromOrigin()]
// {For all views along the path from view_i to view_j}
//
// But the offset between the two layers, the layer in view_i and the layer in
// view_j, is computed by
// view_offset_ij_dip = SUM [view.origin().OffsetFromOrigin()]
// {For all views along the path from view_i to view_j}
//
// layer_offset_ij_pixel = ROUND (view_offset_ij_dip * device_scale_factor)
//
// Due to this difference in the logic for computation of offset, the values
// view_offset_ij_pixel and layer_offset_ij_pixel may not always be equal.
// They will differ by some subpixel_offset. This leads to bugs like
// crbug.com/734787.
// The subpixel offset needs to be applied to the layer to get the correct
// output during paint.
//
// This class manages the computation of subpixel offset internally when
// working with offsets.
class LayerOffsetData {
public:
explicit LayerOffsetData(float device_scale_factor = 1.f,
const gfx::Vector2d& offset = gfx::Vector2d())
: device_scale_factor_(device_scale_factor) {
AddOffset(offset);
}
const gfx::Vector2d& offset() const { return offset_; }
const gfx::Vector2dF GetSubpixelOffset() const {
// |rounded_pixel_offset_| is stored in physical pixel space. Convert it
// into DIP space before returning.
gfx::Vector2dF subpixel_offset(rounded_pixel_offset_);
subpixel_offset.InvScale(device_scale_factor_);
return subpixel_offset;
}
LayerOffsetData& operator+=(const gfx::Vector2d& offset) {
AddOffset(offset);
return *this;
}
LayerOffsetData operator+(const gfx::Vector2d& offset) const {
LayerOffsetData offset_data(*this);
offset_data.AddOffset(offset);
return offset_data;
}
private:
// Adds the |offset_to_parent| to the total |offset_| and updates the
// |rounded_pixel_offset_| value.
void AddOffset(const gfx::Vector2d& offset_to_parent) {
// Add the DIP |offset_to_parent| amount to the total offset.
offset_ += offset_to_parent;
// Convert |offset_to_parent| to physical pixel coordinates.
gfx::Vector2dF fractional_pixel_offset(
offset_to_parent.x() * device_scale_factor_,
offset_to_parent.y() * device_scale_factor_);
// Since pixels cannot be fractional, we need to round the offset to get
// the correct physical pixel coordinate.
gfx::Vector2d integral_pixel_offset =
gfx::ToRoundedVector2d(fractional_pixel_offset);
// |integral_pixel_offset - fractional_pixel_offset| gives the subpixel
// offset amount for |offset_to_parent|. This is added to
// |rounded_pixel_offset_| to update the total subpixel offset.
rounded_pixel_offset_ += integral_pixel_offset - fractional_pixel_offset;
}
// Total offset so far. This stores the offset between two nodes in the view
// hierarchy.
gfx::Vector2d offset_;
// This stores the value such that if added to
// |offset_ * device_scale_factor| will give the correct aligned offset in
// physical pixels.
gfx::Vector2dF rounded_pixel_offset_;
// The device scale factor at which the subpixel offset is being computed.
float device_scale_factor_;
};
// Creation and lifetime -----------------------------------------------------
View();
View(const View&) = delete;
View& operator=(const View&) = delete;
~View() override;
// By default a View is owned by its parent unless specified otherwise here.
void set_owned_by_client() { owned_by_client_ = true; }
bool owned_by_client() const { return owned_by_client_; }
// Tree operations -----------------------------------------------------------
// Get the Widget that hosts this View, if any.
virtual const Widget* GetWidget() const;
virtual Widget* GetWidget();
// Adds |view| as a child of this view, optionally at |index|.
// Returns the raw pointer for callers which want to hold a pointer to the
// added view. This requires declaring the function as a template in order to
// return the actual passed-in type.
template <typename T>
T* AddChildView(std::unique_ptr<T> view) {
DCHECK(!view->owned_by_client())
<< "This should only be called if the client is passing ownership of "
"|view| to the parent View.";
return AddChildView<T>(view.release());
}
template <typename T>
T* AddChildViewAt(std::unique_ptr<T> view, size_t index) {
DCHECK(!view->owned_by_client())
<< "This should only be called if the client is passing ownership of "
"|view| to the parent View.";
return AddChildViewAt<T>(view.release(), index);
}
// Prefer using the AddChildView(std::unique_ptr) overloads over raw pointers
// for new code.
template <typename T>
T* AddChildView(T* view) {
AddChildViewAtImpl(view, children_.size());
return view;
}
template <typename T>
T* AddChildViewAt(T* view, size_t index) {
AddChildViewAtImpl(view, index);
return view;
}
// Moves |view| to the specified |index|. An |index| at least as large as that
// of the last child moves the view to the end.
void ReorderChildView(View* view, size_t index);
// Removes |view| from this view. The view's parent will change to null.
void RemoveChildView(View* view);
// Removes |view| from this view and transfers ownership back to the caller in
// the form of a std::unique_ptr<T>.
// TODO(kylixrd): Rename back to RemoveChildView() once the code is refactored
// to eliminate the uses of the old RemoveChildView().
template <typename T>
std::unique_ptr<T> RemoveChildViewT(T* view) {
DCHECK(!view->owned_by_client())
<< "This should only be called if the client doesn't already have "
"ownership of |view|.";
DCHECK(base::Contains(children_, view));
RemoveChildView(view);
return base::WrapUnique(view);
}
// Partially specialized version to directly take a raw_ptr<T>.
template <typename T>
std::unique_ptr<T> RemoveChildViewT(raw_ptr<T> view) {
return RemoveChildViewT(view.get());
}
// Removes all the children from this view. This deletes all children that are
// not set_owned_by_client(), which is deprecated.
void RemoveAllChildViews();
// TODO(pbos): Remove this method, deleting children when removing them should
// not be optional. If ownership needs to be preserved, use RemoveChildViewT()
// to retain ownership of the removed children.
void RemoveAllChildViewsWithoutDeleting();
const Views& children() const { return children_; }
// Returns the parent view.
const View* parent() const { return parent_; }
View* parent() { return parent_; }
// Returns true if |view| is contained within this View's hierarchy, even as
// an indirect descendant. Will return true if child is also this view.
bool Contains(const View* view) const;
// Returns an iterator pointing to |view|, or children_.cend() if |view| is
// not a child of this view.
Views::const_iterator FindChild(const View* view) const;
// Returns the index of |view|, or nullopt if |view| is not a child of this
// view.
absl::optional<size_t> GetIndexOf(const View* view) const;
// Size and disposition ------------------------------------------------------
// Methods for obtaining and modifying the position and size of the view.
// Position is in the coordinate system of the view's parent.
// Position is NOT flipped for RTL. See "RTL positioning" for RTL-sensitive
// position accessors.
// Transformations are not applied on the size/position. For example, if
// bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the
// width will still be 100 (although when painted, it will be 50x100, painted
// at location (0, 0)).
void SetBounds(int x, int y, int width, int height);
void SetBoundsRect(const gfx::Rect& bounds);
void SetSize(const gfx::Size& size);
void SetPosition(const gfx::Point& position);
void SetX(int x);
void SetY(int y);
// No transformation is applied on the size or the locations.
const gfx::Rect& bounds() const { return bounds_; }
int x() const { return bounds_.x(); }
int y() const { return bounds_.y(); }
int width() const { return bounds_.width(); }
int height() const { return bounds_.height(); }
const gfx::Point& origin() const { return bounds_.origin(); }
const gfx::Size& size() const { return bounds_.size(); }
// Returns the bounds of the content area of the view, i.e. the rectangle
// enclosed by the view's border.
gfx::Rect GetContentsBounds() const;
// Returns the bounds of the view in its own coordinates (i.e. position is
// 0, 0).
gfx::Rect GetLocalBounds() const;
// Returns the insets of the current border. If there is no border an empty
// insets is returned.
virtual gfx::Insets GetInsets() const;
// Returns the visible bounds of the receiver in the receivers coordinate
// system.
//
// When traversing the View hierarchy in order to compute the bounds, the
// function takes into account the mirroring setting and transformation for
// each View and therefore it will return the mirrored and transformed version
// of the visible bounds if need be.
gfx::Rect GetVisibleBounds() const;
// Return the bounds of the View in screen coordinate system.
gfx::Rect GetBoundsInScreen() const;
// Return the bounds that an anchored widget should anchor to. These can be
// different from |GetBoundsInScreen()| when a view is larger than its visible
// size, for instance to provide a larger hittable area.
virtual gfx::Rect GetAnchorBoundsInScreen() const;
// Returns the baseline of this view, or -1 if this view has no baseline. The
// return value is relative to the preferred height.
virtual int GetBaseline() const;
// Get the size the View would like to be under the current bounds.
// If the View is never laid out before, assume it to be laid out in an
// unbounded space.
// TODO(crbug.com/1346889): Don't use this. Use the size-constrained
// GetPreferredSize(const SizeBounds&) instead.
gfx::Size GetPreferredSize() const;
// Get the size the View would like to be given `available_size`, ignoring the
// current bounds.
gfx::Size GetPreferredSize(const SizeBounds& available_size) const;
// Sets or unsets the size that this View will request during layout. The
// actual size may differ. It should rarely be necessary to set this; usually
// the right approach is controlling the parent's layout via a LayoutManager.
void SetPreferredSize(absl::optional<gfx::Size> size);
// Convenience method that sizes this view to its preferred size.
void SizeToPreferredSize();
// Gets the minimum size of the view. View's implementation invokes
// GetPreferredSize.
virtual gfx::Size GetMinimumSize() const;
// Gets the maximum size of the view. Currently only used for sizing shell
// windows.
virtual gfx::Size GetMaximumSize() const;
// Return the preferred height for a specific width. Override if the
// preferred height depends upon the width (such as a multi-line label). If
// a LayoutManger has been installed this returns the value of
// LayoutManager::GetPreferredHeightForWidth(), otherwise this returns
// GetPreferredSize().height().
virtual int GetHeightForWidth(int w) const;
// Returns a bound on the available space for a child view, for example, in
// case the child view wants to play an animation that would cause it to
// become larger. Default is not to bound the available size; it is the
// responsibility of specific view/layout manager implementations to determine
// if and when a bound applies.
virtual SizeBounds GetAvailableSize(const View* child) const;
// The |Visible| property. See comment above for instructions on declaring and
// implementing a property.
//
// Sets whether this view is visible. Painting is scheduled as needed. Also,
// clears focus if the focused view or one of its ancestors is set to be
// hidden.
virtual void SetVisible(bool visible);
// Return whether a view is visible.
bool GetVisible() const;
// Adds a callback associated with the above Visible property. The callback
// will be invoked whenever the Visible property changes.
[[nodiscard]] base::CallbackListSubscription AddVisibleChangedCallback(
PropertyChangedCallback callback);
// Returns true if this view is drawn on screen.
virtual bool IsDrawn() const;
// The |Enabled| property. See comment above for instructions on declaring and
// implementing a property.
//
// Set whether this view is enabled. A disabled view does not receive keyboard
// or mouse inputs. If |enabled| differs from the current value, SchedulePaint
// is invoked. Also, clears focus if the focused view is disabled.
void SetEnabled(bool enabled);
// Returns whether the view is enabled.
bool GetEnabled() const;
// Adds a callback associated with the above |Enabled| property. The callback
// will be invoked whenever the property changes.
[[nodiscard]] base::CallbackListSubscription AddEnabledChangedCallback(
PropertyChangedCallback callback);
// Returns the child views ordered in reverse z-order. That is, views later in
// the returned vector have a higher z-order (are painted later) than those
// early in the vector. The returned vector has exactly the same number of
// Views as |children_|. The default implementation returns |children_|,
// subclass if the paint order should differ from that of |children_|.
// This order is taken into account by painting and targeting implementations.
// NOTE: see SetPaintToLayer() for details on painting and views with layers.
virtual Views GetChildrenInZOrder();
// Transformations -----------------------------------------------------------
// Methods for setting transformations for a view (e.g. rotation, scaling).
// Care should be taken not to transform a view in such a way that its bounds
// lie outside those of its parent, or else the default ViewTargeterDelegate
// implementation will not pass mouse events to the view.
gfx::Transform GetTransform() const;
// Clipping is done relative to the view's local bounds.
void SetClipPath(const SkPath& path);
const SkPath& clip_path() const { return clip_path_; }
// Sets the transform to the supplied transform.
void SetTransform(const gfx::Transform& transform);
// Accelerated painting ------------------------------------------------------
// Sets whether this view paints to a layer. A view paints to a layer if
// either of the following are true:
// . the view has a non-identity transform.
// . SetPaintToLayer(ui::LayerType) has been invoked.
// View creates the Layer only when it exists in a Widget with a non-NULL
// Compositor.
// Enabling a view to have a layer impacts painting of sibling views.
// Specifically views with layers effectively paint in a z-order that is
// always above any sibling views that do not have layers. This happens
// regardless of the ordering returned by GetChildrenInZOrder().
void SetPaintToLayer(ui::LayerType layer_type = ui::LAYER_TEXTURED);
// Cancels layer painting triggered by a call to |SetPaintToLayer()|. Note
// that this will not actually destroy the layer if the view paints to a layer
// for another reason.
void DestroyLayer();
// Add or remove layers above or below this view. This view does not take
// ownership of the layers. It is the caller's responsibility to keep track of
// this View's size and update their layer accordingly.
//
// In very rare cases, it may be necessary to override these. If any of this
// view's contents must be painted to the same layer as its parent, or can't
// handle being painted with transparency, overriding might be appropriate.
// One example is LabelButton, where the label must paint below any added
// layers for subpixel rendering reasons. Overrides should be made
// judiciously, and generally they should just forward the calls to a child
// view. They must be overridden together for correctness.
virtual void AddLayerToRegion(ui::Layer* new_layer, LayerRegion region);
virtual void RemoveLayerFromRegions(ui::Layer* old_layer);
// This is like RemoveLayerFromRegions() but doesn't remove |old_layer| from
// its parent. This is useful for when a layer beneth this view is owned by a
// ui::LayerOwner which just recreated it (by calling RecreateLayer()). In
// this case, this function can be called to remove it from |layers_below_| or
// |layers_above_|, and to stop observing it, but it remains in the layer tree
// since the expectation of ui::LayerOwner::RecreateLayer() is that the old
// layer remains under the same parent, and stacked above the newly cloned
// layer.
void RemoveLayerFromRegionsKeepInLayerTree(ui::Layer* old_layer);
// Gets the layers associated with this view that should be immediate children
// of the parent layer. They are returned in bottom-to-top order. This
// optionally includes |this->layer()| and any layers added with
// |AddLayerToRegion()|.
// Returns an empty vector if this view doesn't paint to a layer.
std::vector<ui::Layer*> GetLayersInOrder(
ViewLayer view_layer = ViewLayer::kInclude);
// ui::LayerObserver:
void LayerDestroyed(ui::Layer* layer) override;
// Overridden from ui::LayerOwner:
std::unique_ptr<ui::Layer> RecreateLayer() override;
// RTL positioning -----------------------------------------------------------
// Methods for accessing the bounds and position of the view, relative to its
// parent. The position returned is mirrored if the parent view is using a RTL
// layout.
//
// NOTE: in the vast majority of the cases, the mirroring implementation is
// transparent to the View subclasses and therefore you should use the
// bounds() accessor instead.
gfx::Rect GetMirroredBounds() const;
gfx::Rect GetMirroredContentsBounds() const;
gfx::Point GetMirroredPosition() const;
int GetMirroredX() const;
// Given a rectangle specified in this View's coordinate system, the function
// computes the 'left' value for the mirrored rectangle within this View. If
// the View's UI layout is not right-to-left, then bounds.x() is returned.
//
// UI mirroring is transparent to most View subclasses and therefore there is
// no need to call this routine from anywhere within your subclass
// implementation.
int GetMirroredXForRect(const gfx::Rect& rect) const;
// Given a rectangle specified in this View's coordinate system, the function
// computes the mirrored rectangle.
gfx::Rect GetMirroredRect(const gfx::Rect& rect) const;
// Given the X coordinate of a point inside the View, this function returns
// the mirrored X coordinate of the point if the View's UI layout is
// right-to-left. If the layout is left-to-right, the same X coordinate is
// returned.
//
// Following are a few examples of the values returned by this function for
// a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
//
// GetMirroredXCoordinateInView(0) -> 100
// GetMirroredXCoordinateInView(20) -> 80
// GetMirroredXCoordinateInView(99) -> 1
int GetMirroredXInView(int x) const;
// Given a X coordinate and a width inside the View, this function returns
// the mirrored X coordinate if the View's UI layout is right-to-left. If the
// layout is left-to-right, the same X coordinate is returned.
//
// Following are a few examples of the values returned by this function for
// a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
//
// GetMirroredXCoordinateInView(0, 10) -> 90
// GetMirroredXCoordinateInView(20, 20) -> 60
int GetMirroredXWithWidthInView(int x, int w) const;
// Layout --------------------------------------------------------------------
// Lay out the child Views (set their bounds based on sizing heuristics
// specific to the current Layout Manager)
virtual void Layout();
bool needs_layout() const { return needs_layout_; }
// Mark this view and all parents to require a relayout. This ensures the
// next call to Layout() will propagate to this view, even if the bounds of
// parent views do not change.
void InvalidateLayout();
// TODO(kylixrd): Update comment once UseDefaultFillLayout is true by default.
// UseDefaultFillLayout will be set to true by default once the codebase is
// audited and refactored.
//
// Gets/Sets the Layout Manager used by this view to size and place its
// children. NOTE: This will force UseDefaultFillLayout to false if it had
// been set to true.
//
// The LayoutManager is owned by the View and is deleted when the view is
// deleted, or when a new LayoutManager is installed. Call
// SetLayoutManager(nullptr) to clear it.
//
// SetLayoutManager returns a bare pointer version of the input parameter
// (now owned by the view). If code needs to use the layout manager after
// being assigned, use this pattern:
//
// views::BoxLayout* box_layout = SetLayoutManager(
// std::make_unique<views::BoxLayout>(...));
// box_layout->Foo();
LayoutManager* GetLayoutManager() const;
template <typename LayoutManager>
LayoutManager* SetLayoutManager(
std::unique_ptr<LayoutManager> layout_manager) {
LayoutManager* lm = layout_manager.get();
SetLayoutManagerImpl(std::move(layout_manager));
return lm;
}
void SetLayoutManager(std::nullptr_t);
// Sets whether or not the default layout manager should be used for this
// view. NOTE: this can only be set if |layout_manager_| isn't assigned.
bool GetUseDefaultFillLayout() const;
void SetUseDefaultFillLayout(bool value);
// Attributes ----------------------------------------------------------------
// Recursively descends the view tree starting at this view, and returns
// the first child that it encounters that has the given ID.
// Returns NULL if no matching child view is found.
const View* GetViewByID(int id) const;
View* GetViewByID(int id);
// Gets and sets the ID for this view. ID should be unique within the subtree
// that you intend to search for it. 0 is the default ID for views.
int GetID() const { return id_; }
void SetID(int id);
// Adds a callback associated with the above |ID| property. The callback will
// be invoked whenever the property changes.
[[nodiscard]] base::CallbackListSubscription AddIDChangedCallback(
PropertyChangedCallback callback);
// A group id is used to tag views which are part of the same logical group.
// Focus can be moved between views with the same group using the arrow keys.
// Groups are currently used to implement radio button mutual exclusion.
// The group id is immutable once it's set.
void SetGroup(int gid);
// Returns the group id of the view, or -1 if the id is not set yet.
int GetGroup() const;
// Adds a callback associated with the above |Group| property. The callback
// will be invoked whenever the property changes.
[[nodiscard]] base::CallbackListSubscription AddGroupChangedCallback(
PropertyChangedCallback callback);
// If this returns true, the views from the same group can each be focused
// when moving focus with the Tab/Shift-Tab key. If this returns false,
// only the selected view from the group (obtained with
// GetSelectedViewForGroup()) is focused.
virtual bool IsGroupFocusTraversable() const;
// Fills |views| with all the available views which belong to the provided
// |group|.
void GetViewsInGroup(int group, Views* views);
// Returns the View that is currently selected in |group|.
// The default implementation simply returns the first View found for that
// group.
virtual View* GetSelectedViewForGroup(int group);
// Coordinate conversion -----------------------------------------------------
// Note that the utility coordinate conversions functions always operate on
// the mirrored position of the child Views if the parent View uses a
// right-to-left UI layout.
// Converts a point from the coordinate system of one View to another.
//
// |source| and |target| must be in the same widget, but don't need to be in
// the same view hierarchy.
// Neither |source| nor |target| can be null.
[[nodiscard]] static gfx::Point ConvertPointToTarget(const View* source,
const View* target,
const gfx::Point& point);
// The in-place version of this method is strongly discouraged, please use the
// by-value version above for improved const-compatability and readability.
static void ConvertPointToTarget(const View* source,
const View* target,
gfx::Point* point);
// Converts |rect| from the coordinate system of |source| to the coordinate
// system of |target|.
//
// |source| and |target| must be in the same widget, but don't need to be in
// the same view hierarchy.
// Neither |source| nor |target| can be null.
[[nodiscard]] static gfx::RectF ConvertRectToTarget(const View* source,
const View* target,
const gfx::RectF& rect);
// The in-place version of this method is strongly discouraged, please use the
// by-value version above for improved const-compatability and readability.
static void ConvertRectToTarget(const View* source,
const View* target,
gfx::RectF* rect);
// Converts |rect| from the coordinate system of |source| to the
// coordinate system of |target|.
//
// |source| and |target| must be in the same widget, but don't need to be in
// the same view hierarchy.
// Neither |source| nor |target| can be null.
//
// Returns the enclosed rect with default allowed conversion error
// (0.00001f).
static gfx::Rect ConvertRectToTarget(const View* source,
const View* target,
gfx::Rect& rect);
// Converts a point from a View's coordinate system to that of its Widget.
static void ConvertPointToWidget(const View* src, gfx::Point* point);
// Converts a point from the coordinate system of a View's Widget to that
// View's coordinate system.
static void ConvertPointFromWidget(const View* dest, gfx::Point* p);
// Converts a point from a View's coordinate system to that of the screen.
[[nodiscard]] static gfx::Point ConvertPointToScreen(const View* src,
const gfx::Point& point);
// The in-place version of this method is strongly discouraged, please use the
// by-value version above for improved const-compatability and readability.
static void ConvertPointToScreen(const View* src, gfx::Point* point);
// Converts a point from the screen coordinate system to that View's
// coordinate system.
[[nodiscard]] static gfx::Point ConvertPointFromScreen(
const View* src,
const gfx::Point& point);
// The in-place version of this method is strongly discouraged, please use the
// by-value version above for improved const-compatability and readability.
static void ConvertPointFromScreen(const View* dst, gfx::Point* point);
// Converts a rect from a View's coordinate system to that of the screen.
static void ConvertRectToScreen(const View* src, gfx::Rect* rect);
// Applies transformation on the rectangle, which is in the view's coordinate
// system, to convert it into the parent's coordinate system.
gfx::Rect ConvertRectToParent(const gfx::Rect& rect) const;
// Converts a rectangle from this views coordinate system to its widget
// coordinate system.
gfx::Rect ConvertRectToWidget(const gfx::Rect& rect) const;
// Painting ------------------------------------------------------------------
// Mark all or part of the View's bounds as dirty (needing repaint).
// |r| is in the View's coordinates.
// TODO(beng): Make protected.
void SchedulePaint();
void SchedulePaintInRect(const gfx::Rect& r);
// Called by the framework to paint a View. Performs translation and clipping
// for View coordinates and language direction as required, allows the View
// to paint itself via the various OnPaint*() event handlers and then paints
// the hierarchy beneath it.
void Paint(const PaintInfo& parent_paint_info);
// The background object may be null.
void SetBackground(std::unique_ptr<Background> b);
Background* GetBackground() const;
const Background* background() const { return background_.get(); }
Background* background() { return background_.get(); }
// The border object may be null.
virtual void SetBorder(std::unique_ptr<Border> b);
Border* GetBorder() const;
// Get the theme provider from the parent widget.
const ui::ThemeProvider* GetThemeProvider() const;
// Get the layout provider for the View.
const LayoutProvider* GetLayoutProvider() const;
// Returns the ColorProvider from the ColorProviderManager.
ui::ColorProvider* GetColorProvider() {
return const_cast<ui::ColorProvider*>(
std::as_const(*this).GetColorProvider());
}
const ui::ColorProvider* GetColorProvider() const;
// Returns the NativeTheme to use for this View. This calls through to
// GetNativeTheme() on the Widget this View is in, or provides a default
// theme if there's no widget, or returns |native_theme_| if that's
// set. Warning: the default theme might not be correct; you should probably
// override OnThemeChanged().
ui::NativeTheme* GetNativeTheme() {
return const_cast<ui::NativeTheme*>(std::as_const(*this).GetNativeTheme());
}
const ui::NativeTheme* GetNativeTheme() const;
// Sets the native theme and informs descendants.
void SetNativeThemeForTesting(ui::NativeTheme* theme);
// RTL painting --------------------------------------------------------------
// Returns whether the gfx::Canvas object passed to Paint() needs to be
// transformed such that anything drawn on the canvas object during Paint()
// is flipped horizontally.
bool GetFlipCanvasOnPaintForRTLUI() const;
// Enables or disables flipping of the gfx::Canvas during Paint(). Note that
// if canvas flipping is enabled, the canvas will be flipped only if the UI
// layout is right-to-left; that is, the canvas will be flipped only if
// GetMirrored() is true.
//
// Enabling canvas flipping is useful for leaf views that draw an image that
// needs to be flipped horizontally when the UI layout is right-to-left
// (views::Button, for example). This method is helpful for such classes
// because their drawing logic stays the same and they can become agnostic to
// the UI directionality.
void SetFlipCanvasOnPaintForRTLUI(bool enable);
// Adds a callback associated with the above FlipCanvasOnPaintForRTLUI
// property. The callback will be invoked whenever the
// FlipCanvasOnPaintForRTLUI property changes.
[[nodiscard]] base::CallbackListSubscription
AddFlipCanvasOnPaintForRTLUIChangedCallback(PropertyChangedCallback callback);
// When set, this view will ignore base::l18n::IsRTL() and instead be drawn
// according to |is_mirrored|.
//
// This is useful for views that should be displayed the same regardless of UI
// direction. Unlike SetFlipCanvasOnPaintForRTLUI this setting has an effect
// on the visual order of child views.
//
// This setting does not propagate to child views. So while the visual order
// of this view's children may change, the visual order of this view's
// grandchildren in relation to their parents are unchanged.
void SetMirrored(bool is_mirrored);
bool GetMirrored() const;
// Input ---------------------------------------------------------------------
// The points, rects, mouse locations, and touch locations in the following
// functions are in the view's coordinates, except for a RootView.
// A convenience function which calls into GetEventHandlerForRect() with
// a 1x1 rect centered at |point|. |point| is in the local coordinate
// space of |this|.
View* GetEventHandlerForPoint(const gfx::Point& point);
// Returns the View that should be the target of an event having |rect| as
// its location, or NULL if no such target exists. |rect| is in the local
// coordinate space of |this|.
View* GetEventHandlerForRect(const gfx::Rect& rect);
// Returns the deepest visible descendant that contains the specified point
// and supports tooltips. If the view does not contain the point, returns
// NULL.
virtual View* GetTooltipHandlerForPoint(const gfx::Point& point);
// Return the cursor that should be used for this view or the default cursor.
// The event location is in the receiver's coordinate system. The caller is
// responsible for managing the lifetime of the returned object, though that
// lifetime may vary from platform to platform. On Windows and Aura,
// the cursor is a shared resource.
virtual ui::Cursor GetCursor(const ui::MouseEvent& event);
// A convenience function which calls HitTestRect() with a rect of size
// 1x1 and an origin of |point|. |point| is in the local coordinate space
// of |this|.
bool HitTestPoint(const gfx::Point& point) const;
// Returns true if |rect| intersects this view's bounds. |rect| is in the
// local coordinate space of |this|.
bool HitTestRect(const gfx::Rect& rect) const;
// Returns true if this view or any of its descendants are permitted to
// be the target of an event.
virtual bool GetCanProcessEventsWithinSubtree() const;
// Sets whether this view or any of its descendants are permitted to be the
// target of an event.
void SetCanProcessEventsWithinSubtree(bool can_process);
// Returns true if the mouse cursor is over |view| and mouse events are
// enabled.
bool IsMouseHovered() const;
// This method is invoked when the user clicks on this view.
// The provided event is in the receiver's coordinate system.
//
// Return true if you processed the event and want to receive subsequent
// MouseDragged and MouseReleased events. This also stops the event from
// bubbling. If you return false, the event will bubble through parent
// views.
//
// If you remove yourself from the tree while processing this, event bubbling
// stops as if you returned true, but you will not receive future events.
// The return value is ignored in this case.
//
// Default implementation returns true if a ContextMenuController has been
// set, false otherwise. Override as needed.
//
virtual bool OnMousePressed(const ui::MouseEvent& event);
// This method is invoked when the user clicked on this control.
// and is still moving the mouse with a button pressed.
// The provided event is in the receiver's coordinate system.
//
// Return true if you processed the event and want to receive
// subsequent MouseDragged and MouseReleased events.
//
// Default implementation returns true if a ContextMenuController has been
// set, false otherwise. Override as needed.
//
virtual bool OnMouseDragged(const ui::MouseEvent& event);
// This method is invoked when the user releases the mouse
// button. The event is in the receiver's coordinate system.
//
// Default implementation notifies the ContextMenuController is appropriate.
// Subclasses that wish to honor the ContextMenuController should invoke
// super.
virtual void OnMouseReleased(const ui::MouseEvent& event);
// This method is invoked when the mouse press/drag was canceled by a
// system/user gesture.
virtual void OnMouseCaptureLost();
// This method is invoked when the mouse is above this control
// The event is in the receiver's coordinate system.
//
// Default implementation does nothing. Override as needed.
virtual void OnMouseMoved(const ui::MouseEvent& event);
// This method is invoked when the mouse enters this control.
//
// Default implementation does nothing. Override as needed.
virtual void OnMouseEntered(const ui::MouseEvent& event);
// This method is invoked when the mouse exits this control
// The provided event location is always (0, 0)
// Default implementation does nothing. Override as needed.
virtual void OnMouseExited(const ui::MouseEvent& event);
// Set both the MouseHandler and the GestureHandler for a drag session.
//
// A drag session is a stream of mouse events starting
// with a MousePressed event, followed by several MouseDragged
// events and finishing with a MouseReleased event.
//
// This method should be only invoked while processing a
// MouseDragged or MousePressed event.
//
// All further mouse dragged and mouse up events will be sent
// the MouseHandler, even if it is reparented to another window.
//
// The MouseHandler is automatically cleared when the control
// comes back from processing the MouseReleased event.
//
// Note: if the mouse handler is no longer connected to a
// view hierarchy, events won't be sent.
virtual void SetMouseAndGestureHandler(View* new_handler);
// Sets a new mouse handler.
virtual void SetMouseHandler(View* new_handler);
// Invoked when a key is pressed or released.
// Subclasses should return true if the event has been processed and false
// otherwise. If the event has not been processed, the parent will be given a
// chance.
virtual bool OnKeyPressed(const ui::KeyEvent& event);
virtual bool OnKeyReleased(const ui::KeyEvent& event);
// Invoked when the user uses the mousewheel. Implementors should return true
// if the event has been processed and false otherwise. This message is sent
// if the view is focused. If the event has not been processed, the parent
// will be given a chance.
virtual bool OnMouseWheel(const ui::MouseWheelEvent& event);
// See field for description.
void SetNotifyEnterExitOnChild(bool notify);
bool GetNotifyEnterExitOnChild() const;
// Convenience method to retrieve the InputMethod associated with the
// Widget that contains this view.
ui::InputMethod* GetInputMethod() {
return const_cast<ui::InputMethod*>(std::as_const(*this).GetInputMethod());
}
const ui::InputMethod* GetInputMethod() const;
// Sets a new ViewTargeter for the view, and returns the previous
// ViewTargeter.
std::unique_ptr<ViewTargeter> SetEventTargeter(
std::unique_ptr<ViewTargeter> targeter);
// Returns the ViewTargeter installed on |this| if one exists,
// otherwise returns the ViewTargeter installed on our root view.
// The return value is guaranteed to be non-null.
ViewTargeter* GetEffectiveViewTargeter() const;
ViewTargeter* targeter() const { return targeter_.get(); }
// Returns the WordLookupClient associated with this view.
virtual WordLookupClient* GetWordLookupClient();
// Overridden from ui::EventTarget:
bool CanAcceptEvent(const ui::Event& event) override;
ui::EventTarget* GetParentTarget() override;
std::unique_ptr<ui::EventTargetIterator> GetChildIterator() const override;
ui::EventTargeter* GetEventTargeter() override;
void ConvertEventToTarget(const ui::EventTarget* target,
ui::LocatedEvent* event) const override;
gfx::PointF GetScreenLocationF(const ui::LocatedEvent& event) const override;
// Overridden from ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnTouchEvent(ui::TouchEvent* event) final;
void OnGestureEvent(ui::GestureEvent* event) override;
base::StringPiece GetLogContext() const override;
// Accelerators --------------------------------------------------------------
// Sets a keyboard accelerator for that view. When the user presses the
// accelerator key combination, the AcceleratorPressed method is invoked.
// Note that you can set multiple accelerators for a view by invoking this
// method several times. Note also that AcceleratorPressed is invoked only
// when CanHandleAccelerators() is true.
void AddAccelerator(const ui::Accelerator& accelerator);
// Removes the specified accelerator for this view.
void RemoveAccelerator(const ui::Accelerator& accelerator);
// Removes all the keyboard accelerators for this view.
void ResetAccelerators();
// Overridden from AcceleratorTarget:
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
// Returns whether accelerators are enabled for this view. Accelerators are
// enabled if the containing widget is visible and the view is enabled() and
// IsDrawn()
bool CanHandleAccelerators() const override;
// Focus ---------------------------------------------------------------------
// Returns whether this view currently has the focus.
virtual bool HasFocus() const;
// Returns the view that is a candidate to be focused next when pressing Tab.
//
// The returned view might not be `IsFocusable`, but it's children can be
// traversed to evaluate if one of them `IsFocusable`.
//
// If this returns `nullptr` then it is the last focusable candidate view in
// the list including its siblings.
View* GetNextFocusableView();
const View* GetNextFocusableView() const;
// Returns the view that is a candidate to be focused next when pressing
// Shift-Tab.
//
// The returned view might not be `IsFocusable`, but it's children can be
// traversed to evaluate if one of them `IsFocusable`.
//
// If this returns `nullptr` then it is the first focusable candidate view in
// the list including its siblings.
View* GetPreviousFocusableView();
// Removes |this| from its focus list, updating the previous and next
// views' points accordingly.
void RemoveFromFocusList();
// Insert |this| before or after |view| in the focus list.
void InsertBeforeInFocusList(View* view);
void InsertAfterInFocusList(View* view);
// Returns the list of children in the order of their focus. Each child might
// not be `IsFocusable`. Children that are not `IsFocusable` might still have
// children of its own that are `IsFocusable`.
Views GetChildrenFocusList();
// Gets/sets |FocusBehavior|. SetFocusBehavior() advances focus if necessary.
virtual FocusBehavior GetFocusBehavior() const;
void SetFocusBehavior(FocusBehavior focus_behavior);
// Set this to suppress default handling of focus for this View. By default
// native focus will be cleared and a11y events announced based on the new
// View focus.
// TODO(pbos): This is here to make removing focus behavior from the base
// implementation of OnFocus a no-op. Try to avoid new uses of this. Also
// investigate if this can be configured with more granularity (which event
// to fire on focus etc.).
void set_suppress_default_focus_handling() {
suppress_default_focus_handling_ = true;
}
// Returns true if this view is focusable, |enabled_| and drawn.
bool IsFocusable() const;
// Return whether this view is focusable when the user requires full keyboard
// access, even though it may not be normally focusable.
bool IsAccessibilityFocusable() const;
// Convenience method to retrieve the FocusManager associated with the
// Widget that contains this view. This can return NULL if this view is not
// part of a view hierarchy with a Widget.
FocusManager* GetFocusManager();
const FocusManager* GetFocusManager() const;
// Request keyboard focus. The receiving view will become the focused view.
virtual void RequestFocus();
// Invoked when a view is about to be requested for focus due to the focus
// traversal. Reverse is this request was generated going backward
// (Shift-Tab).
virtual void AboutToRequestFocusFromTabTraversal(bool reverse) {}
// Invoked when a key is pressed before the key event is processed (and
// potentially eaten) by the focus manager for tab traversal, accelerators and
// other focus related actions.
// The default implementation returns false, ensuring that tab traversal and
// accelerators processing is performed.
// Subclasses should return true if they want to process the key event and not
// have it processed as an accelerator (if any) or as a tab traversal (if the
// key event is for the TAB key). In that case, OnKeyPressed will
// subsequently be invoked for that event.
virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event);
// Subclasses that contain traversable children that are not directly
// accessible through the children hierarchy should return the associated
// FocusTraversable for the focus traversal to work properly.
virtual FocusTraversable* GetFocusTraversable();
// Subclasses that can act as a "pane" must implement their own
// FocusTraversable to keep the focus trapped within the pane.
// If this method returns an object, any view that's a direct or
// indirect child of this view will always use this FocusTraversable
// rather than the one from the widget.
virtual FocusTraversable* GetPaneFocusTraversable();
// Tooltips ------------------------------------------------------------------
// Gets the tooltip for this View. If the View does not have a tooltip,
// the returned value should be empty.
// Any time the tooltip text that a View is displaying changes, it must
// invoke TooltipTextChanged.
// |p| provides the coordinates of the mouse (relative to this view).
virtual std::u16string GetTooltipText(const gfx::Point& p) const;
// Context menus -------------------------------------------------------------
// Sets the ContextMenuController. Setting this to non-null makes the View
// process mouse events.
ContextMenuController* context_menu_controller() {
return context_menu_controller_;
}
void set_context_menu_controller(ContextMenuController* menu_controller) {
context_menu_controller_ = menu_controller;
}
// Provides default implementation for context menu handling. The default
// implementation calls the ShowContextMenu of the current
// ContextMenuController (if it is not NULL). Overridden in subclassed views
// to provide right-click menu display triggered by the keyboard (i.e. for the
// Chrome toolbar Back and Forward buttons). No source needs to be specified,
// as it is always equal to the current View.
// Note that this call is asynchronous for views menu and synchronous for
// mac's native menu.
virtual void ShowContextMenu(const gfx::Point& p,
ui::MenuSourceType source_type);
// Returns the location, in screen coordinates, to show the context menu at
// when the context menu is shown from the keyboard. This implementation
// returns the middle of the visible region of this view.
//
// This method is invoked when the context menu is shown by way of the
// keyboard.
virtual gfx::Point GetKeyboardContextMenuLocation();
// Drag and drop -------------------------------------------------------------
DragController* drag_controller() { return drag_controller_; }
void set_drag_controller(DragController* drag_controller) {
drag_controller_ = drag_controller;
}
// During a drag and drop session when the mouse moves the view under the
// mouse is queried for the drop types it supports by way of the
// GetDropFormats methods. If the view returns true and the drag site can
// provide data in one of the formats, the view is asked if the drop data
// is required before any other drop events are sent. Once the
// data is available the view is asked if it supports the drop (by way of
// the CanDrop method). If a view returns true from CanDrop,
// OnDragEntered is sent to the view when the mouse first enters the view,
// as the mouse moves around within the view OnDragUpdated is invoked.
// If the user releases the mouse over the view and OnDragUpdated returns a
// valid drop, then GetDropCallback is invoked. If the mouse moves outside the
// view or over another view that wants the drag, OnDragExited is invoked.
//
// Similar to mouse events, the deepest view under the mouse is first checked
// if it supports the drop (Drop). If the deepest view under
// the mouse does not support the drop, the ancestors are walked until one
// is found that supports the drop.
// Override and return the set of formats that can be dropped on this view.
// |formats| is a bitmask of the formats defined bye OSExchangeData::Format.
// The default implementation returns false, which means the view doesn't
// support dropping.
virtual bool GetDropFormats(int* formats,
std::set<ui::ClipboardFormatType>* format_types);
// Override and return true if the data must be available before any drop
// methods should be invoked. The default is false.
virtual bool AreDropTypesRequired();
// A view that supports drag and drop must override this and return true if
// data contains a type that may be dropped on this view.
virtual bool CanDrop(const OSExchangeData& data);
// OnDragEntered is invoked when the mouse enters this view during a drag and
// drop session and CanDrop returns true. This is immediately
// followed by an invocation of OnDragUpdated, and eventually one of
// OnDragExited or GetDropCallback.
virtual void OnDragEntered(const ui::DropTargetEvent& event);
// Invoked during a drag and drop session while the mouse is over the view.
// This should return a bitmask of the DragDropTypes::DragOperation supported
// based on the location of the event. Return 0 to indicate the drop should
// not be accepted.
virtual int OnDragUpdated(const ui::DropTargetEvent& event);
// Invoked during a drag and drop session when the mouse exits the views, or
// when the drag session was canceled and the mouse was over the view.
virtual void OnDragExited();
// Invoked from DoDrag after the drag completes. This implementation does
// nothing, and is intended for subclasses to do cleanup.
virtual void OnDragDone();
// Invoked during a drag and drop session when OnDragUpdated returns a valid
// operation and the user release the mouse but the drop is held because of
// DataTransferPolicyController. When calling, ensure that the |event|
// uses View local coordinates.
virtual DropCallback GetDropCallback(const ui::DropTargetEvent& event);
// Returns true if the mouse was dragged enough to start a drag operation.
// delta_x and y are the distance the mouse was dragged.
static bool ExceededDragThreshold(const gfx::Vector2d& delta);
// Accessibility -------------------------------------------------------------
// Get the object managing the accessibility interface for this View.
ViewAccessibility& GetViewAccessibility() const;
// Modifies |node_data| to reflect the current accessible state of this view.
// It accomplishes this by keeping the data up-to-date in response to the use
// of the accessible-property setters.
// NOTE: View authors should use the available property setters rather than
// overriding this function. Views which need to expose accessibility
// properties which are currently not supported View properties should ensure
// their view's `GetAccessibleNodeData` calls `GetAccessibleNodeData` on the
// parent class. This ensures that if an owning view customizes an accessible
// property, such as the name, role, or description, that customization is
// included in your view's `AXNodeData`.
virtual void GetAccessibleNodeData(ui::AXNodeData* node_data);
// Sets/gets the accessible name.
// The value of the accessible name is a localized, end-user-consumable string
// which may be derived from visible information (e.g. the text on a button)
// or invisible information (e.g. the alternative text describing an icon).
// In the case of focusable objects, the name will be presented by the screen
// reader when that object gains focus and is critical to understanding the
// purpose of that object non-visually.
void SetAccessibleName(const std::u16string& name);
const std::u16string& GetAccessibleName() const;
// Sets the accessible name to the specified string and source type.
// To indicate that this view should never have an accessible name, e.g. to
// prevent screen readers from speaking redundant information, set the type to
// `kAttributeExplicitlyEmpty`. NOTE: Do not use `kAttributeExplicitlyEmpty`
// on a view which may or may not have a name depending on circumstances. Also
// please seek review from accessibility OWNERs when removing the name,
// especially for views which are focusable or otherwise interactive.
void SetAccessibleName(std::u16string name, ax::mojom::NameFrom name_from);
// Sets the accessible name of this view to that of `naming_view`. Often
// `naming_view` is a `views::Label`, but any view with an accessible name
// will work.
void SetAccessibleName(View* naming_view);
// Sets/gets the accessible role.
void SetAccessibleRole(const ax::mojom::Role role);
ax::mojom::Role GetAccessibleRole() const;
// Sets the accessible role along with a customized string to be used by
// assistive technologies to present the role. When there is no role
// description provided, assisitive technologies will use either the default
// role descriptions we provide (which are currently located in a number of
// places. See crbug.com/1290866) or the value provided by their platform. As
// a general rule, it is preferable to not override the role string. Please
// seek review from accessibility OWNERs when using this function.
void SetAccessibleRole(const ax::mojom::Role role,
const std::u16string& role_description);
// Sets/gets the accessible description string.
void SetAccessibleDescription(const std::u16string& description);
const std::u16string& GetAccessibleDescription() const;
// Sets the accessible description to the specified string and source type.
// To remove the description and prevent alternatives (such as tooltip text)
// from being used, set the type to `kAttributeExplicitlyEmpty`
void SetAccessibleDescription(const std::u16string& description,
ax::mojom::DescriptionFrom description_from);
// Sets the accessible description of this view to the accessible name of
// `describing_view`. Often `describing_view` is a `views::Label`, but any
// view with an accessible name will work.
void SetAccessibleDescription(View* describing_view);
// Handle a request from assistive technology to perform an action on this
// view. Returns true on success, but note that the success/failure is
// not propagated to the client that requested the action, since the
// request is sometimes asynchronous. The right way to send a response is
// via NotifyAccessibilityEvent(), below.
virtual bool HandleAccessibleAction(const ui::AXActionData& action_data);
// Returns an instance of the native accessibility interface for this view.
virtual gfx::NativeViewAccessible GetNativeViewAccessible();
// Notifies assistive technology that an accessibility event has
// occurred on this view, such as when the view is focused or when its
// value changes. Pass true for |send_native_event| except for rare
// cases where the view is a native control that's already sending a
// native accessibility event and the duplicate event would cause
// problems.
void NotifyAccessibilityEvent(ax::mojom::Event event_type,
bool send_native_event);
// Views may override this function to know when an accessibility
// event is fired. This will be called by NotifyAccessibilityEvent.
virtual void OnAccessibilityEvent(ax::mojom::Event event_type);
// Scrolling -----------------------------------------------------------------
// TODO(beng): Figure out if this can live somewhere other than View, i.e.
// closer to ScrollView.
// Scrolls the specified region, in this View's coordinate system, to be
// visible. View's implementation passes the call onto the parent View (after
// adjusting the coordinates). It is up to views that only show a portion of
// the child view, such as Viewport, to override appropriately.
virtual void ScrollRectToVisible(const gfx::Rect& rect);
// Scrolls the view's bounds or some subset thereof to be visible. By default
// this function calls ScrollRectToVisible(GetLocalBounds()).
void ScrollViewToVisible();
void AddObserver(ViewObserver* observer);
void RemoveObserver(ViewObserver* observer);
bool HasObserver(const ViewObserver* observer) const;
// http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
// Callers should not depend on this as it is meant to be temporary.
enum class LifeCycleState : uint32_t {
kAlive = 0x600D600D,
kDestroying = 0x90141013,
kDestroyed = 0xBAADBAAD,
};
LifeCycleState life_cycle_state() const { return life_cycle_state_; }
protected:
// Used to track a drag. RootView passes this into
// ProcessMousePressed/Dragged.
struct DragInfo {
// Sets possible_drag to false and start_x/y to 0. This is invoked by
// RootView prior to invoke ProcessMousePressed.
void Reset();
// Sets possible_drag to true and start_pt to the specified point.
// This is invoked by the target view if it detects the press may generate
// a drag.
void PossibleDrag(const gfx::Point& p);
// Whether the press may generate a drag.
bool possible_drag = false;
// Coordinates of the mouse press.
gfx::Point start_pt;
};
// Accessibility -------------------------------------------------------------
// Convenience function to set common accessibility properties during view
// construction/initialization. It should only be used to define property
// values as part of the creation of this view; not to provide property-
// change updates. This function will only modify properties for which a value
// has been explicitly set.
void SetAccessibilityProperties(
absl::optional<ax::mojom::Role> role = absl::nullopt,
absl::optional<std::u16string> name = absl::nullopt,
absl::optional<std::u16string> description = absl::nullopt,
absl::optional<std::u16string> role_description = absl::nullopt,
absl::optional<ax::mojom::NameFrom> name_from = absl::nullopt,
absl::optional<ax::mojom::DescriptionFrom> description_from =
absl::nullopt);
// Called when the accessible name of the View changed.
virtual void OnAccessibleNameChanged(const std::u16string& new_name) {}
// Called by `SetAccessibleName` to allow subclasses to adjust the new name.
// Potential use cases include setting the accessible name to the tooltip
// text when the new name is empty and prepending/appending additional text
// to the new name.
virtual void AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) {}
// Size and disposition ------------------------------------------------------
// Calculates the natural size for the View, to be taken into consideration
// when the parent is performing layout.
// `preferred_size_` will take precedence over CalculatePreferredSize() if
// it exists.
virtual gfx::Size CalculatePreferredSize() const;
// Calculates the preferred size for the View given `available_size`.
// `preferred_size_` will take precedence over CalculatePreferredSize() if
// it exists.
virtual gfx::Size CalculatePreferredSize(
const SizeBounds& available_size) const;
// Override to be notified when the bounds of the view have changed.
virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) {}
// Called when the preferred size of a child view changed. This gives the
// parent an opportunity to do a fresh layout if that makes sense.
virtual void ChildPreferredSizeChanged(View* child) {}
// Called when the visibility of a child view changed. This gives the parent
// an opportunity to do a fresh layout if that makes sense.
virtual void ChildVisibilityChanged(View* child) {}
// Invalidates the layout and calls ChildPreferredSizeChanged() on the parent
// if there is one. Be sure to call PreferredSizeChanged() when overriding
// such that the layout is properly invalidated.
virtual void PreferredSizeChanged();
// Override returning true when the view needs to be notified when its visible
// bounds relative to the root view may have changed. Only used by
// NativeViewHost.
virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const;
// Notification that this View's visible bounds relative to the root view may
// have changed. The visible bounds are the region of the View not clipped by
// its ancestors. This is used for clipping NativeViewHost.
virtual void OnVisibleBoundsChanged();
// Tree operations -----------------------------------------------------------
// This method is invoked when the tree changes.
//
// When a view is removed, it is invoked for all children and grand
// children. For each of these views, a notification is sent to the
// view and all parents.
//
// When a view is added, a notification is sent to the view, all its
// parents, and all its children (and grand children)
//
// Default implementation does nothing. Override to perform operations
// required when a view is added or removed from a view hierarchy
//
// Refer to comments in struct |ViewHierarchyChangedDetails| for |details|.
//
// See also AddedToWidget() and RemovedFromWidget() for detecting when the
// view is added to/removed from a widget.
virtual void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
// When SetVisible() changes the visibility of a view, this method is
// invoked for that view as well as all the children recursively.
virtual void VisibilityChanged(View* starting_from, bool is_visible);
// This method is invoked when the parent NativeView of the widget that the
// view is attached to has changed and the view hierarchy has not changed.
// ViewHierarchyChanged() is called when the parent NativeView of the widget
// that the view is attached to is changed as a result of changing the view
// hierarchy. Overriding this method is useful for tracking which
// FocusManager manages this view.
virtual void NativeViewHierarchyChanged();
// This method is invoked for a view when it is attached to a hierarchy with
// a widget, i.e. GetWidget() starts returning a non-null result.
// It is also called when the view is moved to a different widget.
virtual void AddedToWidget();
// This method is invoked for a view when it is removed from a hierarchy with
// a widget or moved to a different widget.
virtual void RemovedFromWidget();
// Painting ------------------------------------------------------------------
// Override to control paint redirection or to provide a different Rectangle
// |r| to be repainted. This is a function with an empty implementation in
// view.cc and is purely intended for subclasses to override.
virtual void OnDidSchedulePaint(const gfx::Rect& r);
// Responsible for calling Paint() on child Views. Override to control the
// order child Views are painted.
virtual void PaintChildren(const PaintInfo& info);
// Override to provide rendering in any part of the View's bounds. Typically
// this is the "contents" of the view. If you override this method you will
// have to call the subsequent OnPaint*() methods manually.
virtual void OnPaint(gfx::Canvas* canvas);
// Override to paint a background before any content is drawn. Typically this
// is done if you are satisfied with a default OnPaint handler but wish to
// supply a different background.
virtual void OnPaintBackground(gfx::Canvas* canvas);
// Override to paint a border not specified by SetBorder().
virtual void OnPaintBorder(gfx::Canvas* canvas);
// Returns the type of scaling to be done for this View. Override this to
// change the default scaling type from |kScaleToFit|. You would want to
// override this for a view and return |kScaleToScaleFactor| in cases where
// scaling should cause no distortion. Such as in the case of an image or
// an icon.
virtual PaintInfo::ScaleType GetPaintScaleType() const;
// Accelerated painting ------------------------------------------------------
// Returns the offset from this view to the nearest ancestor with a layer. If
// |layer_parent| is non-NULL it is set to the nearest ancestor with a layer.
virtual LayerOffsetData CalculateOffsetToAncestorWithLayer(
ui::Layer** layer_parent);
// Updates the view's layer's parent. Called when a view is added to a view
// hierarchy, responsible for parenting the view's layer to the enclosing
// layer in the hierarchy.
virtual void UpdateParentLayer();
// If this view has a layer, the layer is reparented to |parent_layer| and its
// bounds is set based on |point|. If this view does not have a layer, then
// recurses through all children. This is used when adding a layer to an
// existing view to make sure all descendants that have layers are parented to
// the right layer.
void MoveLayerToParent(ui::Layer* parent_layer,
const LayerOffsetData& offset_data);
// Called to update the bounds of any child layers within this View's
// hierarchy when something happens to the hierarchy.
void UpdateChildLayerBounds(const LayerOffsetData& offset_data);
// Overridden from ui::LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override;
void OnLayerTransformed(const gfx::Transform& old_transform,
ui::PropertyChangeReason reason) final;
void OnLayerClipRectChanged(const gfx::Rect& old_rect,
ui::PropertyChangeReason reason) override;
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
// Finds the layer that this view paints to (it may belong to an ancestor
// view), then reorders the immediate children of that layer to match the
// order of the view tree.
void ReorderLayers();
// This reorders the immediate children of |*parent_layer| to match the
// order of the view tree. Child layers which are owned by a view are
// reordered so that they are below any child layers not owned by a view.
// Widget::ReorderNativeViews() should be called to reorder any child layers
// with an associated view. Widget::ReorderNativeViews() may reorder layers
// below layers owned by a view.
virtual void ReorderChildLayers(ui::Layer* parent_layer);
// Notifies parents about a layer being created or destroyed in a child. An
// example where a subclass may override this method is when it wants to clip
// the child by adding its own layer.
virtual void OnChildLayerChanged(View* child);
// Input ---------------------------------------------------------------------
virtual DragInfo* GetDragInfo();
// Focus ---------------------------------------------------------------------
// Override to be notified when focus has changed either to or from this View.
virtual void OnFocus();
virtual void OnBlur();
// Handle view focus/blur events for this view.
void Focus();
void Blur();
// System events -------------------------------------------------------------
// Called when either the UI theme or the NativeTheme associated with this
// View changes. This is also called when the NativeTheme first becomes
// available (after the view is added to a widget hierarchy). Overriding
// allows individual Views to do special cleanup and processing (such as
// dropping resource caches). To dispatch a theme changed notification, call
// Widget::ThemeChanged().
virtual void OnThemeChanged();
// Tooltips ------------------------------------------------------------------
// Views must invoke this when the tooltip text they are to display changes.
void TooltipTextChanged();
// Drag and drop -------------------------------------------------------------
// These are cover methods that invoke the method of the same name on
// the DragController. Subclasses may wish to override rather than install
// a DragController.
// See DragController for a description of these methods.
virtual int GetDragOperations(const gfx::Point& press_pt);
virtual void WriteDragData(const gfx::Point& press_pt, OSExchangeData* data);
// Returns whether we're in the middle of a drag session that was initiated
// by us.
bool InDrag() const;
// Returns how much the mouse needs to move in one direction to start a
// drag. These methods cache in a platform-appropriate way. These values are
// used by the public static method ExceededDragThreshold().
static int GetHorizontalDragThreshold();
static int GetVerticalDragThreshold();
// PropertyHandler -----------------------------------------------------------
// Note: you MUST call this base method from derived classes that override it
// or else your class will not properly register for ElementTrackerViews and
// won't be available for interactive tests or in-product help/tutorials which
// use that system.
void AfterPropertyChange(const void* key, int64_t old_value) override;
// Property Support ----------------------------------------------------------
void OnPropertyChanged(ui::metadata::PropertyKey property,
PropertyEffects property_effects);
private:
friend class internal::PreEventDispatchHandler;
friend class internal::PostEventDispatchHandler;
friend class internal::RootView;
friend class internal::ScopedChildrenLock;
friend class FocusManager;
friend class ViewDebugWrapperImpl;
friend class ViewLayerTest;
friend class ViewLayerPixelCanvasTest;
friend class ViewTestApi;
friend class Widget;
FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCache);
FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCacheInRTL);
FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithUnknownInvalidation);
FRIEND_TEST_ALL_PREFIXES(ViewTest, PauseAccessibilityEvents);
// This is the default view layout. It is a very simple version of FillLayout,
// which merely sets the bounds of the children to the content bounds. The
// actual FillLayout isn't used here because it supports a couple of features
// not used in the vast majority of instances. It also descends from
// LayoutManagerBase which adds some extra overhead not needed here.
class DefaultFillLayout : public LayoutManager {
public:
DefaultFillLayout();
~DefaultFillLayout() override;
void Layout(View* host) override;
gfx::Size GetPreferredSize(const View* host) const override;
int GetPreferredHeightForWidth(const View* host, int width) const override;
};
// Painting -----------------------------------------------------------------
// Responsible for propagating SchedulePaint() to the view's layer. If there
// is no associated layer, the requested paint rect is propagated up the
// view hierarchy by calling this function on the parent view. Rectangle |r|
// is in the view's coordinate system. The transformations are applied to it
// to convert it into the parent coordinate system before propagating
// SchedulePaint() up the view hierarchy. This function should NOT be directly
// called. Instead call SchedulePaint() or SchedulePaintInRect(), which will
// call into this as necessary.
void SchedulePaintInRectImpl(const gfx::Rect& r);
// Invoked before and after the bounds change to schedule painting the old and
// new bounds.
void SchedulePaintBoundsChanged(bool size_changed);
// Schedules a paint on the parent View if it exists.
void SchedulePaintOnParent();
// Returns whether this view is eligible for painting, i.e. is visible and
// nonempty. Note that this does not behave like IsDrawn(), since it doesn't
// check ancestors recursively; rather, it's used to prune subtrees of views
// during painting.
bool ShouldPaint() const;
// Adjusts the transform of |recorder| in advance of painting.
void SetUpTransformRecorderForPainting(
const gfx::Vector2d& offset_from_parent,
ui::TransformRecorder* recorder) const;
// Recursively calls the painting method |func| on all non-layered children,
// in Z order.
void RecursivePaintHelper(void (View::*func)(const PaintInfo&),
const PaintInfo& info);
// Invokes Paint() and, if necessary, PaintDebugRects(). Should be called
// only on the root of a widget/layer. PaintDebugRects() is invoked as a
// separate pass, instead of being rolled into Paint(), so that siblings will
// not obscure debug rects.
void PaintFromPaintRoot(const ui::PaintContext& parent_context);
// Draws a semitransparent rect to indicate the bounds of this view.
// Recursively does the same for all children. Invoked only with
// --draw-view-bounds-rects.
void PaintDebugRects(const PaintInfo& paint_info);
// Tree operations -----------------------------------------------------------
// Adds |view| as a child of this view at |index|.
void AddChildViewAtImpl(View* view, size_t index);
// Removes |view| from the hierarchy tree. If |update_tool_tip| is
// true, the tooltip is updated. If |delete_removed_view| is true, the
// view is also deleted (if it is parent owned). If |new_parent| is
// not null, the remove is the result of AddChildView() to a new
// parent. For this case, |new_parent| is the View that |view| is
// going to be added to after the remove completes.
void DoRemoveChildView(View* view,
bool update_tool_tip,
bool delete_removed_view,
View* new_parent);
// Call ViewHierarchyChanged() for all child views and all parents.
// |old_parent| is the original parent of the View that was removed.
// If |new_parent| is not null, the View that was removed will be reparented
// to |new_parent| after the remove operation.
// If is_removed_from_widget is true, calls RemovedFromWidget for all
// children.
void PropagateRemoveNotifications(View* old_parent,
View* new_parent,
bool is_removed_from_widget);
// Call ViewHierarchyChanged() for all children.
// If is_added_to_widget is true, calls AddedToWidget for all children.
void PropagateAddNotifications(const ViewHierarchyChangedDetails& details,
bool is_added_to_widget);
// Propagates NativeViewHierarchyChanged() notification through all the
// children.
void PropagateNativeViewHierarchyChanged();
// Calls ViewHierarchyChanged() and notifies observers.
void ViewHierarchyChangedImpl(const ViewHierarchyChangedDetails& details);
// Size and disposition ------------------------------------------------------
// Call VisibilityChanged() recursively for all children.
void PropagateVisibilityNotifications(View* from, bool is_visible);
// Registers/unregisters accelerators as necessary and calls
// VisibilityChanged().
void VisibilityChangedImpl(View* starting_from, bool is_visible);
// Visible bounds notification registration.
// When a view is added to a hierarchy, it and all its children are asked if
// they need to be registered for "visible bounds within root" notifications
// (see comment on OnVisibleBoundsChanged()). If they do, they are registered
// with every ancestor between them and the root of the hierarchy.
static void RegisterChildrenForVisibleBoundsNotification(View* view);
static void UnregisterChildrenForVisibleBoundsNotification(View* view);
void RegisterForVisibleBoundsNotification();
void UnregisterForVisibleBoundsNotification();
// Adds/removes view to the list of descendants that are notified any time
// this views location and possibly size are changed.
void AddDescendantToNotify(View* view);
void RemoveDescendantToNotify(View* view);
// Non-templatized backend for SetLayoutManager().
void SetLayoutManagerImpl(std::unique_ptr<LayoutManager> layout);
// Transformations -----------------------------------------------------------
// Returns in |transform| the transform to get from coordinates of |ancestor|
// to this. Returns true if |ancestor| is found. If |ancestor| is not found,
// or NULL, |transform| is set to convert from root view coordinates to this.
bool GetTransformRelativeTo(const View* ancestor,
gfx::Transform* transform) const;
// Coordinate conversion -----------------------------------------------------
// Converts a point in the view's coordinate to an ancestor view's coordinate
// system using necessary transformations. Returns whether the point was
// successfully converted to the ancestor's coordinate system.
bool ConvertPointForAncestor(const View* ancestor, gfx::Point* point) const;
// Converts a point in the ancestor's coordinate system to the view's
// coordinate system using necessary transformations. Returns whether the
// point was successfully converted from the ancestor's coordinate system
// to the view's coordinate system.
bool ConvertPointFromAncestor(const View* ancestor, gfx::Point* point) const;
// Converts a rect in the view's coordinate to an ancestor view's coordinate
// system using necessary transformations. Returns whether the rect was
// successfully converted to the ancestor's coordinate system.
bool ConvertRectForAncestor(const View* ancestor, gfx::RectF* rect) const;
// Converts a rect in the ancestor's coordinate system to the view's
// coordinate system using necessary transformations. Returns whether the
// rect was successfully converted from the ancestor's coordinate system
// to the view's coordinate system.
bool ConvertRectFromAncestor(const View* ancestor, gfx::RectF* rect) const;
// Accelerated painting ------------------------------------------------------
// Creates the layer and related fields for this view.
void CreateLayer(ui::LayerType layer_type);
// Recursively calls UpdateParentLayers() on all descendants, stopping at any
// Views that have layers. Calls UpdateParentLayer() for any Views that have
// a layer with no parent. If at least one descendant had an unparented layer
// true is returned.
bool UpdateParentLayers();
// Parents this view's layer to |parent_layer|, and sets its bounds and other
// properties in accordance to the layer hierarchy.
void ReparentLayer(ui::Layer* parent_layer);
// Called to update the layer visibility. The layer will be visible if the
// View itself, and all its parent Views are visible. This also updates
// visibility of the child layers.
void UpdateLayerVisibility();
void UpdateChildLayerVisibility(bool visible);
enum class LayerChangeNotifyBehavior {
// Notify the parent chain about the layer change.
NOTIFY,
// Don't notify the parent chain about the layer change.
DONT_NOTIFY
};
// Destroys the layer associated with this view, and reparents any descendants
// to the destroyed layer's parent. If the view does not currently have a
// layer, this has no effect.
// The |notify_parents| enum controls whether a notification about the layer
// change is sent to the parents.
void DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents);
// Determines whether we need to be painting to a layer, checks whether we
// currently have a layer, and creates or destroys the layer if necessary.
void CreateOrDestroyLayer();
// Notifies parents about layering changes in the view. This includes layer
// creation and destruction.
void NotifyParentsOfLayerChange();
// Orphans the layers in this subtree that are parented to layers outside of
// this subtree.
void OrphanLayers();
// Adjust the layer's offset so that it snaps to the physical pixel boundary.
// This has no effect if the view does not have an associated layer.
void SnapLayerToPixelBoundary(const LayerOffsetData& offset_data);
// Sets the layer's bounds given in DIP coordinates.
void SetLayerBounds(const gfx::Size& size_in_dip,
const LayerOffsetData& layer_offset_data);
// Creates a mask layer for the current view using |clip_path_|.
void CreateMaskLayer();
// Implementation for adding a layer above or beneath the view layer. Called
// from |AddLayerToRegion()|.
void AddLayerToRegionImpl(ui::Layer* new_layer,
std::vector<ui::Layer*>& layer_vector);
// Sets this view's layer and the layers above and below's parent to the given
// parent_layer. This will also ensure the layers are added to the given
// parent in the correct order.
void SetLayerParent(ui::Layer* parent_layer);
// Layout --------------------------------------------------------------------
// Returns whether a layout is deferred to a layout manager, either the
// default fill layout or the assigned layout manager.
bool HasLayoutManager() const;
// Input ---------------------------------------------------------------------
bool ProcessMousePressed(const ui::MouseEvent& event);
void ProcessMouseDragged(ui::MouseEvent* event);
void ProcessMouseReleased(const ui::MouseEvent& event);
// Accelerators --------------------------------------------------------------
// Registers this view's keyboard accelerators that are not registered to
// FocusManager yet, if possible.
void RegisterPendingAccelerators();
// Unregisters all the keyboard accelerators associated with this view.
// |leave_data_intact| if true does not remove data from accelerators_ array,
// so it could be re-registered with other focus manager
void UnregisterAccelerators(bool leave_data_intact);
// Focus ---------------------------------------------------------------------
// Sets previous/next focusable views for both |view| and other children
// assuming we've just inserted |view| at |pos|.
void SetFocusSiblings(View* view, Views::const_iterator pos);
// Helper function to advance focus, in case the currently focused view has
// become unfocusable.
void AdvanceFocusIfNecessary();
// System events -------------------------------------------------------------
// Used to propagate UI theme changed or NativeTheme changed notifications
// from the root view to all views in the hierarchy.
void PropagateThemeChanged();
// Used to propagate device scale factor changed notifications from the root
// view to all views in the hierarchy.
void PropagateDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor);
// Tooltips ------------------------------------------------------------------
// Propagates UpdateTooltip() to the TooltipManager for the Widget.
// This must be invoked any time the View hierarchy changes in such a way
// the view under the mouse differs. For example, if the bounds of a View is
// changed, this is invoked. Similarly, as Views are added/removed, this
// is invoked.
void UpdateTooltip();
// Drag and drop -------------------------------------------------------------
// Starts a drag and drop operation originating from this view. This invokes
// WriteDragData to write the data and GetDragOperations to determine the
// supported drag operations. When done, OnDragDone is invoked. |press_pt| is
// in the view's coordinate system.
// Returns true if a drag was started.
bool DoDrag(const ui::LocatedEvent& event,
const gfx::Point& press_pt,
ui::mojom::DragEventSource source);
// Property support ----------------------------------------------------------
// Called from OnPropertyChanged with the given set of property effects. This
// function is NOT called if effects == kPropertyEffectsNone.
void HandlePropertyChangeEffects(PropertyEffects effects);
// The following methods are used by the property access system described in
// the comments above. They follow the required naming convention in order to
// allow them to be visible via the metadata.
int GetX() const;
int GetY() const;
int GetWidth() const;
int GetHeight() const;
void SetWidth(int width);
void SetHeight(int height);
bool GetIsDrawn() const;
// Special property accessor used by metadata to get the ToolTip text.
std::u16string GetTooltip() const;
//////////////////////////////////////////////////////////////////////////////
// Creation and lifetime -----------------------------------------------------
// False if this View is owned by its parent - i.e. it will be deleted by its
// parent during its parents destruction. False is the default.
bool owned_by_client_ = false;
// Attributes ----------------------------------------------------------------
// The id of this View. Used to find this View.
int id_ = 0;
// The group of this view. Some view subclasses use this id to find other
// views of the same group. For example radio button uses this information
// to find other radio buttons.
int group_ = -1;
// Tree operations -----------------------------------------------------------
// This view's parent.
raw_ptr<View, DanglingUntriaged> parent_ = nullptr;
// This view's children.
Views children_;
#if DCHECK_IS_ON()
// True while iterating over |children_|. Used to detect and DCHECK when
// |children_| is mutated during iteration.
mutable bool iterating_ = false;
#endif
bool can_process_events_within_subtree_ = true;
// Size and disposition ------------------------------------------------------
absl::optional<gfx::Size> preferred_size_;
// This View's bounds in the parent coordinate system.
gfx::Rect bounds_;
// Whether this view is visible.
bool visible_ = true;
// Whether this view is enabled.
bool enabled_ = true;
// When this flag is on, a View receives a mouse-enter and mouse-leave event
// even if a descendant View is the event-recipient for the real mouse
// events. When this flag is turned on, and mouse moves from outside of the
// view into a child view, both the child view and this view receives
// mouse-enter event. Similarly, if the mouse moves from inside a child view
// and out of this view, then both views receive a mouse-leave event.
// When this flag is turned off, if the mouse moves from inside this view into
// a child view, then this view receives a mouse-leave event. When this flag
// is turned on, it does not receive the mouse-leave event in this case.
// When the mouse moves from inside the child view out of the child view but
// still into this view, this view receives a mouse-enter event if this flag
// is turned off, but doesn't if this flag is turned on.
// This flag is initialized to false.
bool notify_enter_exit_on_child_ = false;
// Whether or not RegisterViewForVisibleBoundsNotification on the RootView
// has been invoked.
bool registered_for_visible_bounds_notification_ = false;
// List of descendants wanting notification when their visible bounds change.
std::unique_ptr<Views> descendants_to_notify_;
// Transformations -----------------------------------------------------------
// Painting will be clipped to this path.
SkPath clip_path_;
// Layout --------------------------------------------------------------------
// Whether the view needs to be laid out.
bool needs_layout_ = true;
// The View's LayoutManager defines the sizing heuristics applied to child
// Views. The default is absolute positioning according to bounds_.
std::unique_ptr<LayoutManager> layout_manager_;
// The default "fill" layout manager. This is set only if |layout_manager_|
// isn't set and SetUseDefaultFillLayout(true) is called or
// |kUseDefaultFillLayout| is true.
absl::optional<DefaultFillLayout> default_fill_layout_;
// Whether this View's layer should be snapped to the pixel boundary.
bool snap_layer_to_pixel_boundary_ = false;
// Painting ------------------------------------------------------------------
// Border.
std::unique_ptr<Border> border_;
// Background may rely on Border, so it must be declared last and destroyed
// first.
std::unique_ptr<Background> background_;
// Cached output of painting to be reused in future frames until invalidated.
ui::PaintCache paint_cache_;
// Whether SchedulePaintInRect() was invoked on this View.
bool needs_paint_ = false;
// Native theme --------------------------------------------------------------
// A native theme for this view and its descendants. Typically null, in which
// case the native theme is drawn from the parent view (eventually the
// widget).
raw_ptr<ui::NativeTheme, DanglingUntriaged> native_theme_ = nullptr;
// RTL painting --------------------------------------------------------------
// Indicates whether or not the gfx::Canvas object passed to Paint() is going
// to be flipped horizontally (using the appropriate transform) on
// right-to-left locales for this View.
bool flip_canvas_on_paint_for_rtl_ui_ = false;
// Controls whether GetTransform(), the mirroring functions, and the like
// horizontally mirror. This controls how child views are physically
// positioned onscreen. The default behavior should be correct in most cases,
// but can be overridden if a particular view must always be laid out in some
// direction regardless of the application's default UI direction.
absl::optional<bool> is_mirrored_;
// Accelerated painting ------------------------------------------------------
// Whether layer painting was explicitly set by a call to |SetPaintToLayer()|.
bool paint_to_layer_explicitly_set_ = false;
// Whether we are painting to a layer because of a non-identity transform.
bool paint_to_layer_for_transform_ = false;
// Set of layers that should be painted above and beneath this View's layer.
// These layers are maintained as siblings of this View's layer and are
// stacked above and beneath, respectively.
std::vector<ui::Layer*> layers_above_;
std::vector<ui::Layer*> layers_below_;
// If painting to a layer |mask_layer_| will mask the current layer and all
// child layers to within the |clip_path_|.
std::unique_ptr<views::ViewMaskLayer> mask_layer_;
// Accelerators --------------------------------------------------------------
// Focus manager accelerators registered on.
raw_ptr<FocusManager, DanglingUntriaged> accelerator_focus_manager_ = nullptr;
// The list of accelerators. List elements in the range
// [0, registered_accelerator_count_) are already registered to FocusManager,
// and the rest are not yet.
std::unique_ptr<std::vector<ui::Accelerator>> accelerators_;
size_t registered_accelerator_count_ = 0;
// Focus ---------------------------------------------------------------------
// Next view to be focused when the Tab key is pressed.
raw_ptr<View, DanglingUntriaged> next_focusable_view_ = nullptr;
// Next view to be focused when the Shift-Tab key combination is pressed.
raw_ptr<View, DanglingUntriaged> previous_focusable_view_ = nullptr;
// The focus behavior of the view in regular and accessibility mode.
FocusBehavior focus_behavior_ = FocusBehavior::NEVER;
// This is set when focus events should be skipped after focus reaches this
// View.
bool suppress_default_focus_handling_ = false;
// Context menus -------------------------------------------------------------
// The menu controller.
raw_ptr<ContextMenuController, DanglingUntriaged> context_menu_controller_ =
nullptr;
// Drag and drop -------------------------------------------------------------
raw_ptr<DragController, DanglingUntriaged> drag_controller_ = nullptr;
// Input --------------------------------------------------------------------
std::unique_ptr<ViewTargeter> targeter_;
// System events -------------------------------------------------------------
#if DCHECK_IS_ON()
bool on_theme_changed_called_ = false;
#endif
// Accessibility -------------------------------------------------------------
// Manages the accessibility interface for this View.
mutable std::unique_ptr<ViewAccessibility> view_accessibility_;
// Updated by the accessibility property setters and returned by
// `GetAccessibleNodeData`.
std::unique_ptr<ui::AXNodeData> ax_node_data_;
// Used by `SetAccessibilityProperties` and to prevent accessibility
// property-change events from being fired during initialization of this view.
bool pause_accessibility_events_ = false;
// Keeps track of whether accessibility checks for this View have run yet.
// They run once inside ::OnPaint() to keep overhead low. The idea is that if
// a View is ready to paint it should also be set up to be accessible.
bool has_run_accessibility_paint_checks_ = false;
// Accessible properties whose values are set by views using the accessible
// property setters, and used to populate the `AXNodeData` associated with
// this view and provided by `View::GetAccessibleNodeData`.
std::u16string accessible_name_;
std::u16string accessible_description_;
ax::mojom::Role accessible_role_ = ax::mojom::Role::kUnknown;
// Observers -----------------------------------------------------------------
base::ObserverList<ViewObserver>::Unchecked observers_;
// http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
LifeCycleState life_cycle_state_ = LifeCycleState::kAlive;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, View, BaseView)
template <typename LayoutManager>
BuilderT& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) & {
auto setter = std::make_unique<::views::internal::PropertySetter<
ViewClass_, std::unique_ptr<LayoutManager>,
decltype((static_cast<LayoutManager* (
ViewClass_::*)(std::unique_ptr<LayoutManager>)>(
&ViewClass_::SetLayoutManager))),
&ViewClass_::SetLayoutManager>>(std::move(layout_manager));
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
return *static_cast<BuilderT*>(this);
}
template <typename LayoutManager>
BuilderT&& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) && {
return std::move(this->SetLayoutManager(std::move(layout_manager)));
}
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleName, const std::u16string&)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleName, View*)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleName,
std::u16string,
ax::mojom::NameFrom)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleDescription, const std::u16string&)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleDescription, View*)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleDescription,
const std::u16string&,
ax::mojom::DescriptionFrom)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleRole, ax::mojom::Role)
VIEW_BUILDER_OVERLOAD_METHOD(SetAccessibleRole,
ax::mojom::Role,
const std::u16string&)
VIEW_BUILDER_PROPERTY(std::unique_ptr<Background>, Background)
VIEW_BUILDER_PROPERTY(std::unique_ptr<Border>, Border)
VIEW_BUILDER_PROPERTY(gfx::Rect, BoundsRect)
VIEW_BUILDER_PROPERTY(gfx::Size, Size)
VIEW_BUILDER_PROPERTY(gfx::Point, Position)
VIEW_BUILDER_PROPERTY(int, X)
VIEW_BUILDER_PROPERTY(int, Y)
VIEW_BUILDER_PROPERTY(gfx::Size, PreferredSize)
VIEW_BUILDER_PROPERTY(SkPath, ClipPath)
VIEW_BUILDER_PROPERTY_DEFAULT(ui::LayerType, PaintToLayer, ui::LAYER_TEXTURED)
VIEW_BUILDER_PROPERTY(bool, Enabled)
VIEW_BUILDER_PROPERTY(bool, FlipCanvasOnPaintForRTLUI)
VIEW_BUILDER_PROPERTY(views::View::FocusBehavior, FocusBehavior)
VIEW_BUILDER_PROPERTY(int, Group)
VIEW_BUILDER_PROPERTY(int, ID)
VIEW_BUILDER_PROPERTY(bool, Mirrored)
VIEW_BUILDER_PROPERTY(bool, NotifyEnterExitOnChild)
VIEW_BUILDER_PROPERTY(gfx::Transform, Transform)
VIEW_BUILDER_PROPERTY(bool, Visible)
VIEW_BUILDER_PROPERTY(bool, CanProcessEventsWithinSubtree)
VIEW_BUILDER_PROPERTY(bool, UseDefaultFillLayout)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, View)
#endif // UI_VIEWS_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view.h | C++ | unknown | 108,547 |
// 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/view_class_properties.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/layout/flex_layout_types.h"
#if !defined(USE_AURA)
// aura_constants.cc also defines these types.
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, bool)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, int)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, gfx::Size*)
#endif
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, gfx::Insets*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::DialogDelegate*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT,
views::HighlightPathGenerator*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::FlexSpecification*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::LayoutAlignment*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, ui::ElementIdentifier)
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(int, kHitTestComponentKey, HTNOWHERE)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(gfx::Insets, kMarginsKey, nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(gfx::Insets, kInternalPaddingKey, nullptr)
DEFINE_UI_CLASS_PROPERTY_KEY(views::DialogDelegate*,
kAnchoredDialogKey,
nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(views::HighlightPathGenerator,
kHighlightPathGeneratorKey,
nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(FlexSpecification, kFlexBehaviorKey, nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(LayoutAlignment,
kCrossAxisAlignmentKey,
nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(gfx::Size, kTableColAndRowSpanKey, nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(LayoutAlignment,
kTableHorizAlignKey,
nullptr)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(LayoutAlignment, kTableVertAlignKey, nullptr)
DEFINE_UI_CLASS_PROPERTY_KEY(bool, kViewIgnoredByLayoutKey, false)
DEFINE_UI_CLASS_PROPERTY_KEY(ui::ElementIdentifier,
kElementIdentifierKey,
ui::ElementIdentifier())
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_class_properties.cc | C++ | unknown | 2,524 |
// 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_VIEW_CLASS_PROPERTIES_H_
#define UI_VIEWS_VIEW_CLASS_PROPERTIES_H_
#include "ui/base/class_property.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/layout/flex_layout_types.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/views_export.h"
namespace gfx {
class Insets;
} // namespace gfx
namespace views {
class DialogDelegate;
class FlexSpecification;
class HighlightPathGenerator;
// The hit test component (e.g. HTCLIENT) for a View in a window frame. Defaults
// to HTNOWHERE.
VIEWS_EXPORT extern const ui::ClassProperty<int>* const kHitTestComponentKey;
// A property to store margins around the outer perimeter of the view. Margins
// are outside the bounds of the view. This is used by various layout managers
// to position views with the proper spacing between them.
//
// Used by multiple layout managers.
VIEWS_EXPORT extern const ui::ClassProperty<gfx::Insets*>* const kMarginsKey;
// A property to store the internal padding contained in a view. When doing
// layout, this padding is counted against the required margin around the view,
// effectively reducing the size of the margin (to a minimum of zero). Examples
// include expansion of buttons in touch mode and empty areas that serve as
// resize handles.
//
// Used by FlexLayout.
VIEWS_EXPORT extern const ui::ClassProperty<gfx::Insets*>* const
kInternalPaddingKey;
// A property to store the bubble dialog anchored to this view, to
// enable the bubble's contents to be included in the focus order.
VIEWS_EXPORT extern const ui::ClassProperty<DialogDelegate*>* const
kAnchoredDialogKey;
// A property to store a highlight-path generator. This generator is used to
// generate a highlight path for focus rings or ink-drop effects.
VIEWS_EXPORT extern const ui::ClassProperty<HighlightPathGenerator*>* const
kHighlightPathGeneratorKey;
// A property to store how a view should flex when placed in a layout.
// Currently only fully supported by FlexLayout. BoxLayout supports weight.
VIEWS_EXPORT extern const ui::ClassProperty<FlexSpecification*>* const
kFlexBehaviorKey;
VIEWS_EXPORT extern const ui::ClassProperty<LayoutAlignment*>* const
kCrossAxisAlignmentKey;
// TableLayout-specific properties:
// Note that col/row span counts padding columns, so if you want to span a
// region consisting of <column><padding column><column>, it's a column span of
// 3, not 2.
VIEWS_EXPORT extern const ui::ClassProperty<gfx::Size*>* const
kTableColAndRowSpanKey;
VIEWS_EXPORT extern const ui::ClassProperty<LayoutAlignment*>* const
kTableHorizAlignKey;
VIEWS_EXPORT extern const ui::ClassProperty<LayoutAlignment*>* const
kTableVertAlignKey;
// Property indicating whether a view should be ignored by a layout. Supported
// by View::DefaultFillLayout and BoxLayout.
// TODO(kylixrd): Use for other layouts.
VIEWS_EXPORT extern const ui::ClassProperty<bool>* const
kViewIgnoredByLayoutKey;
// Tag for the view associated with ui::ElementTracker.
VIEWS_EXPORT extern const ui::ClassProperty<ui::ElementIdentifier>* const
kElementIdentifierKey;
} // namespace views
// Declaring the template specialization here to make sure that the
// compiler in all builds, including jumbo builds, always knows about
// the specialization before the first template instance use. Using a
// template instance before its specialization is declared in a
// translation unit is a C++ error.
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, gfx::Insets*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::DialogDelegate*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT,
views::HighlightPathGenerator*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::FlexSpecification*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::LayoutAlignment*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, gfx::Size*)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, ui::ElementIdentifier)
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, bool)
#endif // UI_VIEWS_VIEW_CLASS_PROPERTIES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_class_properties.h | C++ | unknown | 4,308 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view_constants.h"
namespace views {
constexpr int kAutoscrollSize = 10;
constexpr int kAutoscrollRowTimerMS = 200;
constexpr int kDropBetweenPixels = 5;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_constants.cc | C++ | unknown | 341 |
// 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_VIEW_CONSTANTS_H_
#define UI_VIEWS_VIEW_CONSTANTS_H_
#include "ui/views/views_export.h"
namespace views {
// Size (width or height) within which the user can hold the mouse and the
// view should scroll.
VIEWS_EXPORT extern const int kAutoscrollSize;
// Time in milliseconds to autoscroll by a row. This is used during drag and
// drop.
VIEWS_EXPORT extern const int kAutoscrollRowTimerMS;
// Used to determine whether a drop is on an item or before/after it. If a drop
// occurs kDropBetweenPixels from the top/bottom it is considered before/after
// the item, otherwise it is on the item.
VIEWS_EXPORT extern const int kDropBetweenPixels;
} // namespace views
#endif // UI_VIEWS_VIEW_CONSTANTS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_constants.h | C++ | unknown | 869 |
// 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/view_constants_aura.h"
#include "ui/base/class_property.h"
#include "ui/views/view.h"
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::View*)
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(views::View*, kHostViewKey, NULL)
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_constants_aura.cc | C++ | unknown | 424 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_VIEW_CONSTANTS_AURA_H_
#define UI_VIEWS_VIEW_CONSTANTS_AURA_H_
#include "ui/aura/window.h"
#include "ui/views/views_export.h"
namespace views {
class View;
// A property key to indicate the view the window is associated with. If
// specified, the z-order of the view, relative to other views, dictates the
// z-order of the window and its associated layer. The associated view must
// have the same parent widget as the window on which the property is set.
VIEWS_EXPORT extern const aura::WindowProperty<View*>* const kHostViewKey;
} // namespace views
// Declaring the template specialization here to make sure that the
// compiler in all builds, including jumbo builds, always knows about
// the specialization before the first template instance use. Using a
// template instance before its specialization is declared in a
// translation unit is a C++ error.
DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, views::View*)
#endif // UI_VIEWS_VIEW_CONSTANTS_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_constants_aura.h | C++ | unknown | 1,140 |
// 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/view_model.h"
#include <stddef.h>
#include "base/check_op.h"
#include "base/ranges/algorithm.h"
#include "ui/views/view.h"
namespace views {
// views in `entries_` are owned by their parents, no need to delete them.
ViewModelBase::~ViewModelBase() = default;
void ViewModelBase::Remove(size_t index) {
check_index(index);
entries_.erase(entries_.begin() + static_cast<ptrdiff_t>(index));
}
void ViewModelBase::Move(size_t index, size_t target_index) {
check_index(index);
check_index(target_index);
if (index == target_index)
return;
Entry entry(entries_[index]);
entries_.erase(entries_.begin() + static_cast<ptrdiff_t>(index));
entries_.insert(entries_.begin() + static_cast<ptrdiff_t>(target_index),
entry);
}
void ViewModelBase::MoveViewOnly(size_t index, size_t target_index) {
if (target_index < index) {
View* view = entries_[index].view;
for (size_t i = index; i > target_index; --i)
entries_[i].view = entries_[i - 1].view;
entries_[target_index].view = view;
} else if (target_index > index) {
View* view = entries_[index].view;
for (size_t i = index; i < target_index; ++i)
entries_[i].view = entries_[i + 1].view;
entries_[target_index].view = view;
}
}
void ViewModelBase::Clear() {
Entries entries;
entries.swap(entries_);
for (const auto& entry : entries)
delete entry.view;
}
absl::optional<size_t> ViewModelBase::GetIndexOfView(const View* view) const {
const auto i = base::ranges::find(entries_, view, &Entry::view);
return (i == entries_.cend())
? absl::nullopt
: absl::make_optional(static_cast<size_t>(i - entries_.cbegin()));
}
ViewModelBase::ViewModelBase() = default;
void ViewModelBase::AddUnsafe(View* view, size_t index) {
DCHECK_LE(index, entries_.size());
Entry entry;
entry.view = view;
entries_.insert(entries_.begin() + static_cast<ptrdiff_t>(index), entry);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model.cc | C++ | unknown | 2,120 |
// 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_VIEW_MODEL_H_
#define UI_VIEWS_VIEW_MODEL_H_
#include <vector>
#include "base/check_op.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/views_export.h"
namespace views {
class View;
class ViewModelUtils;
// Internal implementation of the templated ViewModelT class. Provides
// non-templated "unsafe" methods for ViewModelT to wrap around. Any methods
// that allow insertion of or access to a View* should be protected, and have a
// public method in the ViewModelT subclass that provides type-safe access to
// the correct View subclass.
class VIEWS_EXPORT ViewModelBase {
public:
struct Entry {
Entry() = default;
// This field is not a raw_ptr<> because it was filtered by the rewriter
// for: #constexpr-ctor-field-initializer
RAW_PTR_EXCLUSION View* view = nullptr;
gfx::Rect ideal_bounds;
};
using Entries = std::vector<Entry>;
ViewModelBase(const ViewModelBase&) = delete;
ViewModelBase& operator=(const ViewModelBase&) = delete;
~ViewModelBase();
const Entries& entries() const { return entries_; }
// Removes the view at the specified index. This does not actually remove the
// view from the view hierarchy.
void Remove(size_t index);
// Moves the view at |index| to |target_index|. |target_index| is in terms
// of the model *after* the view at |index| is removed.
void Move(size_t index, size_t target_index);
// Variant of Move() that leaves the bounds as is. That is, after invoking
// this the bounds of the view at |target_index| (and all other indices) are
// exactly the same as the bounds of the view at |target_index| before
// invoking this.
void MoveViewOnly(size_t index, size_t target_index);
// Returns the number of views.
size_t view_size() const { return entries_.size(); }
// Removes and deletes all the views.
void Clear();
void set_ideal_bounds(size_t index, const gfx::Rect& bounds) {
check_index(index);
entries_[index].ideal_bounds = bounds;
}
const gfx::Rect& ideal_bounds(size_t index) const {
check_index(index);
return entries_[index].ideal_bounds;
}
// Returns the index of the specified view, or nullopt if the view isn't in
// the model.
absl::optional<size_t> GetIndexOfView(const View* view) const;
protected:
ViewModelBase();
// Returns the view at the specified index. Note: Most users should use
// view_at() in the subclass, to get a view of the correct type. (Do not call
// ViewAtBase then static_cast to the desired type.)
View* ViewAtBase(size_t index) const {
check_index(index);
return entries_[index].view;
}
// Adds |view| to this model. This does not add |view| to a view hierarchy,
// only to this model.
void AddUnsafe(View* view, size_t index);
private:
// For access to ViewAtBase().
friend class ViewModelUtils;
void check_index(size_t index) const { DCHECK_LT(index, entries_.size()); }
Entries entries_;
};
// ViewModelT is used to track an 'interesting' set of a views. Often times
// during animations views are removed after a delay, which makes for tricky
// coordinate conversion as you have to account for the possibility of the
// indices from the model not lining up with those you expect. This class lets
// you define the 'interesting' views and operate on those views.
template <class T>
class ViewModelT : public ViewModelBase {
public:
ViewModelT() = default;
ViewModelT(const ViewModelT&) = delete;
ViewModelT& operator=(const ViewModelT&) = delete;
// Adds |view| to this model. This does not add |view| to a view hierarchy,
// only to this model.
void Add(T* view, size_t index) { AddUnsafe(view, index); }
// Returns the view at the specified index.
T* view_at(size_t index) const { return static_cast<T*>(ViewAtBase(index)); }
};
// ViewModel is a collection of views with no specfic type. If all views have
// the same type, the use of ViewModelT is preferred so that the views can be
// retrieved without potentially unsafe downcasts.
using ViewModel = ViewModelT<View>;
} // namespace views
#endif // UI_VIEWS_VIEW_MODEL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model.h | C++ | unknown | 4,356 |
// 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/view_model.h"
#include <string>
#include "base/strings/string_number_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/view.h"
namespace views {
namespace {
// Returns a string containing the x-coordinate of each of the views in |model|.
std::string BoundsString(const ViewModel& model) {
std::string result;
for (size_t i = 0; i < model.view_size(); ++i) {
if (i != 0)
result += " ";
result += base::NumberToString(model.ideal_bounds(i).x());
}
return result;
}
// Returns a string containing the id of each of the views in |model|.
std::string ViewIDsString(const ViewModel& model) {
std::string result;
for (size_t i = 0; i < model.view_size(); ++i) {
if (i != 0)
result += " ";
result += base::NumberToString(model.view_at(i)->GetID());
}
return result;
}
} // namespace
TEST(ViewModel, BasicAssertions) {
View v1;
ViewModel model;
model.Add(&v1, 0);
EXPECT_EQ(1u, model.view_size());
EXPECT_EQ(&v1, model.view_at(0));
gfx::Rect v1_bounds(1, 2, 3, 4);
model.set_ideal_bounds(0, v1_bounds);
EXPECT_EQ(v1_bounds, model.ideal_bounds(0));
EXPECT_EQ(0u, model.GetIndexOfView(&v1));
}
TEST(ViewModel, Move) {
View v1, v2, v3;
v1.SetID(0);
v2.SetID(1);
v3.SetID(2);
ViewModel model;
model.Add(&v1, 0);
model.Add(&v2, 1);
model.Add(&v3, 2);
model.Move(0, 2);
EXPECT_EQ("1 2 0", ViewIDsString(model));
model.Move(2, 0);
EXPECT_EQ("0 1 2", ViewIDsString(model));
}
TEST(ViewModel, MoveViewOnly) {
View v1, v2, v3;
v1.SetID(0);
v2.SetID(1);
v3.SetID(2);
ViewModel model;
model.Add(&v1, 0);
model.Add(&v2, 1);
model.Add(&v3, 2);
model.set_ideal_bounds(0, gfx::Rect(10, 0, 1, 2));
model.set_ideal_bounds(1, gfx::Rect(11, 0, 1, 2));
model.set_ideal_bounds(2, gfx::Rect(12, 0, 1, 2));
model.MoveViewOnly(0, 2);
EXPECT_EQ("1 2 0", ViewIDsString(model));
EXPECT_EQ("10 11 12", BoundsString(model));
model.MoveViewOnly(2, 0);
EXPECT_EQ("0 1 2", ViewIDsString(model));
EXPECT_EQ("10 11 12", BoundsString(model));
model.MoveViewOnly(0, 1);
EXPECT_EQ("1 0 2", ViewIDsString(model));
EXPECT_EQ("10 11 12", BoundsString(model));
model.MoveViewOnly(1, 0);
EXPECT_EQ("0 1 2", ViewIDsString(model));
EXPECT_EQ("10 11 12", BoundsString(model));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model_unittest.cc | C++ | unknown | 2,488 |
// 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/view_model_utils.h"
#include <iterator>
#include "base/ranges/algorithm.h"
#include "ui/views/view.h"
#include "ui/views/view_model.h"
namespace views {
namespace {
// Used in calculating ideal bounds.
int primary_axis_coordinate(bool is_horizontal, const gfx::Point& point) {
return is_horizontal ? point.x() : point.y();
}
} // namespace
// static
void ViewModelUtils::SetViewBoundsToIdealBounds(const ViewModelBase& model) {
for (auto& entry : model.entries())
entry.view->SetBoundsRect(entry.ideal_bounds);
}
// static
bool ViewModelUtils::IsAtIdealBounds(const ViewModelBase& model) {
return base::ranges::all_of(
model.entries(), [](const ViewModelBase::Entry& entry) {
return entry.view->bounds() == entry.ideal_bounds;
});
}
// static
size_t ViewModelUtils::DetermineMoveIndex(const ViewModelBase& model,
View* view,
bool is_horizontal,
int x,
int y) {
const auto& entries = model.entries();
const int value = primary_axis_coordinate(is_horizontal, gfx::Point(x, y));
DCHECK(model.GetIndexOfView(view).has_value());
auto iter = entries.begin();
for (; iter->view != view; ++iter) {
const int mid_point = primary_axis_coordinate(
is_horizontal, iter->ideal_bounds.CenterPoint());
if (value < mid_point)
return static_cast<size_t>(std::distance(entries.begin(), iter));
}
if (std::next(iter) == entries.end())
return static_cast<size_t>(std::distance(entries.begin(), iter));
// For indices after the current index ignore the bounds of the view being
// dragged. This keeps the view from bouncing around as moved.
const int delta = primary_axis_coordinate(
is_horizontal, std::next(iter)->ideal_bounds.origin() -
iter->ideal_bounds.origin().OffsetFromOrigin());
for (++iter; iter != entries.end(); ++iter) {
const int mid_point = primary_axis_coordinate(
is_horizontal, iter->ideal_bounds.CenterPoint()) -
delta;
if (value < mid_point)
return static_cast<size_t>(std::distance(entries.begin(), iter)) - 1;
}
return entries.size() - 1;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model_utils.cc | C++ | unknown | 2,494 |
// 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_VIEW_MODEL_UTILS_H_
#define UI_VIEWS_VIEW_MODEL_UTILS_H_
#include <stddef.h>
#include "ui/views/views_export.h"
namespace views {
class View;
class ViewModelBase;
class VIEWS_EXPORT ViewModelUtils {
public:
ViewModelUtils() = delete;
ViewModelUtils(const ViewModelUtils&) = delete;
ViewModelUtils& operator=(const ViewModelUtils&) = delete;
// Sets the bounds of each view to its ideal bounds.
static void SetViewBoundsToIdealBounds(const ViewModelBase& model);
// Returns true if the Views in |model| are at their ideal bounds.
static bool IsAtIdealBounds(const ViewModelBase& model);
// Returns the index to move |view| to based on a coordinate of |x| and |y|.
static size_t DetermineMoveIndex(const ViewModelBase& model,
View* view,
bool is_horizontal,
int x,
int y);
};
} // namespace views
#endif // UI_VIEWS_VIEW_MODEL_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model_utils.h | C++ | unknown | 1,166 |
// 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/view_model_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/view.h"
#include "ui/views/view_model.h"
namespace views {
// Makes sure SetViewBoundsToIdealBounds updates the view appropriately.
TEST(ViewModelUtils, SetViewBoundsToIdealBounds) {
View v1;
ViewModel model;
model.Add(&v1, 0);
gfx::Rect v1_bounds(1, 2, 3, 4);
model.set_ideal_bounds(0, v1_bounds);
ViewModelUtils::SetViewBoundsToIdealBounds(model);
EXPECT_EQ(v1_bounds, v1.bounds());
}
// Assertions for DetermineMoveIndex.
TEST(ViewModelUtils, DetermineMoveIndex) {
View v1, v2, v3;
ViewModel model;
model.Add(&v1, 0);
model.Add(&v2, 1);
model.Add(&v3, 2);
model.set_ideal_bounds(0, gfx::Rect(0, 0, 10, 10));
model.set_ideal_bounds(1, gfx::Rect(10, 0, 1000, 10));
model.set_ideal_bounds(2, gfx::Rect(1010, 0, 2, 10));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v1, true, -10, 0));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v1, true, 4, 0));
EXPECT_EQ(1u, ViewModelUtils::DetermineMoveIndex(model, &v1, true, 506, 0));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v1, true, 1010, 0));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v1, true, 2000, 0));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v2, true, -10, 0));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v2, true, 4, 0));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v2, true, 12, 0));
// Try the same when vertical.
model.set_ideal_bounds(0, gfx::Rect(0, 0, 10, 10));
model.set_ideal_bounds(1, gfx::Rect(0, 10, 10, 1000));
model.set_ideal_bounds(2, gfx::Rect(0, 1010, 10, 2));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v1, false, 0, -10));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v1, false, 0, 4));
EXPECT_EQ(1u, ViewModelUtils::DetermineMoveIndex(model, &v1, false, 0, 506));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v1, false, 0, 1010));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v1, false, 0, 2000));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v2, false, 0, -10));
EXPECT_EQ(0u, ViewModelUtils::DetermineMoveIndex(model, &v2, false, 0, 4));
EXPECT_EQ(2u, ViewModelUtils::DetermineMoveIndex(model, &v2, false, 0, 12));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_model_utils_unittest.cc | C++ | unknown | 2,499 |
// 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_VIEW_OBSERVER_H_
#define UI_VIEWS_VIEW_OBSERVER_H_
#include "ui/views/views_export.h"
namespace views {
class View;
struct ViewHierarchyChangedDetails;
// ViewObserver is used to observe changes to a View. The first argument to all
// ViewObserver functions is the View the observer was added to.
class VIEWS_EXPORT ViewObserver {
public:
// Called when |child| is added as a child to |observed_view|.
virtual void OnChildViewAdded(View* observed_view, View* child) {}
// Called when |child| is removed as a child of |observed_view|.
virtual void OnChildViewRemoved(View* observed_view, View* child) {}
// Called when |observed_view|, an ancestor, or its Widget has its visibility
// changed. |starting_view| is who |View::SetVisible()| was called on (or null
// if the Widget visibility changed).
virtual void OnViewVisibilityChanged(View* observed_view,
View* starting_view) {}
// Called from View::PreferredSizeChanged().
virtual void OnViewPreferredSizeChanged(View* observed_view) {}
// Called when the bounds of |observed_view| change.
virtual void OnViewBoundsChanged(View* observed_view) {}
// Called when the bounds of |observed_view|'s layer change.
virtual void OnLayerTargetBoundsChanged(View* observed_view) {}
// Called when the `observed_view`'s layer transform changes.
// TODO(crbug.com/1203386): This is temporarily added to support a migration.
// Do not use for new call sites, we should instead figure out how to
// migrate this method (and possibly others) into callbacks.
virtual void OnViewLayerTransformed(View* observed_view) {}
// Called when `observed_view`'s layer clip rect changes.
virtual void OnViewLayerClipRectChanged(View* observed_view) {}
// Called when View::ViewHierarchyChanged() is called.
virtual void OnViewHierarchyChanged(
View* observed_view,
const ViewHierarchyChangedDetails& details) {}
// Called when View::AddedToWidget() is called.
virtual void OnViewAddedToWidget(View* observed_view) {}
// Called when View::RemovedFromWidget() is called.
virtual void OnViewRemovedFromWidget(View* observed_view) {}
// Called when a child is reordered among its siblings, specifically
// View::ReorderChildView() is called on |observed_view|.
virtual void OnChildViewReordered(View* observed_view, View* child) {}
// Called when the active UI theme or NativeTheme has changed for
// |observed_view|.
virtual void OnViewThemeChanged(View* observed_view) {}
// Called from ~View.
virtual void OnViewIsDeleting(View* observed_view) {}
// Called immediately after |observed_view| has gained focus.
virtual void OnViewFocused(View* observed_view) {}
// Called immediately after |observed_view| has lost focus.
virtual void OnViewBlurred(View* observed_view) {}
protected:
virtual ~ViewObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_VIEW_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_observer.h | C++ | unknown | 3,119 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view_targeter.h"
#include "ui/events/event_target.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/view_targeter_delegate.h"
namespace views {
ViewTargeter::ViewTargeter(ViewTargeterDelegate* delegate)
: delegate_(delegate) {
DCHECK(delegate_);
}
ViewTargeter::~ViewTargeter() = default;
bool ViewTargeter::DoesIntersectRect(const View* target,
const gfx::Rect& rect) const {
return delegate_->DoesIntersectRect(target, rect);
}
View* ViewTargeter::TargetForRect(View* root, const gfx::Rect& rect) const {
return delegate_->TargetForRect(root, rect);
}
ui::EventTarget* ViewTargeter::FindTargetForEvent(ui::EventTarget* root,
ui::Event* event) {
View* const view = static_cast<View*>(root);
if (event->IsKeyEvent())
return FindTargetForKeyEvent(view, *event->AsKeyEvent());
if (event->IsScrollEvent())
return FindTargetForScrollEvent(view, *event->AsScrollEvent());
CHECK(event->IsGestureEvent())
<< "ViewTargeter does not yet support this event type.";
ui::GestureEvent* gesture = event->AsGestureEvent();
View* gesture_target = FindTargetForGestureEvent(view, *gesture);
root->ConvertEventToTarget(gesture_target, gesture);
return gesture_target;
}
ui::EventTarget* ViewTargeter::FindNextBestTarget(
ui::EventTarget* previous_target,
ui::Event* event) {
if (!previous_target)
return nullptr;
if (event->IsGestureEvent()) {
ui::GestureEvent* gesture = event->AsGestureEvent();
ui::EventTarget* next_target =
FindNextBestTargetForGestureEvent(previous_target, *gesture);
previous_target->ConvertEventToTarget(next_target, gesture);
return next_target;
}
return previous_target->GetParentTarget();
}
View* ViewTargeter::FindTargetForKeyEvent(View* root, const ui::KeyEvent& key) {
if (root->GetFocusManager())
return root->GetFocusManager()->GetFocusedView();
return nullptr;
}
View* ViewTargeter::FindTargetForScrollEvent(View* root,
const ui::ScrollEvent& scroll) {
gfx::Rect rect(scroll.location(), gfx::Size(1, 1));
return root->GetEffectiveViewTargeter()->TargetForRect(root, rect);
}
View* ViewTargeter::FindTargetForGestureEvent(View* root,
const ui::GestureEvent& gesture) {
// TODO(tdanderson): The only code path that performs targeting for gestures
// uses the ViewTargeter installed on the RootView (i.e.,
// a RootViewTargeter). Provide a default implementation
// here if we need to be able to perform gesture targeting
// starting at an arbitrary node in a Views tree.
NOTREACHED_NORETURN();
}
ui::EventTarget* ViewTargeter::FindNextBestTargetForGestureEvent(
ui::EventTarget* previous_target,
const ui::GestureEvent& gesture) {
NOTREACHED_NORETURN();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_targeter.cc | C++ | unknown | 3,182 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_VIEW_TARGETER_H_
#define UI_VIEWS_VIEW_TARGETER_H_
#include "base/memory/raw_ptr.h"
#include "ui/events/event_targeter.h"
#include "ui/views/views_export.h"
namespace gfx {
class Rect;
} // namespace gfx
namespace ui {
class GestureEvent;
class KeyEvent;
class ScrollEvent;
} // namespace ui
namespace views {
class View;
class ViewTargeterDelegate;
// A ViewTargeter is installed on a View that wishes to use the custom
// hit-testing or event-targeting behaviour defined by |delegate|.
class VIEWS_EXPORT ViewTargeter : public ui::EventTargeter {
public:
explicit ViewTargeter(ViewTargeterDelegate* delegate);
ViewTargeter(const ViewTargeter&) = delete;
ViewTargeter& operator=(const ViewTargeter&) = delete;
~ViewTargeter() override;
// A call-through to DoesIntersectRect() on |delegate_|.
bool DoesIntersectRect(const View* target, const gfx::Rect& rect) const;
// A call-through to TargetForRect() on |delegate_|.
View* TargetForRect(View* root, const gfx::Rect& rect) const;
protected:
// ui::EventTargeter:
ui::EventTarget* FindTargetForEvent(ui::EventTarget* root,
ui::Event* event) override;
ui::EventTarget* FindNextBestTarget(ui::EventTarget* previous_target,
ui::Event* event) override;
private:
View* FindTargetForKeyEvent(View* root, const ui::KeyEvent& key);
View* FindTargetForScrollEvent(View* root, const ui::ScrollEvent& scroll);
virtual View* FindTargetForGestureEvent(View* root,
const ui::GestureEvent& gesture);
virtual ui::EventTarget* FindNextBestTargetForGestureEvent(
ui::EventTarget* previous_target,
const ui::GestureEvent& gesture);
// ViewTargeter does not own the |delegate_|, but |delegate_| must
// outlive the targeter.
raw_ptr<ViewTargeterDelegate, DanglingUntriaged> delegate_;
};
} // namespace views
#endif // UI_VIEWS_VIEW_TARGETER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_targeter.h | C++ | unknown | 2,126 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view_targeter_delegate.h"
#include <limits.h>
#include "base/containers/adapters.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/views/rect_based_targeting_utils.h"
#include "ui/views/view.h"
namespace {
// The minimum percentage of a view's area that needs to be covered by a rect
// representing a touch region in order for that view to be considered by the
// rect-based targeting algorithm.
static const float kRectTargetOverlap = 0.6f;
} // namespace
namespace views {
// TODO(tdanderson): Move the contents of rect_based_targeting_utils.(h|cc)
// into here.
bool ViewTargeterDelegate::DoesIntersectRect(const View* target,
const gfx::Rect& rect) const {
return target->GetLocalBounds().Intersects(rect);
}
View* ViewTargeterDelegate::TargetForRect(View* root, const gfx::Rect& rect) {
// |rect_view| represents the current best candidate to return
// if rect-based targeting (i.e., fuzzing) is used.
// |rect_view_distance| is used to keep track of the distance
// between the center point of |rect_view| and the center
// point of |rect|.
View* rect_view = nullptr;
int rect_view_distance = INT_MAX;
// |point_view| represents the view that would have been returned
// from this function call if point-based targeting were used.
View* point_view = nullptr;
View::Views children = root->GetChildrenInZOrder();
DCHECK_EQ(root->children().size(), children.size());
for (auto* child : base::Reversed(children)) {
if (!child->GetCanProcessEventsWithinSubtree() || !child->GetEnabled())
continue;
// Ignore any children which are invisible or do not intersect |rect|.
if (!child->GetVisible())
continue;
gfx::RectF rect_in_child_coords_f(rect);
View::ConvertRectToTarget(root, child, &rect_in_child_coords_f);
gfx::Rect rect_in_child_coords =
gfx::ToEnclosingRect(rect_in_child_coords_f);
if (!child->HitTestRect(rect_in_child_coords))
continue;
View* cur_view = child->GetEventHandlerForRect(rect_in_child_coords);
if (views::UsePointBasedTargeting(rect))
return cur_view;
gfx::RectF cur_view_bounds_f(cur_view->GetLocalBounds());
View::ConvertRectToTarget(cur_view, root, &cur_view_bounds_f);
gfx::Rect cur_view_bounds = gfx::ToEnclosingRect(cur_view_bounds_f);
if (views::PercentCoveredBy(cur_view_bounds, rect) >= kRectTargetOverlap) {
// |cur_view| is a suitable candidate for rect-based targeting.
// Check to see if it is the closest suitable candidate so far.
gfx::Point touch_center(rect.CenterPoint());
int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center,
cur_view_bounds);
if (!rect_view || cur_dist < rect_view_distance) {
rect_view = cur_view;
rect_view_distance = cur_dist;
}
} else if (!rect_view && !point_view) {
// Rect-based targeting has not yielded any candidates so far. Check
// if point-based targeting would have selected |cur_view|.
gfx::Point point_in_child_coords(rect_in_child_coords.CenterPoint());
if (child->HitTestPoint(point_in_child_coords))
point_view = child->GetEventHandlerForPoint(point_in_child_coords);
}
}
if (views::UsePointBasedTargeting(rect) || (!rect_view && !point_view))
return root;
return rect_view ? rect_view : point_view;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_targeter_delegate.cc | C++ | unknown | 3,652 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_VIEW_TARGETER_DELEGATE_H_
#define UI_VIEWS_VIEW_TARGETER_DELEGATE_H_
#include "ui/views/views_export.h"
namespace gfx {
class Rect;
}
namespace views {
class View;
// Defines the default behaviour for hit-testing and event-targeting against a
// View using a rectangular region representing an event's location (i.e., the
// bounding box of a gesture or a 1x1 rect in the case of a mouse event). Views
// wishing to define custom hit-testing or event-targeting behaviour do so by
// extending ViewTargeterDelegate and then installing a ViewTargeter on
// themselves.
class VIEWS_EXPORT ViewTargeterDelegate {
public:
ViewTargeterDelegate() = default;
ViewTargeterDelegate(const ViewTargeterDelegate&) = delete;
ViewTargeterDelegate& operator=(const ViewTargeterDelegate&) = delete;
virtual ~ViewTargeterDelegate() = default;
// Returns true if |target| should be considered as a candidate target for
// an event having |rect| as its location, where |rect| is in the local
// coordinate space of |target|. Overrides of this method by a View subclass
// should enforce DCHECK_EQ(this, target).
// TODO(tdanderson): Consider changing the name of this method to better
// reflect its purpose.
virtual bool DoesIntersectRect(const View* target,
const gfx::Rect& rect) const;
// If point-based targeting should be used, return the deepest visible
// descendant of |root| that contains the center point of |rect|.
// If rect-based targeting (i.e., fuzzing) should be used, return the
// closest visible descendant of |root| having at least kRectTargetOverlap of
// its area covered by |rect|. If no such descendant exists, return the
// deepest visible descendant of |root| that contains the center point of
// |rect|. See http://goo.gl/3Jp2BD for more information about rect-based
// targeting.
virtual View* TargetForRect(View* root, const gfx::Rect& rect);
};
} // namespace views
#endif // UI_VIEWS_VIEW_TARGETER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_targeter_delegate.h | C++ | unknown | 2,187 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view_targeter.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/events/event_targeter.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/views/masked_targeter_delegate.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view_targeter_delegate.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/unique_widget_ptr.h"
namespace views {
// A derived class of View used for testing purposes.
class TestingView : public View, public ViewTargeterDelegate {
public:
TestingView() = default;
TestingView(const TestingView&) = delete;
TestingView& operator=(const TestingView&) = delete;
~TestingView() override = default;
// Reset all test state.
void Reset() { SetCanProcessEventsWithinSubtree(true); }
// A call-through function to ViewTargeterDelegate::DoesIntersectRect().
bool TestDoesIntersectRect(const View* target, const gfx::Rect& rect) const {
return DoesIntersectRect(target, rect);
}
};
// A derived class of View having a triangular-shaped hit test mask.
class TestMaskedView : public View, public MaskedTargeterDelegate {
public:
TestMaskedView() = default;
TestMaskedView(const TestMaskedView&) = delete;
TestMaskedView& operator=(const TestMaskedView&) = delete;
~TestMaskedView() override = default;
// A call-through function to MaskedTargeterDelegate::DoesIntersectRect().
bool TestDoesIntersectRect(const View* target, const gfx::Rect& rect) const {
return DoesIntersectRect(target, rect);
}
private:
// MaskedTargeterDelegate:
bool GetHitTestMask(SkPath* mask) const override {
DCHECK(mask);
SkScalar w = SkIntToScalar(width());
SkScalar h = SkIntToScalar(height());
// Create a triangular mask within the bounds of this View.
mask->moveTo(w / 2, 0);
mask->lineTo(w, h);
mask->lineTo(0, h);
mask->close();
return true;
}
};
namespace test {
// TODO(tdanderson): Clean up this test suite by moving common code/state into
// ViewTargeterTest and overriding SetUp(), TearDown(), etc.
// See crbug.com/355680.
class ViewTargeterTest : public ViewsTestBase {
public:
ViewTargeterTest() = default;
ViewTargeterTest(const ViewTargeterTest&) = delete;
ViewTargeterTest& operator=(const ViewTargeterTest&) = delete;
~ViewTargeterTest() override = default;
void SetGestureHandler(internal::RootView* root_view, View* handler) {
root_view->gesture_handler_ = handler;
}
void SetGestureHandlerSetBeforeProcessing(internal::RootView* root_view,
bool set) {
root_view->gesture_handler_set_before_processing_ = set;
}
};
namespace {
gfx::Point ConvertPointFromWidgetToView(View* view, const gfx::Point& p) {
gfx::Point tmp(p);
View::ConvertPointToTarget(view->GetWidget()->GetRootView(), view, &tmp);
return tmp;
}
gfx::Rect ConvertRectFromWidgetToView(View* view, const gfx::Rect& r) {
gfx::Rect tmp(r);
tmp.set_origin(ConvertPointFromWidgetToView(view, r.origin()));
return tmp;
}
} // namespace
// Verifies that the the functions ViewTargeter::FindTargetForEvent()
// and ViewTargeter::FindNextBestTarget() are implemented correctly
// for key events.
TEST_F(ViewTargeterTest, ViewTargeterForKeyEvents) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
widget->Init(std::move(init_params));
widget->Show();
View* content = widget->SetContentsView(std::make_unique<View>());
View* child = content->AddChildView(std::make_unique<View>());
View* grandchild = child->AddChildView(std::make_unique<View>());
grandchild->SetFocusBehavior(View::FocusBehavior::ALWAYS);
grandchild->RequestFocus();
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
ui::KeyEvent key_event('a', ui::VKEY_A, ui::DomCode::NONE, ui::EF_NONE);
// The focused view should be the initial target of the event.
ui::EventTarget* current_target =
targeter->FindTargetForEvent(root_view, &key_event);
EXPECT_EQ(grandchild, static_cast<View*>(current_target));
// Verify that FindNextBestTarget() will return the parent view of the
// argument (and NULL if the argument has no parent view).
current_target = targeter->FindNextBestTarget(grandchild, &key_event);
EXPECT_EQ(child, static_cast<View*>(current_target));
current_target = targeter->FindNextBestTarget(child, &key_event);
EXPECT_EQ(content, static_cast<View*>(current_target));
current_target = targeter->FindNextBestTarget(content, &key_event);
EXPECT_EQ(widget->GetRootView(), static_cast<View*>(current_target));
current_target =
targeter->FindNextBestTarget(widget->GetRootView(), &key_event);
EXPECT_EQ(nullptr, static_cast<View*>(current_target));
}
// Verifies that the the functions ViewTargeter::FindTargetForEvent()
// and ViewTargeter::FindNextBestTarget() are implemented correctly
// for scroll events.
TEST_F(ViewTargeterTest, ViewTargeterForScrollEvents) {
UniqueWidgetPtr 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, 200, 200);
widget->Init(std::move(init_params));
// The coordinates used for SetBounds() are in the parent coordinate space.
auto owning_content = std::make_unique<View>();
owning_content->SetBounds(0, 0, 100, 100);
View* content = widget->SetContentsView(std::move(owning_content));
View* child = content->AddChildView(std::make_unique<View>());
child->SetBounds(50, 50, 20, 20);
View* grandchild = child->AddChildView(std::make_unique<View>());
grandchild->SetBounds(0, 0, 5, 5);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
// The event falls within the bounds of |child| and |content| but not
// |grandchild|, so |child| should be the initial target for the event.
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(60, 60),
ui::EventTimeForNow(), 0, 0, 3, 0, 3, 2);
ui::EventTarget* current_target =
targeter->FindTargetForEvent(root_view, &scroll);
EXPECT_EQ(child, static_cast<View*>(current_target));
// Verify that FindNextBestTarget() will return the parent view of the
// argument (and NULL if the argument has no parent view).
current_target = targeter->FindNextBestTarget(child, &scroll);
EXPECT_EQ(content, static_cast<View*>(current_target));
current_target = targeter->FindNextBestTarget(content, &scroll);
EXPECT_EQ(widget->GetRootView(), static_cast<View*>(current_target));
current_target = targeter->FindNextBestTarget(widget->GetRootView(), &scroll);
EXPECT_EQ(nullptr, static_cast<View*>(current_target));
// The event falls outside of the original specified bounds of |content|,
// |child|, and |grandchild|. But since |content| is the contents view,
// and contents views are resized to fill the entire area of the root
// view, the event's initial target should still be |content|.
scroll = ui::ScrollEvent(ui::ET_SCROLL, gfx::Point(150, 150),
ui::EventTimeForNow(), 0, 0, 3, 0, 3, 2);
current_target = targeter->FindTargetForEvent(root_view, &scroll);
EXPECT_EQ(content, static_cast<View*>(current_target));
}
// Convenience to make constructing a GestureEvent simpler.
ui::GestureEvent CreateTestGestureEvent(
const ui::GestureEventDetails& details) {
return ui::GestureEvent(details.bounding_box().CenterPoint().x(),
details.bounding_box().CenterPoint().y(), 0,
base::TimeTicks(), details);
}
// Verifies that the the functions ViewTargeter::FindTargetForEvent()
// and ViewTargeter::FindNextBestTarget() are implemented correctly
// for gesture events.
TEST_F(ViewTargeterTest, ViewTargeterForGestureEvents) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.bounds = gfx::Rect(0, 0, 200, 200);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
content->SetBounds(0, 0, 100, 100);
// The coordinates used for SetBounds() are in the parent coordinate space.
View* child = content->AddChildView(std::make_unique<View>());
child->SetBounds(50, 50, 20, 20);
View* grandchild = child->AddChildView(std::make_unique<View>());
grandchild->SetBounds(0, 0, 5, 5);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
// Define some gesture events for testing.
gfx::RectF bounding_box(gfx::PointF(46.f, 46.f), gfx::SizeF(8.f, 8.f));
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_bounding_box(bounding_box);
ui::GestureEvent tap = CreateTestGestureEvent(details);
details = ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN);
details.set_bounding_box(bounding_box);
ui::GestureEvent scroll_begin = CreateTestGestureEvent(details);
details = ui::GestureEventDetails(ui::ET_GESTURE_END);
details.set_bounding_box(bounding_box);
ui::GestureEvent end = CreateTestGestureEvent(details);
// Assume that the view currently handling gestures has been set as
// |grandchild| by a previous gesture event. Thus subsequent TAP and
// SCROLL_BEGIN events should be initially targeted to |grandchild|, and
// re-targeting should be prohibited for TAP but permitted for
// GESTURE_SCROLL_BEGIN (which should be re-targeted to the parent of
// |grandchild|).
SetGestureHandlerSetBeforeProcessing(root_view, true);
SetGestureHandler(root_view, grandchild);
EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &tap));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &tap));
EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &scroll_begin));
EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &scroll_begin));
// GESTURE_END events should be targeted to the existing gesture handler,
// but re-targeting should be prohibited.
EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &end));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &end));
// Assume that the view currently handling gestures is still set as
// |grandchild|, but this was not done by a previous gesture. Thus we are
// in the process of finding the View to which subsequent gestures will be
// dispatched, so TAP and SCROLL_BEGIN events should be re-targeted up
// the ancestor chain.
SetGestureHandlerSetBeforeProcessing(root_view, false);
EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &tap));
EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &scroll_begin));
// GESTURE_END events are not permitted to be re-targeted up the ancestor
// chain; they are only ever targeted in the case where the gesture handler
// was established by a previous gesture.
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &end));
// Assume that the default gesture handler was set by the previous gesture,
// but that this handler is currently NULL. No gesture events should be
// re-targeted in this case (regardless of the view that is passed in to
// FindNextBestTarget() as the previous target).
SetGestureHandler(root_view, nullptr);
SetGestureHandlerSetBeforeProcessing(root_view, true);
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(child, &tap));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(nullptr, &tap));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(content, &scroll_begin));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(content, &end));
// Reset the locations of the gesture events to be in the root view
// coordinate space since we are about to call FindTargetForEvent()
// again (calls to FindTargetForEvent() and FindNextBestTarget()
// mutate the location of the gesture events to be in the coordinate
// space of the returned view).
details = ui::GestureEventDetails(ui::ET_GESTURE_TAP);
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
details = ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN);
details.set_bounding_box(bounding_box);
scroll_begin = CreateTestGestureEvent(details);
details = ui::GestureEventDetails(ui::ET_GESTURE_END);
details.set_bounding_box(bounding_box);
end = CreateTestGestureEvent(details);
// If no default gesture handler is currently set, targeting should be
// performed using the location of the gesture event for a TAP and a
// SCROLL_BEGIN.
SetGestureHandlerSetBeforeProcessing(root_view, false);
EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &tap));
EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &scroll_begin));
// If no default gesture handler is currently set, GESTURE_END events
// should never be re-targeted to any View.
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(nullptr, &end));
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(child, &end));
}
// Tests that the contents view is targeted instead of the root view for
// gesture events that should be targeted to the contents view. Also
// tests that the root view is targeted for gesture events which should
// not be targeted to any other view in the views tree.
TEST_F(ViewTargeterTest, TargetContentsAndRootView) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.bounds = gfx::Rect(0, 0, 200, 200);
widget->Init(std::move(init_params));
// The coordinates used for SetBounds() are in the parent coordinate space.
auto owning_content = std::make_unique<View>();
owning_content->SetBounds(0, 0, 100, 100);
View* content = widget->SetContentsView(std::move(owning_content));
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
// A gesture event located entirely within the contents view should
// target the contents view.
gfx::RectF bounding_box(gfx::PointF(96.f, 96.f), gfx::SizeF(8.f, 8.f));
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_bounding_box(bounding_box);
ui::GestureEvent tap = CreateTestGestureEvent(details);
EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap));
// A gesture event not located entirely within the contents view but
// having its center within the contents view should target
// the contents view.
bounding_box = gfx::RectF(gfx::PointF(194.f, 100.f), gfx::SizeF(8.f, 8.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap));
// A gesture event with its center not located within the contents
// view but that overlaps the contents view by at least 60% should
// target the contents view.
bounding_box = gfx::RectF(gfx::PointF(50.f, 0.f), gfx::SizeF(400.f, 200.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap));
// A gesture event not overlapping the contents view by at least
// 60% and not having its center within the contents view should
// be targeted to the root view.
bounding_box = gfx::RectF(gfx::PointF(196.f, 100.f), gfx::SizeF(8.f, 8.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(widget->GetRootView(),
targeter->FindTargetForEvent(root_view, &tap));
// A gesture event completely outside the contents view should be targeted
// to the root view.
bounding_box = gfx::RectF(gfx::PointF(205.f, 100.f), gfx::SizeF(8.f, 8.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(widget->GetRootView(),
targeter->FindTargetForEvent(root_view, &tap));
// A gesture event with dimensions 1x1 located entirely within the
// contents view should target the contents view.
bounding_box = gfx::RectF(gfx::PointF(175.f, 100.f), gfx::SizeF(1.f, 1.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap));
// A gesture event with dimensions 1x1 located entirely outside the
// contents view should be targeted to the root view.
bounding_box = gfx::RectF(gfx::PointF(205.f, 100.f), gfx::SizeF(1.f, 1.f));
details.set_bounding_box(bounding_box);
tap = CreateTestGestureEvent(details);
EXPECT_EQ(widget->GetRootView(),
targeter->FindTargetForEvent(root_view, &tap));
}
// Tests that calls to FindTargetForEvent() and FindNextBestTarget() change
// the location of a gesture event to be in the correct coordinate space.
TEST_F(ViewTargeterTest, GestureEventCoordinateConversion) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.bounds = gfx::Rect(0, 0, 200, 200);
widget->Init(std::move(init_params));
// The coordinates used for SetBounds() are in the parent coordinate space.
View* content = widget->SetContentsView(std::make_unique<View>());
content->SetBounds(0, 0, 100, 100);
View* child = content->AddChildView(std::make_unique<View>());
child->SetBounds(50, 50, 20, 20);
View* grandchild = child->AddChildView(std::make_unique<View>());
grandchild->SetBounds(5, 5, 10, 10);
View* great_grandchild = grandchild->AddChildView(std::make_unique<View>());
great_grandchild->SetBounds(3, 3, 4, 4);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
// Define a GESTURE_TAP event with a bounding box centered at (60, 60)
// in root view coordinates with width and height of 4.
gfx::RectF bounding_box(gfx::PointF(58.f, 58.f), gfx::SizeF(4.f, 4.f));
gfx::PointF center_point(bounding_box.CenterPoint());
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_bounding_box(bounding_box);
ui::GestureEvent tap = CreateTestGestureEvent(details);
// Calculate the location of the gesture in each of the different
// coordinate spaces.
gfx::Point location_in_root(gfx::ToFlooredPoint(center_point));
EXPECT_EQ(gfx::Point(60, 60), location_in_root);
gfx::Point location_in_great_grandchild(
ConvertPointFromWidgetToView(great_grandchild, location_in_root));
EXPECT_EQ(gfx::Point(2, 2), location_in_great_grandchild);
gfx::Point location_in_grandchild(
ConvertPointFromWidgetToView(grandchild, location_in_root));
EXPECT_EQ(gfx::Point(5, 5), location_in_grandchild);
gfx::Point location_in_child(
ConvertPointFromWidgetToView(child, location_in_root));
EXPECT_EQ(gfx::Point(10, 10), location_in_child);
gfx::Point location_in_content(
ConvertPointFromWidgetToView(content, location_in_root));
EXPECT_EQ(gfx::Point(60, 60), location_in_content);
// Verify the location of |tap| is in screen coordinates.
EXPECT_EQ(gfx::Point(60, 60), tap.location());
// The initial target should be |great_grandchild| and the location of
// the event should be changed into the coordinate space of the target.
EXPECT_EQ(great_grandchild, targeter->FindTargetForEvent(root_view, &tap));
EXPECT_EQ(location_in_great_grandchild, tap.location());
SetGestureHandler(root_view, great_grandchild);
// The next target should be |grandchild| and the location of
// the event should be changed into the coordinate space of the target.
EXPECT_EQ(grandchild, targeter->FindNextBestTarget(great_grandchild, &tap));
EXPECT_EQ(location_in_grandchild, tap.location());
SetGestureHandler(root_view, grandchild);
// The next target should be |child| and the location of
// the event should be changed into the coordinate space of the target.
EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &tap));
EXPECT_EQ(location_in_child, tap.location());
SetGestureHandler(root_view, child);
// The next target should be |content| and the location of
// the event should be changed into the coordinate space of the target.
EXPECT_EQ(content, targeter->FindNextBestTarget(child, &tap));
EXPECT_EQ(location_in_content, tap.location());
SetGestureHandler(root_view, content);
// The next target should be |root_view| and the location of
// the event should be changed into the coordinate space of the target.
EXPECT_EQ(widget->GetRootView(), targeter->FindNextBestTarget(content, &tap));
EXPECT_EQ(location_in_root, tap.location());
SetGestureHandler(root_view, widget->GetRootView());
// The next target should be NULL and the location of the event should
// remain unchanged.
EXPECT_EQ(nullptr, targeter->FindNextBestTarget(widget->GetRootView(), &tap));
EXPECT_EQ(location_in_root, tap.location());
}
// Tests that the functions ViewTargeterDelegate::DoesIntersectRect()
// and MaskedTargeterDelegate::DoesIntersectRect() work as intended when
// called on views which are derived from ViewTargeterDelegate.
// Also verifies that ViewTargeterDelegate::DoesIntersectRect() can
// be called from the ViewTargeter installed on RootView.
TEST_F(ViewTargeterTest, DoesIntersectRect) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 650, 650);
widget->Init(std::move(params));
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ViewTargeter* view_targeter = root_view->targeter();
// The coordinates used for SetBounds() are in the parent coordinate space.
auto* v1 = root_view->AddChildView(std::make_unique<TestMaskedView>());
v1->SetBounds(0, 0, 200, 200);
auto* v2 = root_view->AddChildView(std::make_unique<TestingView>());
v2->SetBounds(300, 0, 300, 300);
auto* v3 = v2->AddChildView(std::make_unique<TestMaskedView>());
v3->SetBounds(0, 0, 100, 100);
// The coordinates used below are in the local coordinate space of the
// view that is passed in as an argument.
// Hit tests against |v1|, which has a hit test mask.
EXPECT_TRUE(v1->TestDoesIntersectRect(v1, gfx::Rect(0, 0, 200, 200)));
EXPECT_TRUE(v1->TestDoesIntersectRect(v1, gfx::Rect(-10, -10, 110, 12)));
EXPECT_TRUE(v1->TestDoesIntersectRect(v1, gfx::Rect(112, 142, 1, 1)));
EXPECT_FALSE(v1->TestDoesIntersectRect(v1, gfx::Rect(0, 0, 20, 20)));
EXPECT_FALSE(v1->TestDoesIntersectRect(v1, gfx::Rect(-10, -10, 90, 12)));
EXPECT_FALSE(v1->TestDoesIntersectRect(v1, gfx::Rect(150, 49, 1, 1)));
// Hit tests against |v2|, which does not have a hit test mask.
EXPECT_TRUE(v2->TestDoesIntersectRect(v2, gfx::Rect(0, 0, 200, 200)));
EXPECT_TRUE(v2->TestDoesIntersectRect(v2, gfx::Rect(-10, 250, 60, 60)));
EXPECT_TRUE(v2->TestDoesIntersectRect(v2, gfx::Rect(250, 250, 1, 1)));
EXPECT_FALSE(v2->TestDoesIntersectRect(v2, gfx::Rect(-10, 250, 7, 7)));
EXPECT_FALSE(v2->TestDoesIntersectRect(v2, gfx::Rect(-1, -1, 1, 1)));
// Hit tests against |v3|, which has a hit test mask and is a child of |v2|.
EXPECT_TRUE(v3->TestDoesIntersectRect(v3, gfx::Rect(0, 0, 50, 50)));
EXPECT_TRUE(v3->TestDoesIntersectRect(v3, gfx::Rect(90, 90, 1, 1)));
EXPECT_FALSE(v3->TestDoesIntersectRect(v3, gfx::Rect(10, 125, 50, 50)));
EXPECT_FALSE(v3->TestDoesIntersectRect(v3, gfx::Rect(110, 110, 1, 1)));
// Verify that hit-testing is performed correctly when using the
// call-through function ViewTargeter::DoesIntersectRect().
EXPECT_TRUE(
view_targeter->DoesIntersectRect(root_view, gfx::Rect(0, 0, 50, 50)));
EXPECT_FALSE(
view_targeter->DoesIntersectRect(root_view, gfx::Rect(-20, -20, 10, 10)));
}
// Tests that calls made directly on the hit-testing methods in View
// (HitTestPoint(), HitTestRect(), etc.) return the correct values.
TEST_F(ViewTargeterTest, HitTestCallsOnView) {
// The coordinates in this test are in the coordinate space of the root view.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// |v1| has no hit test mask. No ViewTargeter is installed on |v1|, which
// means that View::HitTestRect() will call into the targeter installed on
// the root view instead when we hit test against |v1|.
gfx::Rect v1_bounds = gfx::Rect(0, 0, 100, 100);
TestingView* v1 = root_view->AddChildView(std::make_unique<TestingView>());
v1->SetBoundsRect(v1_bounds);
// |v2| has a triangular hit test mask. Install a ViewTargeter on |v2| which
// will be called into by View::HitTestRect().
gfx::Rect v2_bounds = gfx::Rect(105, 0, 100, 100);
TestMaskedView* v2 =
root_view->AddChildView(std::make_unique<TestMaskedView>());
v2->SetBoundsRect(v2_bounds);
v2->SetEventTargeter(std::make_unique<ViewTargeter>(v2));
gfx::Point v1_centerpoint = v1_bounds.CenterPoint();
gfx::Point v2_centerpoint = v2_bounds.CenterPoint();
gfx::Point v1_origin = v1_bounds.origin();
gfx::Point v2_origin = v2_bounds.origin();
gfx::Rect r1(10, 10, 110, 15);
gfx::Rect r2(106, 1, 98, 98);
gfx::Rect r3(0, 0, 300, 300);
gfx::Rect r4(115, 342, 200, 10);
// Test calls into View::HitTestPoint().
EXPECT_TRUE(
v1->HitTestPoint(ConvertPointFromWidgetToView(v1, v1_centerpoint)));
EXPECT_TRUE(
v2->HitTestPoint(ConvertPointFromWidgetToView(v2, v2_centerpoint)));
EXPECT_TRUE(v1->HitTestPoint(ConvertPointFromWidgetToView(v1, v1_origin)));
EXPECT_FALSE(v2->HitTestPoint(ConvertPointFromWidgetToView(v2, v2_origin)));
// Test calls into View::HitTestRect().
EXPECT_TRUE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r1)));
EXPECT_FALSE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r1)));
EXPECT_FALSE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r2)));
EXPECT_TRUE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r2)));
EXPECT_TRUE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r3)));
EXPECT_TRUE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r3)));
EXPECT_FALSE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r4)));
EXPECT_FALSE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r4)));
// Test calls into View::GetEventHandlerForPoint().
EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_centerpoint));
EXPECT_EQ(v2, root_view->GetEventHandlerForPoint(v2_centerpoint));
EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_origin));
EXPECT_EQ(root_view, root_view->GetEventHandlerForPoint(v2_origin));
// Test calls into View::GetTooltipHandlerForPoint().
EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_centerpoint));
EXPECT_EQ(v2, root_view->GetTooltipHandlerForPoint(v2_centerpoint));
EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_origin));
EXPECT_EQ(root_view, root_view->GetTooltipHandlerForPoint(v2_origin));
EXPECT_FALSE(v1->GetTooltipHandlerForPoint(v2_origin));
}
TEST_F(ViewTargeterTest, FavorChildContainingHitBounds) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.bounds = gfx::Rect(0, 0, 200, 200);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
content->SetBounds(0, 0, 50, 50);
View* child = content->AddChildView(std::make_unique<View>());
child->SetBounds(2, 2, 50, 50);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
ui::EventTargeter* targeter = root_view->targeter();
gfx::RectF bounding_box(gfx::PointF(4.f, 4.f), gfx::SizeF(42.f, 42.f));
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_bounding_box(bounding_box);
ui::GestureEvent tap = CreateTestGestureEvent(details);
EXPECT_EQ(child, targeter->FindTargetForEvent(root_view, &tap));
}
} // namespace test
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_targeter_unittest.cc | C++ | unknown | 28,730 |
// 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_VIEW_TEST_API_H_
#define UI_VIEWS_VIEW_TEST_API_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/view.h"
namespace views {
class VIEWS_EXPORT ViewTestApi {
public:
explicit ViewTestApi(View* view) : view_(view) {}
ViewTestApi(const ViewTestApi&) = delete;
ViewTestApi& operator=(const ViewTestApi&) = delete;
~ViewTestApi() = default;
bool needs_layout() { return view_->needs_layout(); }
void ClearNeedsPaint() { view_->needs_paint_ = false; }
bool needs_paint() const { return view_->needs_paint_; }
private:
raw_ptr<View> view_;
};
} // namespace views
#endif // UI_VIEWS_VIEW_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_test_api.h | C++ | unknown | 789 |
// 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/view_tracker.h"
namespace views {
ViewTracker::ViewTracker(View* view) {
SetView(view);
}
ViewTracker::~ViewTracker() = default;
void ViewTracker::SetView(View* view) {
if (view == view_)
return;
observation_.Reset();
view_ = view;
if (view_)
observation_.Observe(view_.get());
}
void ViewTracker::OnViewIsDeleting(View* observed_view) {
SetView(nullptr);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_tracker.cc | C++ | unknown | 570 |
// 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_VIEW_TRACKER_H_
#define UI_VIEWS_VIEW_TRACKER_H_
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/views_export.h"
namespace views {
// ViewTracker tracks a single View. When the View is deleted it's removed.
class VIEWS_EXPORT ViewTracker : public ViewObserver {
public:
explicit ViewTracker(View* view = nullptr);
ViewTracker(const ViewTracker&) = delete;
ViewTracker& operator=(const ViewTracker&) = delete;
~ViewTracker() override;
void SetView(View* view);
View* view() { return view_; }
const View* view() const { return view_; }
// ViewObserver:
void OnViewIsDeleting(View* observed_view) override;
private:
raw_ptr<View> view_ = nullptr;
base::ScopedObservation<View, ViewObserver> observation_{this};
};
} // namespace views
#endif // UI_VIEWS_VIEW_TRACKER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_tracker.h | C++ | unknown | 1,066 |
// 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/view_tracker.h"
#include <memory>
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
namespace views {
using ViewTrackerTest = ViewsTestBase;
TEST_F(ViewTrackerTest, RemovedOnDelete) {
ViewTracker tracker;
{
View view;
tracker.SetView(&view);
EXPECT_EQ(&view, tracker.view());
}
EXPECT_EQ(nullptr, tracker.view());
}
TEST_F(ViewTrackerTest, ObservedAtConstruction) {
std::unique_ptr<ViewTracker> tracker;
{
View view;
tracker = std::make_unique<ViewTracker>(&view);
EXPECT_EQ(&view, tracker->view());
}
EXPECT_EQ(nullptr, tracker->view());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_tracker_unittest.cc | C++ | unknown | 793 |
// 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/view.h"
#include <stddef.h>
#include <map>
#include <memory>
#include <set>
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/icu_test_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "cc/paint/display_item_list.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/paint_context.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/compositor/test/test_layers.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/scoped_target_handler.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/test_native_theme.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/paint_info.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view_observer.h"
#include "ui/views/view_utils.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/native_widget.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/window/dialog_delegate.h"
using testing::ElementsAre;
namespace {
// Returns true if |ancestor| is an ancestor of |layer|.
bool LayerIsAncestor(const ui::Layer* ancestor, const ui::Layer* layer) {
while (layer && layer != ancestor)
layer = layer->parent();
return layer == ancestor;
}
// Convenience functions for walking a View tree.
const views::View* FirstView(const views::View* view) {
const views::View* v = view;
while (!v->children().empty())
v = v->children().front();
return v;
}
const views::View* NextView(const views::View* view) {
const views::View* v = view;
const views::View* parent = v->parent();
if (!parent)
return nullptr;
const auto next = std::next(parent->FindChild(v));
return (next == parent->children().cend()) ? parent : FirstView(*next);
}
// Convenience functions for walking a Layer tree.
const ui::Layer* FirstLayer(const ui::Layer* layer) {
const ui::Layer* l = layer;
while (!l->children().empty())
l = l->children().front();
return l;
}
const ui::Layer* NextLayer(const ui::Layer* layer) {
const ui::Layer* parent = layer->parent();
if (!parent)
return nullptr;
const std::vector<ui::Layer*> children = parent->children();
const auto i = base::ranges::find(children, layer) + 1;
return (i == children.cend()) ? parent : FirstLayer(*i);
}
// Given the root nodes of a View tree and a Layer tree, makes sure the two
// trees are in sync.
bool ViewAndLayerTreeAreConsistent(const views::View* view,
const ui::Layer* layer) {
const views::View* v = FirstView(view);
const ui::Layer* l = FirstLayer(layer);
while (v && l) {
// Find the view with a layer.
while (v && !v->layer())
v = NextView(v);
EXPECT_TRUE(v);
if (!v)
return false;
// Check if the View tree and the Layer tree are in sync.
EXPECT_EQ(l, v->layer());
if (v->layer() != l)
return false;
// Check if the visibility states of the View and the Layer are in sync.
EXPECT_EQ(l->IsVisible(), v->IsDrawn());
if (v->IsDrawn() != l->IsVisible()) {
for (const views::View* vv = v; vv; vv = vv->parent())
LOG(ERROR) << "V: " << vv << " " << vv->GetVisible() << " "
<< vv->IsDrawn() << " " << vv->layer();
for (const ui::Layer* ll = l; ll; ll = ll->parent())
LOG(ERROR) << "L: " << ll << " " << ll->IsVisible();
return false;
}
// Check if the size of the View and the Layer are in sync.
EXPECT_EQ(l->bounds(), v->bounds());
if (v->bounds() != l->bounds())
return false;
if (v == view || l == layer)
return v == view && l == layer;
v = NextView(v);
l = NextLayer(l);
}
return false;
}
// Constructs a View tree with the specified depth.
void ConstructTree(views::View* view, int depth) {
if (depth == 0)
return;
int count = base::RandInt(1, 5);
for (int i = 0; i < count; i++) {
views::View* v = new views::View;
view->AddChildView(v);
if (base::RandDouble() > 0.5)
v->SetPaintToLayer();
if (base::RandDouble() < 0.2)
v->SetVisible(false);
ConstructTree(v, depth - 1);
}
}
void ScrambleTree(views::View* view) {
if (view->children().empty())
return;
for (views::View* child : view->children())
ScrambleTree(child);
size_t count = view->children().size();
if (count > 1) {
const uint64_t max = count - 1;
size_t a = static_cast<size_t>(base::RandGenerator(max));
size_t b = static_cast<size_t>(base::RandGenerator(max));
if (a != b) {
views::View* view_a = view->children()[a];
views::View* view_b = view->children()[b];
view->ReorderChildView(view_a, b);
view->ReorderChildView(view_b, a);
}
}
if (!view->layer() && base::RandDouble() < 0.1)
view->SetPaintToLayer();
if (base::RandDouble() < 0.1)
view->SetVisible(!view->GetVisible());
}
} // namespace
namespace views {
using ViewTest = ViewsTestBase;
// A derived class for testing purpose.
class TestView : public View {
public:
TestView() = default;
~TestView() override = default;
// Reset all test state
void Reset() {
did_change_bounds_ = false;
did_layout_ = false;
last_mouse_event_type_ = 0;
location_.SetPoint(0, 0);
received_mouse_enter_ = false;
received_mouse_exit_ = false;
did_paint_ = false;
accelerator_count_map_.clear();
}
// Exposed as public for testing.
void DoFocus() { views::View::Focus(); }
void DoBlur() { views::View::Blur(); }
void Layout() override {
did_layout_ = true;
View::Layout();
}
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnMouseEntered(const ui::MouseEvent& event) override;
void OnMouseExited(const ui::MouseEvent& event) override;
void OnPaint(gfx::Canvas* canvas) override;
void OnDidSchedulePaint(const gfx::Rect& rect) override;
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
void OnThemeChanged() override;
void OnAccessibilityEvent(ax::mojom::Event event_type) override;
// OnBoundsChanged.
bool did_change_bounds_;
gfx::Rect new_bounds_;
// Layout.
bool did_layout_ = false;
// MouseEvent.
int last_mouse_event_type_;
gfx::Point location_;
bool received_mouse_enter_;
bool received_mouse_exit_;
bool delete_on_pressed_ = false;
// Painting.
std::vector<gfx::Rect> scheduled_paint_rects_;
bool did_paint_ = false;
// Accelerators.
std::map<ui::Accelerator, int> accelerator_count_map_;
// Native theme.
raw_ptr<const ui::NativeTheme> native_theme_ = nullptr;
// Accessibility events
ax::mojom::Event last_a11y_event_ = ax::mojom::Event::kNone;
};
class A11yTestView : public TestView {
public:
// Convenience constructor to test `View::SetAccessibilityProperties`
explicit A11yTestView(
absl::optional<ax::mojom::Role> role = absl::nullopt,
absl::optional<std::u16string> name = absl::nullopt,
absl::optional<std::u16string> description = absl::nullopt,
absl::optional<std::u16string> role_description = absl::nullopt,
absl::optional<ax::mojom::NameFrom> name_from = absl::nullopt,
absl::optional<ax::mojom::DescriptionFrom> description_from =
absl::nullopt) {
SetAccessibilityProperties(
std::move(role), std::move(name), std::move(description),
std::move(role_description), std::move(name_from),
std::move(description_from));
}
~A11yTestView() override = default;
// Overridden from views::View:
void AdjustAccessibleName(std::u16string& new_name,
ax::mojom::NameFrom& name_from) override {
if (name_prefix_.has_value()) {
new_name.insert(0, name_prefix_.value());
}
if (name_from_.has_value()) {
name_from = name_from_.value();
}
}
void SetAccessibleNamePrefix(absl::optional<std::u16string> name_prefix) {
name_prefix_ = std::move(name_prefix);
}
void SetAccessibleNameFrom(absl::optional<ax::mojom::NameFrom> name_from) {
name_from_ = std::move(name_from);
}
private:
absl::optional<std::u16string> name_prefix_;
absl::optional<ax::mojom::NameFrom> name_from_;
};
////////////////////////////////////////////////////////////////////////////////
// Metadata
////////////////////////////////////////////////////////////////////////////////
TEST_F(ViewTest, MetadataTest) {
auto test_view = std::make_unique<TestView>();
test::TestViewMetadata(test_view.get());
}
////////////////////////////////////////////////////////////////////////////////
// Layout
////////////////////////////////////////////////////////////////////////////////
TEST_F(ViewTest, LayoutCalledInvalidateAndOriginChanges) {
TestView parent;
TestView* child = new TestView;
gfx::Rect parent_rect(0, 0, 100, 100);
parent.SetBoundsRect(parent_rect);
parent.Reset();
// |AddChildView| invalidates parent's layout.
parent.AddChildView(child);
// Change rect so that only rect's origin is affected.
parent.SetBoundsRect(parent_rect + gfx::Vector2d(10, 0));
EXPECT_TRUE(parent.did_layout_);
// After child layout is invalidated, parent and child must be laid out
// during parent->BoundsChanged(...) call.
parent.Reset();
child->Reset();
child->InvalidateLayout();
parent.SetBoundsRect(parent_rect + gfx::Vector2d(20, 0));
EXPECT_TRUE(parent.did_layout_);
EXPECT_TRUE(child->did_layout_);
}
// Tests that SizeToPreferredSize will trigger a Layout if the size has changed
// or if layout is marked invalid.
TEST_F(ViewTest, SizeToPreferredSizeInducesLayout) {
TestView example_view;
example_view.SetPreferredSize(gfx::Size(101, 102));
example_view.SizeToPreferredSize();
EXPECT_TRUE(example_view.did_layout_);
example_view.Reset();
example_view.SizeToPreferredSize();
EXPECT_FALSE(example_view.did_layout_);
example_view.InvalidateLayout();
example_view.SizeToPreferredSize();
EXPECT_TRUE(example_view.did_layout_);
}
void TestView::OnAccessibilityEvent(ax::mojom::Event event_type) {
last_a11y_event_ = event_type;
}
////////////////////////////////////////////////////////////////////////////////
// Accessibility Property Setters
////////////////////////////////////////////////////////////////////////////////
TEST_F(ViewTest, PauseAccessibilityEvents) {
TestView v;
EXPECT_EQ(v.pause_accessibility_events_, false);
// Setting the accessible name when `pause_accessibility_events_` is false
// should result in an event being fired.
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetAccessibleName(u"Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
EXPECT_EQ(v.pause_accessibility_events_, false);
// Setting the accessible name when `pause_accessibility_events_` is true
// should result in no event being fired.
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.pause_accessibility_events_ = true;
v.SetAccessibleName(u"New Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kNone);
EXPECT_EQ(v.pause_accessibility_events_, true);
// A11yTestView views are constructed using `SetAccessibilityProperties`. By
// default, `pause_accessibility_events_` is false. It is temporarily set to
// true and then reset at the end of initialization.
A11yTestView ax_v(ax::mojom::Role::kButton, u"Name", u"Description");
EXPECT_EQ(ax_v.last_a11y_event_, ax::mojom::Event::kNone);
EXPECT_EQ(ax_v.pause_accessibility_events_, false);
}
TEST_F(ViewTest, SetAccessibilityPropertiesRoleNameDescription) {
views::test::AXEventCounter ax_counter(views::AXEventManager::Get());
A11yTestView v(ax::mojom::Role::kButton, u"Name", u"Description");
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kButton);
EXPECT_EQ(data.role, ax::mojom::Role::kButton);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kAttribute);
EXPECT_EQ(v.GetAccessibleDescription(), u"Description");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kAriaDescription);
// There should not be any accessibility events fired when properties are
// set within `SetAccessibilityProperties`. For the above properties, the only
// event type is `kTextChanged`.
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 0);
// Setting the accessible name after initialization should result in an event
// being fired.
v.SetAccessibleName(u"New Name");
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 1);
}
TEST_F(ViewTest, SetAccessibilityPropertiesRoleNameDescriptionDetailed) {
views::test::AXEventCounter ax_counter(views::AXEventManager::Get());
A11yTestView v(ax::mojom::Role::kButton, u"Name", u"Description",
/*role_description*/ u"", ax::mojom::NameFrom::kContents,
ax::mojom::DescriptionFrom::kTitle);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kButton);
EXPECT_EQ(data.role, ax::mojom::Role::kButton);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kContents);
EXPECT_EQ(v.GetAccessibleDescription(), u"Description");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kTitle);
// There should not be any accessibility events fired when properties are
// set within `SetAccessibilityProperties`. For the above properties, the only
// event type is `kTextChanged`.
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 0);
// Setting the accessible name after initialization should result in an event
// being fired.
v.SetAccessibleName(u"New Name");
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 1);
}
TEST_F(ViewTest, SetAccessibilityPropertiesRoleRolenameNameDescription) {
views::test::AXEventCounter ax_counter(views::AXEventManager::Get());
A11yTestView v(ax::mojom::Role::kButton, u"Name", u"Description",
u"Super Button");
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kButton);
EXPECT_EQ(data.role, ax::mojom::Role::kButton);
EXPECT_EQ(
data.GetString16Attribute(ax::mojom::StringAttribute::kRoleDescription),
u"Super Button");
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(v.GetAccessibleDescription(), u"Description");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
// There should not be any accessibility events fired when properties are
// set within `SetAccessibilityProperties`. For the above properties, the only
// event type is `kTextChanged`.
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 0);
// Setting the accessible name after initialization should result in an event
// being fired.
v.SetAccessibleName(u"New Name");
EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kTextChanged, &v), 1);
}
TEST_F(ViewTest, SetAccessibilityPropertiesRoleAndRoleDescription) {
A11yTestView v(ax::mojom::Role::kButton,
/*name*/ absl::nullopt,
/*description*/ absl::nullopt, u"Super Button");
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kButton);
EXPECT_EQ(data.role, ax::mojom::Role::kButton);
EXPECT_EQ(
data.GetString16Attribute(ax::mojom::StringAttribute::kRoleDescription),
u"Super Button");
}
TEST_F(ViewTest, SetAccessibilityPropertiesNameExplicitlyEmpty) {
A11yTestView v(ax::mojom::Role::kNone,
/*name*/ u"",
/*description*/ u"",
/*role_description*/ u"",
ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kNone);
EXPECT_EQ(data.role, ax::mojom::Role::kNone);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
}
TEST_F(ViewTest, SetAccessibleRole) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kUnknown);
EXPECT_EQ(data.role, ax::mojom::Role::kUnknown);
data = ui::AXNodeData();
v.SetAccessibleRole(ax::mojom::Role::kButton);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(data.role, ax::mojom::Role::kButton);
EXPECT_EQ(v.GetAccessibleRole(), ax::mojom::Role::kButton);
}
TEST_F(ViewTest, SetAccessibleNameToStringWithRoleAlreadySet) {
TestView v;
v.SetAccessibleRole(ax::mojom::Role::kButton);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
v.SetAccessibleName(u"Name");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
}
TEST_F(ViewTest, AdjustAccessibleNameStringWithRoleAlreadySet) {
A11yTestView v(ax::mojom::Role::kButton);
v.SetAccessibleNamePrefix(u"Prefix: ");
ui::AXNodeData data;
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
v.SetAccessibleName(u"Name");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Prefix: Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Prefix: Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
}
TEST_F(ViewTest, SetAccessibleNameToLabelWithRoleAlreadySet) {
TestView label;
label.SetAccessibleName(u"Label's Name");
TestView v;
v.SetAccessibleRole(ax::mojom::Role::kButton);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kNone);
EXPECT_FALSE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds));
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
v.SetAccessibleName(&label);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Label's Name");
EXPECT_TRUE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds));
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kRelatedElement);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Label's Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
}
TEST_F(ViewTest, AdjustAccessibleNameFrom) {
A11yTestView v(ax::mojom::Role::kTextField);
v.SetAccessibleNameFrom(ax::mojom::NameFrom::kPlaceholder);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
v.SetAccessibleName(u"Name");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kPlaceholder);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
}
TEST_F(ViewTest, AdjustAccessibleNameFromLabelWithRoleAlreadySet) {
TestView label;
label.SetAccessibleName(u"Label's Name");
A11yTestView v(ax::mojom::Role::kButton);
v.SetAccessibleNamePrefix(u"Prefix: ");
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kNone);
EXPECT_FALSE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds));
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
v.SetAccessibleName(&label);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Prefix: Label's Name");
EXPECT_TRUE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds));
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kRelatedElement);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Prefix: Label's Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
}
TEST_F(ViewTest, SetAccessibleNameExplicitlyEmpty) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kNone);
data = ui::AXNodeData();
v.SetAccessibleName(u"", ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
}
TEST_F(ViewTest, SetAccessibleNameExplicitlyEmptyToRemoveName) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.SetAccessibleRole(ax::mojom::Role::kButton);
v.SetAccessibleName(u"Name");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
data = ui::AXNodeData();
v.SetAccessibleName(u"", ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(static_cast<ax::mojom::NameFrom>(
data.GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)),
ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
}
TEST_F(ViewTest, SetAccessibleNameToStringRoleNotInitiallySet) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
// Setting the name prior to setting the role violates an expectation of
// `AXNodeData::SetName`. `View::SetAccessibleName` handles that case by
// setting the property but not adding it to `ax_node_data_` until a role
// has been set.
v.SetAccessibleName(u"Name");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
// Setting the role to a valid role should add the previously-set name to
// ax_node_data_. Note there is currently no role-changed accessibility event.
v.SetAccessibleRole(ax::mojom::Role::kButton);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kNone);
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
}
TEST_F(ViewTest, SetAccessibleNameToLabelRoleNotInitiallySet) {
TestView label;
label.SetAccessibleName(u"Label's Name");
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
// Setting the name prior to setting the role violates an expectation of
// `AXNodeData::SetName`. `View::SetAccessibleName` handles that case by
// setting the property but not adding it to `ax_node_data_` until a role
// has been set.
v.SetAccessibleName(&label);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Label's Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kTextChanged);
v.last_a11y_event_ = ax::mojom::Event::kNone;
data = ui::AXNodeData();
// Setting the role to a valid role should add the previously-set name to
// ax_node_data_. Note there is currently no role-changed accessibility event.
v.SetAccessibleRole(ax::mojom::Role::kButton);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleName(), u"Label's Name");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
u"Label's Name");
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kNone);
}
TEST_F(ViewTest, SetAccessibleDescriptionToString) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"");
data = ui::AXNodeData();
v.SetAccessibleDescription(u"Description");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"Description");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
}
TEST_F(ViewTest, SetAccessibleDescriptionToLabel) {
TestView label;
label.SetAccessibleName(u"Label's Name");
TestView v;
v.SetAccessibleRole(ax::mojom::Role::kButton);
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kNone);
EXPECT_FALSE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kDescribedbyIds));
data = ui::AXNodeData();
v.SetAccessibleDescription(&label);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"Label's Name");
EXPECT_TRUE(
data.HasIntListAttribute(ax::mojom::IntListAttribute::kDescribedbyIds));
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kRelatedElement);
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Label's Name");
}
TEST_F(ViewTest, SetAccessibleDescriptionExplicitlyEmpty) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kNone);
data = ui::AXNodeData();
v.SetAccessibleDescription(
u"", ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
}
TEST_F(ViewTest, SetAccessibleDescriptionExplicitlyEmptyToRemoveDescription) {
TestView v;
ui::AXNodeData data = ui::AXNodeData();
v.SetAccessibleRole(ax::mojom::Role::kButton);
v.SetAccessibleDescription(u"Description");
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"Description");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"Description");
data = ui::AXNodeData();
v.SetAccessibleDescription(
u"", ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
v.GetAccessibleNodeData(&data);
EXPECT_EQ(v.GetAccessibleDescription(), u"");
EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kDescription),
u"");
EXPECT_EQ(static_cast<ax::mojom::DescriptionFrom>(data.GetIntAttribute(
ax::mojom::IntAttribute::kDescriptionFrom)),
ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
}
////////////////////////////////////////////////////////////////////////////////
// OnBoundsChanged
////////////////////////////////////////////////////////////////////////////////
TEST_F(ViewTest, OnBoundsChangedFiresA11yEvent) {
TestView v;
// Should change when scaled or moved.
gfx::Rect initial(0, 0, 200, 200);
gfx::Rect scaled(0, 0, 250, 250);
gfx::Rect moved(100, 100, 250, 250);
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetBoundsRect(initial);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kLocationChanged);
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetBoundsRect(scaled);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kLocationChanged);
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetBoundsRect(moved);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kLocationChanged);
}
void TestView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
did_change_bounds_ = true;
new_bounds_ = bounds();
}
TEST_F(ViewTest, OnBoundsChanged) {
TestView v;
gfx::Rect prev_rect(0, 0, 200, 200);
gfx::Rect new_rect(100, 100, 250, 250);
v.SetBoundsRect(prev_rect);
v.Reset();
v.SetBoundsRect(new_rect);
EXPECT_TRUE(v.did_change_bounds_);
EXPECT_EQ(v.new_bounds_, new_rect);
EXPECT_EQ(v.bounds(), new_rect);
}
TEST_F(ViewTest, TransformFiresA11yEvent) {
TestView v;
v.SetPaintToLayer();
gfx::Rect bounds(0, 0, 200, 200);
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetBoundsRect(bounds);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kLocationChanged);
gfx::Transform transform;
transform.Translate(gfx::Vector2dF(10, 10));
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.layer()->SetTransform(transform);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kLocationChanged);
}
////////////////////////////////////////////////////////////////////////////////
// OnStateChanged
////////////////////////////////////////////////////////////////////////////////
TEST_F(ViewTest, OnStateChangedFiresA11yEvent) {
TestView v;
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetEnabled(false);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kStateChanged);
v.last_a11y_event_ = ax::mojom::Event::kNone;
v.SetEnabled(true);
EXPECT_EQ(v.last_a11y_event_, ax::mojom::Event::kStateChanged);
}
////////////////////////////////////////////////////////////////////////////////
// MouseEvent
////////////////////////////////////////////////////////////////////////////////
bool TestView::OnMousePressed(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
if (delete_on_pressed_)
delete this;
return true;
}
bool TestView::OnMouseDragged(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
return true;
}
void TestView::OnMouseReleased(const ui::MouseEvent& event) {
last_mouse_event_type_ = event.type();
location_.SetPoint(event.x(), event.y());
}
void TestView::OnMouseEntered(const ui::MouseEvent& event) {
received_mouse_enter_ = true;
}
void TestView::OnMouseExited(const ui::MouseEvent& event) {
received_mouse_exit_ = true;
}
TEST_F(ViewTest, MouseEvent) {
auto view1 = std::make_unique<TestView>();
view1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
auto view2 = std::make_unique<TestView>();
view2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
UniqueWidgetPtr widget(std::make_unique<Widget>());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
auto* root = AsViewClass<internal::RootView>(widget->GetRootView());
TestView* v1 = root->AddChildView(std::move(view1));
TestView* v2 = v1->AddChildView(std::move(view2));
v1->Reset();
v2->Reset();
gfx::Point p1(110, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_PRESSED);
EXPECT_EQ(v2->location_.x(), 10);
EXPECT_EQ(v2->location_.y(), 20);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
// Drag event out of bounds. Should still go to v2
v1->Reset();
v2->Reset();
gfx::Point p2(50, 40);
ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, p2, p2, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
root->OnMouseDragged(dragged);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_DRAGGED);
EXPECT_EQ(v2->location_.x(), -50);
EXPECT_EQ(v2->location_.y(), -60);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
// Releasted event out of bounds. Should still go to v2
v1->Reset();
v2->Reset();
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
root->OnMouseDragged(released);
EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_RELEASED);
EXPECT_EQ(v2->location_.x(), -100);
EXPECT_EQ(v2->location_.y(), -100);
// Make sure v1 did not receive the event
EXPECT_EQ(v1->last_mouse_event_type_, 0);
}
// Confirm that a view can be deleted as part of processing a mouse press.
TEST_F(ViewTest, DeleteOnPressed) {
auto view1 = std::make_unique<TestView>();
view1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
auto view2 = std::make_unique<TestView>();
view2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
view1->Reset();
view2->Reset();
UniqueWidgetPtr widget(std::make_unique<Widget>());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
TestView* v1 = root->AddChildView(std::move(view1));
TestView* v2 = v1->AddChildView(std::move(view2));
v2->delete_on_pressed_ = true;
gfx::Point point(110, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_TRUE(v1->children().empty());
}
// Detect the return value of OnMouseDragged
TEST_F(ViewTest, DetectReturnFormDrag) {
auto view1 = std::make_unique<TestView>();
view1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
auto view2 = std::make_unique<TestView>();
view2->SetBoundsRect(gfx::Rect(100, 100, 100, 100));
UniqueWidgetPtr widget(std::make_unique<Widget>());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
auto* root = AsViewClass<internal::RootView>(widget->GetRootView());
TestView* v1 = root->AddChildView(std::move(view1));
TestView* v2 = v1->AddChildView(std::move(view2));
v1->Reset();
v2->Reset();
gfx::Point p1(110, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
v1->Reset();
v2->Reset();
gfx::Point p2(50, 40);
ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, p2, p2, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, 0);
EXPECT_TRUE(root->OnMouseDragged(dragged));
v1->Reset();
v2->Reset();
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
EXPECT_TRUE(root->OnMouseDragged(released));
}
////////////////////////////////////////////////////////////////////////////////
// Painting
////////////////////////////////////////////////////////////////////////////////
void TestView::OnPaint(gfx::Canvas* canvas) {
did_paint_ = true;
}
namespace {
// Helper class to create a Widget with standard parameters that is closed when
// the helper class goes out of scope.
class ScopedTestPaintWidget {
public:
explicit ScopedTestPaintWidget(Widget::InitParams params)
: widget_(new Widget) {
widget_->Init(std::move(params));
widget_->GetRootView()->SetBounds(0, 0, 25, 26);
}
ScopedTestPaintWidget(const ScopedTestPaintWidget&) = delete;
ScopedTestPaintWidget& operator=(const ScopedTestPaintWidget&) = delete;
~ScopedTestPaintWidget() { widget_->CloseNow(); }
Widget* operator->() { return widget_; }
private:
raw_ptr<Widget> widget_;
};
} // namespace
TEST_F(ViewTest, PaintEmptyView) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
// |v1| is empty.
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 0, 1);
root_view->AddChildView(v1);
// |v11| is a child of an empty |v1|.
TestView* v11 = new TestView;
v11->SetBounds(3, 4, 6, 5);
v1->AddChildView(v11);
// |v2| is not.
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
root_view->AddChildView(v2);
// Paint "everything".
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
first_paint.size()));
// The empty view has nothing to paint so it doesn't try build a cache, nor do
// its children which would be clipped by its (empty) self.
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v11->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintWithMovedViewUsesCache) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect pixel_rect = gfx::Rect(1, 1);
float device_scale_factor = 1.f;
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
// The visual rects for (clip, drawing, transform) should be in layer space.
gfx::Rect expected_visual_rect_in_layer_space(10, 11, 12, 13);
int item_index = 3;
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
// If invalidation doesn't intersect v1, we paint with the cache.
list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_FALSE(v1->did_paint_);
v1->Reset();
// If invalidation does intersect v1, we don't paint with the cache.
list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, v1->bounds(), false));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
// Moving the view should still use the cache when the invalidation doesn't
// intersect v1.
list = base::MakeRefCounted<cc::DisplayItemList>();
v1->SetX(9);
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_FALSE(v1->did_paint_);
v1->Reset();
item_index = 3;
expected_visual_rect_in_layer_space.SetRect(9, 11, 12, 13);
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
// Moving the view should not use the cache when painting without
// invalidation.
list = base::MakeRefCounted<cc::DisplayItemList>();
v1->SetX(8);
root_view->PaintFromPaintRoot(ui::PaintContext(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false),
ui::PaintContext::CLONE_WITHOUT_INVALIDATION));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
item_index = 3;
expected_visual_rect_in_layer_space.SetRect(8, 11, 12, 13);
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
}
TEST_F(ViewTest, PaintWithMovedViewUsesCacheInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect pixel_rect = gfx::Rect(1, 1);
float device_scale_factor = 1.f;
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
// The visual rects for (clip, drawing, transform) should be in layer space.
// x: 25 - 10(x) - 12(width) = 3
gfx::Rect expected_visual_rect_in_layer_space(3, 11, 12, 13);
int item_index = 3;
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
// If invalidation doesn't intersect v1, we paint with the cache.
list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_FALSE(v1->did_paint_);
v1->Reset();
// If invalidation does intersect v1, we don't paint with the cache.
list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, v1->bounds(), false));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
// Moving the view should still use the cache when the invalidation doesn't
// intersect v1.
list = base::MakeRefCounted<cc::DisplayItemList>();
v1->SetX(9);
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false));
EXPECT_FALSE(v1->did_paint_);
v1->Reset();
item_index = 3;
// x: 25 - 9(x) - 12(width) = 4
expected_visual_rect_in_layer_space.SetRect(4, 11, 12, 13);
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
// Moving the view should not use the cache when painting without
// invalidation.
list = base::MakeRefCounted<cc::DisplayItemList>();
v1->SetX(8);
root_view->PaintFromPaintRoot(ui::PaintContext(
ui::PaintContext(list.get(), device_scale_factor, pixel_rect, false),
ui::PaintContext::CLONE_WITHOUT_INVALIDATION));
EXPECT_TRUE(v1->did_paint_);
v1->Reset();
item_index = 3;
// x: 25 - 8(x) - 12(width) = 5
expected_visual_rect_in_layer_space.SetRect(5, 11, 12, 13);
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index++));
EXPECT_EQ(expected_visual_rect_in_layer_space,
list->VisualRectForTesting(item_index));
}
TEST_F(ViewTest, PaintWithUnknownInvalidation) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), 1.f, first_paint, false));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(1, 1);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
// With a known invalidation, v1 and v2 are not painted.
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->PaintFromPaintRoot(
ui::PaintContext(list.get(), 1.f, paint_area, false));
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
// With unknown invalidation, v1 and v2 are painted.
root_view->PaintFromPaintRoot(
ui::PaintContext(ui::PaintContext(list.get(), 1.f, paint_area, false),
ui::PaintContext::CLONE_WITHOUT_INVALIDATION));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintContainsChildren) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(25, 26);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintContainsChildrenInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Verify where the layers actually appear.
v1->SetPaintToLayer();
// x: 25 - 10(x) - 12(width) = 3
EXPECT_EQ(gfx::Rect(3, 11, 12, 13), v1->layer()->bounds());
v1->DestroyLayer();
v2->SetPaintToLayer();
// x: 25 - 10(parent x) - 3(x) - 6(width) = 6
EXPECT_EQ(gfx::Rect(6, 15, 6, 5), v2->layer()->bounds());
v2->DestroyLayer();
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(25, 26);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsChildren) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(9, 10, 5, 6);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsChildrenInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Verify where the layers actually appear.
v1->SetPaintToLayer();
// x: 25 - 10(x) - 12(width) = 3
EXPECT_EQ(gfx::Rect(3, 11, 12, 13), v1->layer()->bounds());
v1->DestroyLayer();
v2->SetPaintToLayer();
// x: 25 - 10(parent x) - 3(x) - 6(width) = 6
EXPECT_EQ(gfx::Rect(6, 15, 6, 5), v2->layer()->bounds());
v2->DestroyLayer();
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(2, 10, 5, 6);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsChildButNotGrandChild) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(9, 10, 2, 3);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsChildButNotGrandChildInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Verify where the layers actually appear.
v1->SetPaintToLayer();
// x: 25 - 10(x) - 12(width) = 3
EXPECT_EQ(gfx::Rect(3, 11, 12, 13), v1->layer()->bounds());
v1->DestroyLayer();
v2->SetPaintToLayer();
// x: 25 - 10(parent x) - 3(x) - 6(width) = 6
EXPECT_EQ(gfx::Rect(6, 15, 6, 5), v2->layer()->bounds());
v2->DestroyLayer();
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(2, 10, 2, 3);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsNoChildren) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(9, 10, 2, 1);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsNoChildrenInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
// Verify where the layers actually appear.
v1->SetPaintToLayer();
// x: 25 - 10(x) - 12(width) = 3
EXPECT_EQ(gfx::Rect(3, 11, 12, 13), v1->layer()->bounds());
v1->DestroyLayer();
v2->SetPaintToLayer();
// x: 25 - 10(parent x) - 3(x) - 6(width) = 6
EXPECT_EQ(gfx::Rect(6, 15, 6, 5), v2->layer()->bounds());
v2->DestroyLayer();
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
gfx::Rect paint_area(2, 10, 2, 1);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsOneChild) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
root_view->AddChildView(v2);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
// Intersects with the second child only.
gfx::Rect paint_area(3, 3, 1, 2);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_FALSE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
// Intersects with the first child only.
paint_area = gfx::Rect(20, 10, 1, 2);
v1->Reset();
v2->Reset();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
TEST_F(ViewTest, PaintIntersectsOneChildInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
root_view->AddChildView(v2);
// Verify where the layers actually appear.
v1->SetPaintToLayer();
// x: 25 - 10(x) - 12(width) = 3
EXPECT_EQ(gfx::Rect(3, 11, 12, 13), v1->layer()->bounds());
v1->DestroyLayer();
v2->SetPaintToLayer();
// x: 25 - 3(x) - 6(width) = 16
EXPECT_EQ(gfx::Rect(16, 4, 6, 5), v2->layer()->bounds());
v2->DestroyLayer();
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
// Intersects with the first child only.
gfx::Rect paint_area(3, 10, 1, 2);
gfx::Rect root_area(root_view->size());
list = base::MakeRefCounted<cc::DisplayItemList>();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
// Intersects with the second child only.
paint_area = gfx::Rect(21, 3, 1, 2);
v1->Reset();
v2->Reset();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), root_view->size()));
EXPECT_FALSE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
TEST_F(ViewTest, PaintInPromotedToLayer) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = new TestView;
v1->SetPaintToLayer();
v1->SetBounds(10, 11, 12, 13);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(3, 4, 6, 5);
v1->AddChildView(v2);
{
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
v1->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false), v1->size()));
v1->Reset();
v2->Reset();
}
{
gfx::Rect paint_area(25, 26);
gfx::Rect view_area(root_view->size());
auto list = base::MakeRefCounted<cc::DisplayItemList>();
// The promoted views are not painted as they are separate paint roots.
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false),
root_view->size()));
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
{
gfx::Rect paint_area(1, 1);
gfx::Rect view_area(v1->size());
auto list = base::MakeRefCounted<cc::DisplayItemList>();
// The |v1| view is painted. If it used its offset incorrect, it would think
// its at (10,11) instead of at (0,0) since it is the paint root.
v1->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), v1->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
}
v1->Reset();
{
gfx::Rect paint_area(3, 3, 1, 2);
gfx::Rect view_area(v1->size());
auto list = base::MakeRefCounted<cc::DisplayItemList>();
// The |v2| view is painted also. If it used its offset incorrect, it would
// think its at (13,15) instead of at (3,4) since |v1| is the paint root.
v1->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), v1->size()));
EXPECT_TRUE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
}
}
// A derived class for testing paint.
class TestPaintView : public TestView {
public:
TestPaintView() = default;
~TestPaintView() override = default;
void OnPaint(gfx::Canvas* canvas) override {
did_paint_ = true;
// Get the bounds from the canvas this view paints to.
EXPECT_TRUE(canvas->GetClipBounds(&canvas_bounds_));
}
gfx::Rect canvas_bounds() const { return canvas_bounds_; }
private:
gfx::Rect canvas_bounds_;
};
TEST_F(ViewTest, PaintLocalBounds) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
// Make |root_view|'s bounds larger so |v1|'s visible bounds is not clipped by
// |root_view|.
root_view->SetBounds(0, 0, 200, 200);
TestPaintView* v1 = new TestPaintView;
v1->SetPaintToLayer();
// Set bounds for |v1| such that it has an offset to its parent and only part
// of it is visible. The visible bounds does not intersect with |root_view|'s
// bounds.
v1->SetBounds(0, -1000, 100, 1100);
root_view->AddChildView(v1);
EXPECT_EQ(gfx::Rect(0, 0, 100, 1100), v1->GetLocalBounds());
EXPECT_EQ(gfx::Rect(0, 1000, 100, 100), v1->GetVisibleBounds());
auto list = base::MakeRefCounted<cc::DisplayItemList>();
ui::PaintContext context(list.get(), 1.f, gfx::Rect(), false);
v1->Paint(PaintInfo::CreateRootPaintInfo(context, gfx::Size()));
EXPECT_TRUE(v1->did_paint_);
// Check that the canvas produced by |v1| for paint contains all of |v1|'s
// visible bounds.
EXPECT_TRUE(v1->canvas_bounds().Contains(v1->GetVisibleBounds()));
}
void TestView::OnDidSchedulePaint(const gfx::Rect& rect) {
scheduled_paint_rects_.push_back(rect);
View::OnDidSchedulePaint(rect);
}
namespace {
gfx::Transform RotationCounterclockwise() {
return gfx::Transform::Make270degRotation();
}
gfx::Transform RotationClockwise() {
return gfx::Transform::Make90degRotation();
}
} // namespace
// Tests the correctness of the rect-based targeting algorithm implemented in
// View::GetEventHandlerForRect(). See http://goo.gl/3Jp2BD for a description
// of rect-based targeting.
TEST_F(ViewTest, GetEventHandlerForRect) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// Have this hierarchy of views (the coordinates here are all in
// the root view's coordinate space):
// v1 (0, 0, 100, 100)
// v2 (150, 0, 250, 100)
// v3 (0, 200, 150, 100)
// v31 (10, 210, 80, 80)
// v32 (110, 210, 30, 80)
// v4 (300, 200, 100, 100)
// v41 (310, 210, 80, 80)
// v411 (370, 275, 10, 5)
// v5 (450, 197, 30, 36)
// v51 (450, 200, 30, 30)
// The coordinates used for SetBounds are in parent coordinates.
TestView* v1 = new TestView;
v1->SetBounds(0, 0, 100, 100);
root_view->AddChildView(v1);
TestView* v2 = new TestView;
v2->SetBounds(150, 0, 250, 100);
root_view->AddChildView(v2);
TestView* v3 = new TestView;
v3->SetBounds(0, 200, 150, 100);
root_view->AddChildView(v3);
TestView* v4 = new TestView;
v4->SetBounds(300, 200, 100, 100);
root_view->AddChildView(v4);
TestView* v31 = new TestView;
v31->SetBounds(10, 10, 80, 80);
v3->AddChildView(v31);
TestView* v32 = new TestView;
v32->SetBounds(110, 10, 30, 80);
v3->AddChildView(v32);
TestView* v41 = new TestView;
v41->SetBounds(10, 10, 80, 80);
v4->AddChildView(v41);
TestView* v411 = new TestView;
v411->SetBounds(60, 65, 10, 5);
v41->AddChildView(v411);
TestView* v5 = new TestView;
v5->SetBounds(450, 197, 30, 36);
root_view->AddChildView(v5);
TestView* v51 = new TestView;
v51->SetBounds(0, 3, 30, 30);
v5->AddChildView(v51);
// |touch_rect| does not intersect any descendant view of |root_view|.
gfx::Rect touch_rect(105, 105, 30, 45);
View* result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
// Covers |v1| by at least 60%.
touch_rect.SetRect(15, 15, 100, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = nullptr;
// Intersects |v1| but does not cover it by at least 60%. The center
// of |touch_rect| is within |v1|.
touch_rect.SetRect(50, 50, 5, 10);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = nullptr;
// Intersects |v1| but does not cover it by at least 60%. The center
// of |touch_rect| is not within |v1|.
touch_rect.SetRect(95, 96, 21, 22);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
// Intersects |v1| and |v2|, but only covers |v2| by at least 60%.
touch_rect.SetRect(95, 10, 300, 120);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v2, result_view);
result_view = nullptr;
// Covers both |v1| and |v2| by at least 60%, but the center point
// of |touch_rect| is closer to the center point of |v2|.
touch_rect.SetRect(20, 20, 400, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v2, result_view);
result_view = nullptr;
// Covers both |v1| and |v2| by at least 60%, but the center point
// of |touch_rect| is closer to the center point of |v1|.
touch_rect.SetRect(-700, -15, 1050, 110);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = nullptr;
// A mouse click within |v1| will target |v1|.
touch_rect.SetRect(15, 15, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v1, result_view);
result_view = nullptr;
// Intersects |v3| and |v31| by at least 60% and the center point
// of |touch_rect| is closer to the center point of |v31|.
touch_rect.SetRect(0, 200, 110, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v31, result_view);
result_view = nullptr;
// Intersects |v3| and |v31|, but neither by at least 60%. The
// center point of |touch_rect| lies within |v31|.
touch_rect.SetRect(80, 280, 15, 15);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v31, result_view);
result_view = nullptr;
// Covers |v3|, |v31|, and |v32| all by at least 60%, and the
// center point of |touch_rect| is closest to the center point
// of |v32|.
touch_rect.SetRect(0, 200, 200, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = nullptr;
// Intersects all of |v3|, |v31|, and |v32|, but only covers
// |v31| and |v32| by at least 60%. The center point of
// |touch_rect| is closest to the center point of |v32|.
touch_rect.SetRect(30, 225, 180, 115);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = nullptr;
// A mouse click at the corner of |v3| will target |v3|.
touch_rect.SetRect(0, 200, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v3, result_view);
result_view = nullptr;
// A mouse click within |v32| will target |v32|.
touch_rect.SetRect(112, 211, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = nullptr;
// Covers all of |v4|, |v41|, and |v411| by at least 60%.
// The center point of |touch_rect| is equally close to
// the center points of |v4| and |v41|.
touch_rect.SetRect(310, 210, 80, 80);
result_view = root_view->GetEventHandlerForRect(touch_rect);
// |v411| is the deepest view that is completely contained by |touch_rect|.
EXPECT_EQ(v411, result_view);
result_view = nullptr;
// Intersects all of |v4|, |v41|, and |v411| but only covers
// |v411| by at least 60%.
touch_rect.SetRect(370, 275, 7, 5);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = nullptr;
// Intersects |v4| and |v41| but covers neither by at least 60%.
// The center point of |touch_rect| is equally close to the center
// points of |v4| and |v41|.
touch_rect.SetRect(345, 245, 7, 7);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = nullptr;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v411|.
touch_rect.SetRect(368, 272, 4, 6);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = nullptr;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v41|.
touch_rect.SetRect(365, 270, 7, 7);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = nullptr;
// Intersects all of |v4|, |v41|, and |v411| and covers none of
// them by at least 60%. The center point of |touch_rect| lies
// within |v4|.
touch_rect.SetRect(205, 275, 200, 2);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v4, result_view);
result_view = nullptr;
// Intersects all of |v4|, |v41|, and |v411| but only covers
// |v41| by at least 60%.
touch_rect.SetRect(310, 210, 61, 66);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = nullptr;
// A mouse click within |v411| will target |v411|.
touch_rect.SetRect(372, 275, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v411, result_view);
result_view = nullptr;
// A mouse click within |v41| will target |v41|.
touch_rect.SetRect(350, 215, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v41, result_view);
result_view = nullptr;
// Covers |v3|, |v4|, and all of their descendants by at
// least 60%. The center point of |touch_rect| is closest
// to the center point of |v32|.
touch_rect.SetRect(0, 200, 400, 100);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v32, result_view);
result_view = nullptr;
// Intersects all of |v2|, |v3|, |v32|, |v4|, |v41|, and |v411|.
// Covers |v2|, |v32|, |v4|, |v41|, and |v411| by at least 60%.
touch_rect.SetRect(110, 15, 375, 450);
result_view = root_view->GetEventHandlerForRect(touch_rect);
// Target is |v411| as it is the deepest view touched by at least 60% of the
// rect.
EXPECT_EQ(v411, result_view);
result_view = nullptr;
// Covers all views (except |v5| and |v51|) by at least 60%. The
// center point of |touch_rect| is equally close to the center
// points of |v2| and |v32|.
touch_rect.SetRect(0, 0, 400, 300);
result_view = root_view->GetEventHandlerForRect(touch_rect);
// |v32| is the deepest view that is contained by the rest.
EXPECT_EQ(v32, result_view);
result_view = nullptr;
// Covers |v5| and |v51| by at least 60%, and the center point of
// the touch is located within both views. Since both views share
// the same center point, the child view should be selected.
touch_rect.SetRect(440, 190, 40, 40);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = nullptr;
// Covers |v5| and |v51| by at least 60%, but the center point of
// the touch is not located within either view. Since both views
// share the same center point, the child view should be selected.
touch_rect.SetRect(455, 187, 60, 60);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = nullptr;
// Covers neither |v5| nor |v51| by at least 60%, but the center
// of the touch is located within |v51|.
touch_rect.SetRect(450, 197, 10, 10);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = nullptr;
// Covers neither |v5| nor |v51| by at least 60% but intersects both.
// The center point is located outside of both views.
touch_rect.SetRect(433, 180, 24, 24);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
// Only intersects |v5| but does not cover it by at least 60%. The
// center point of the touch region is located within |v5|.
touch_rect.SetRect(449, 196, 3, 3);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v5, result_view);
result_view = nullptr;
// A mouse click within |v5| (but not |v51|) should target |v5|.
touch_rect.SetRect(462, 199, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v5, result_view);
result_view = nullptr;
// A mouse click |v5| and |v51| should target the child view.
touch_rect.SetRect(452, 226, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = nullptr;
// A mouse click on the center of |v5| and |v51| should target
// the child view.
touch_rect.SetRect(465, 215, 1, 1);
result_view = root_view->GetEventHandlerForRect(touch_rect);
EXPECT_EQ(v51, result_view);
result_view = nullptr;
widget->CloseNow();
}
// Tests that GetEventHandlerForRect() and GetTooltipHandlerForPoint() behave
// as expected when different views in the view hierarchy return false
// when GetCanProcessEventsWithinSubtree() is called.
TEST_F(ViewTest, GetCanProcessEventsWithinSubtree) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// Have this hierarchy of views (the coords here are in the coordinate
// space of the root view):
// v (0, 0, 100, 100)
// - v_child (0, 0, 20, 30)
// - v_grandchild (5, 5, 5, 15)
TestView* v = new TestView;
v->SetBounds(0, 0, 100, 100);
root_view->AddChildView(v);
v->SetNotifyEnterExitOnChild(true);
TestView* v_child = new TestView;
v_child->SetBounds(0, 0, 20, 30);
v->AddChildView(v_child);
TestView* v_grandchild = new TestView;
v_grandchild->SetBounds(5, 5, 5, 15);
v_child->AddChildView(v_grandchild);
v->Reset();
v_child->Reset();
v_grandchild->Reset();
// Define rects and points within the views in the hierarchy.
gfx::Rect rect_in_v_grandchild(7, 7, 3, 3);
gfx::Point point_in_v_grandchild(rect_in_v_grandchild.origin());
gfx::Rect rect_in_v_child(12, 3, 5, 5);
gfx::Point point_in_v_child(rect_in_v_child.origin());
gfx::Rect rect_in_v(50, 50, 25, 30);
gfx::Point point_in_v(rect_in_v.origin());
// When all three views return true when GetCanProcessEventsWithinSubtree()
// is called, targeting should behave as expected.
View* result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild);
EXPECT_EQ(v_grandchild, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild);
EXPECT_EQ(v_grandchild, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v_child);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v);
EXPECT_EQ(v, result_view);
result_view = nullptr;
// When |v_grandchild| returns false when GetCanProcessEventsWithinSubtree()
// is called, then |v_grandchild| cannot be returned as a target.
v_grandchild->SetCanProcessEventsWithinSubtree(false);
result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v_child);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child);
EXPECT_EQ(v_child, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v);
EXPECT_EQ(v, result_view);
// When |v_grandchild| returns false when GetCanProcessEventsWithinSubtree()
// is called, then NULL should be returned as a target if we call
// GetTooltipHandlerForPoint() with |v_grandchild| as the root of the
// views tree. Note that the location must be in the coordinate space
// of the root view (|v_grandchild| in this case), so use (1, 1).
result_view = v_grandchild;
result_view = v_grandchild->GetTooltipHandlerForPoint(gfx::Point(1, 1));
EXPECT_EQ(nullptr, result_view);
result_view = nullptr;
// When |v_child| returns false when GetCanProcessEventsWithinSubtree()
// is called, then neither |v_child| nor |v_grandchild| can be returned
// as a target (|v| should be returned as the target for each case).
v_grandchild->Reset();
v_child->SetCanProcessEventsWithinSubtree(false);
result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v_child);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v);
EXPECT_EQ(v, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v);
EXPECT_EQ(v, result_view);
result_view = nullptr;
// When |v| returns false when GetCanProcessEventsWithinSubtree()
// is called, then none of |v|, |v_child|, and |v_grandchild| can be returned
// as a target (|root_view| should be returned as the target for each case).
v_child->Reset();
v->SetCanProcessEventsWithinSubtree(false);
result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v_child);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
result_view = root_view->GetEventHandlerForRect(rect_in_v);
EXPECT_EQ(root_view, result_view);
result_view = nullptr;
result_view = root_view->GetTooltipHandlerForPoint(point_in_v);
EXPECT_EQ(root_view, result_view);
widget->CloseNow();
}
TEST_F(ViewTest, NotifyEnterExitOnChild) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
// Have this hierarchy of views (the coords here are in root coord):
// v1 (0, 0, 100, 100)
// - v11 (0, 0, 20, 30)
// - v111 (5, 5, 5, 15)
// - v12 (50, 10, 30, 90)
// - v121 (60, 20, 10, 10)
// v2 (105, 0, 100, 100)
// - v21 (120, 10, 50, 20)
TestView* v1 = new TestView;
v1->SetBounds(0, 0, 100, 100);
root_view->AddChildView(v1);
v1->SetNotifyEnterExitOnChild(true);
TestView* v11 = new TestView;
v11->SetBounds(0, 0, 20, 30);
v1->AddChildView(v11);
TestView* v111 = new TestView;
v111->SetBounds(5, 5, 5, 15);
v11->AddChildView(v111);
TestView* v12 = new TestView;
v12->SetBounds(50, 10, 30, 90);
v1->AddChildView(v12);
TestView* v121 = new TestView;
v121->SetBounds(10, 10, 10, 10);
v12->AddChildView(v121);
TestView* v2 = new TestView;
v2->SetBounds(105, 0, 100, 100);
root_view->AddChildView(v2);
TestView* v21 = new TestView;
v21->SetBounds(15, 10, 50, 20);
v2->AddChildView(v21);
v1->Reset();
v11->Reset();
v111->Reset();
v12->Reset();
v121->Reset();
v2->Reset();
v21->Reset();
// Move the mouse in v111.
gfx::Point p1(6, 6);
ui::MouseEvent move1(ui::ET_MOUSE_MOVED, p1, p1, ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move1);
EXPECT_TRUE(v111->received_mouse_enter_);
EXPECT_FALSE(v11->last_mouse_event_type_);
EXPECT_TRUE(v1->received_mouse_enter_);
v111->Reset();
v1->Reset();
// Now, move into v121.
gfx::Point p2(65, 21);
ui::MouseEvent move2(ui::ET_MOUSE_MOVED, p2, p2, ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move2);
EXPECT_TRUE(v111->received_mouse_exit_);
EXPECT_TRUE(v121->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v111->Reset();
v121->Reset();
// Now, move into v11.
gfx::Point p3(1, 1);
ui::MouseEvent move3(ui::ET_MOUSE_MOVED, p3, p3, ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move3);
EXPECT_TRUE(v121->received_mouse_exit_);
EXPECT_TRUE(v11->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v121->Reset();
v11->Reset();
// Move to v21.
gfx::Point p4(121, 15);
ui::MouseEvent move4(ui::ET_MOUSE_MOVED, p4, p4, ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move4);
EXPECT_TRUE(v21->received_mouse_enter_);
EXPECT_FALSE(v2->last_mouse_event_type_);
EXPECT_TRUE(v11->received_mouse_exit_);
EXPECT_TRUE(v1->received_mouse_exit_);
v21->Reset();
v11->Reset();
v1->Reset();
// Move to v1.
gfx::Point p5(21, 0);
ui::MouseEvent move5(ui::ET_MOUSE_MOVED, p5, p5, ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move5);
EXPECT_TRUE(v21->received_mouse_exit_);
EXPECT_TRUE(v1->received_mouse_enter_);
v21->Reset();
v1->Reset();
// Now, move into v11.
gfx::Point p6(15, 15);
ui::MouseEvent mouse6(ui::ET_MOUSE_MOVED, p6, p6, ui::EventTimeForNow(), 0,
0);
root_view->OnMouseMoved(mouse6);
EXPECT_TRUE(v11->received_mouse_enter_);
EXPECT_FALSE(v1->last_mouse_event_type_);
v11->Reset();
v1->Reset();
// Move back into v1. Although |v1| had already received an ENTER for mouse6,
// and the mouse remains inside |v1| the whole time, it receives another ENTER
// when the mouse leaves v11.
gfx::Point p7(21, 0);
ui::MouseEvent mouse7(ui::ET_MOUSE_MOVED, p7, p7, ui::EventTimeForNow(), 0,
0);
root_view->OnMouseMoved(mouse7);
EXPECT_TRUE(v11->received_mouse_exit_);
EXPECT_FALSE(v1->received_mouse_enter_);
widget->CloseNow();
}
TEST_F(ViewTest, Textfield) {
const std::u16string kText =
u"Reality is that which, when you stop believing it, doesn't go away.";
const std::u16string kExtraText = u"Pretty deep, Philip!";
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
Textfield* textfield = new Textfield();
root_view->AddChildView(textfield);
// Test setting, appending text.
textfield->SetText(kText);
EXPECT_EQ(kText, textfield->GetText());
textfield->AppendText(kExtraText);
EXPECT_EQ(kText + kExtraText, textfield->GetText());
textfield->SetText(std::u16string());
EXPECT_TRUE(textfield->GetText().empty());
// Test selection related methods.
textfield->SetText(kText);
EXPECT_TRUE(textfield->GetSelectedText().empty());
textfield->SelectAll(false);
EXPECT_EQ(kText, textfield->GetText());
textfield->ClearSelection();
EXPECT_TRUE(textfield->GetSelectedText().empty());
widget->CloseNow();
}
// Tests that the Textfield view respond appropiately to cut/copy/paste.
TEST_F(ViewTest, TextfieldCutCopyPaste) {
const std::u16string kNormalText = u"Normal";
const std::u16string kReadOnlyText = u"Read only";
const std::u16string kPasswordText = u"Password! ** Secret stuff **";
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 100, 100);
widget->Init(std::move(params));
View* root_view = widget->GetRootView();
Textfield* normal = new Textfield();
Textfield* read_only = new Textfield();
read_only->SetReadOnly(true);
Textfield* password = new Textfield();
password->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
root_view->AddChildView(normal);
root_view->AddChildView(read_only);
root_view->AddChildView(password);
normal->SetText(kNormalText);
read_only->SetText(kReadOnlyText);
password->SetText(kPasswordText);
//
// Test cut.
//
normal->SelectAll(false);
normal->ExecuteCommand(Textfield::kCut, 0);
std::u16string result;
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
EXPECT_EQ(kNormalText, result);
normal->SetText(kNormalText); // Let's revert to the original content.
read_only->SelectAll(false);
read_only->ExecuteCommand(Textfield::kCut, 0);
result.clear();
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
// Cut should have failed, so the clipboard content should not have changed.
EXPECT_EQ(kNormalText, result);
password->SelectAll(false);
password->ExecuteCommand(Textfield::kCut, 0);
result.clear();
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
// Cut should have failed, so the clipboard content should not have changed.
EXPECT_EQ(kNormalText, result);
//
// Test copy.
//
// Start with |read_only| to observe a change in clipboard text.
read_only->SelectAll(false);
read_only->ExecuteCommand(Textfield::kCopy, 0);
result.clear();
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
EXPECT_EQ(kReadOnlyText, result);
normal->SelectAll(false);
normal->ExecuteCommand(Textfield::kCopy, 0);
result.clear();
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
EXPECT_EQ(kNormalText, result);
password->SelectAll(false);
password->ExecuteCommand(Textfield::kCopy, 0);
result.clear();
clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr,
&result);
// Text cannot be copied from an obscured field; the clipboard won't change.
EXPECT_EQ(kNormalText, result);
//
// Test paste.
//
// Attempting to paste kNormalText in a read-only text-field should fail.
read_only->SelectAll(false);
read_only->ExecuteCommand(Textfield::kPaste, 0);
EXPECT_EQ(kReadOnlyText, read_only->GetText());
password->SelectAll(false);
password->ExecuteCommand(Textfield::kPaste, 0);
EXPECT_EQ(kNormalText, password->GetText());
// Copy from |read_only| to observe a change in the normal textfield text.
read_only->SelectAll(false);
read_only->ExecuteCommand(Textfield::kCopy, 0);
normal->SelectAll(false);
normal->ExecuteCommand(Textfield::kPaste, 0);
EXPECT_EQ(kReadOnlyText, normal->GetText());
widget->CloseNow();
}
class ViewPaintOptimizationTest : public ViewsTestBase {
public:
ViewPaintOptimizationTest() = default;
ViewPaintOptimizationTest(const ViewPaintOptimizationTest&) = delete;
ViewPaintOptimizationTest& operator=(const ViewPaintOptimizationTest&) =
delete;
~ViewPaintOptimizationTest() override = default;
void SetUp() override {
scoped_feature_list_.InitAndEnableFeature(
views::features::kEnableViewPaintOptimization);
ViewTest::SetUp();
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Tests that only Views where SchedulePaint was invoked get repainted.
TEST_F(ViewPaintOptimizationTest, PaintDirtyViewsOnly) {
ScopedTestPaintWidget widget(CreateParams(Widget::InitParams::TYPE_POPUP));
View* root_view = widget->GetRootView();
TestView* v1 = root_view->AddChildView(std::make_unique<TestView>());
v1->SetBounds(10, 11, 12, 13);
TestView* v2 = root_view->AddChildView(std::make_unique<TestView>());
v2->SetBounds(3, 4, 6, 5);
TestView* v21 = v2->AddChildView(std::make_unique<TestView>());
v21->SetBounds(2, 3, 4, 5);
// Paint everything once, since it has to build its cache. Then we can test
// invalidation.
gfx::Rect first_paint(1, 1);
auto list = base::MakeRefCounted<cc::DisplayItemList>();
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, first_paint, false),
root_view->size()));
v1->Reset();
v2->Reset();
v21->Reset();
gfx::Rect paint_area(10, 11, 12, 13);
list = base::MakeRefCounted<cc::DisplayItemList>();
// Schedule a paint on v2 which marks it invalidated.
v2->SchedulePaint();
EXPECT_FALSE(v1->did_paint_);
EXPECT_FALSE(v2->did_paint_);
EXPECT_FALSE(v21->did_paint_);
// Paint with an unknown invalidation. The invalidation is irrelevant since
// repainting a view only depends on whether the view had a scheduled paint.
gfx::Rect empty_rect;
EXPECT_TRUE(empty_rect.IsEmpty());
root_view->Paint(PaintInfo::CreateRootPaintInfo(
ui::PaintContext(list.get(), 1.f, paint_area, false), empty_rect.size()));
// Only v2 should be repainted.
EXPECT_FALSE(v1->did_paint_);
EXPECT_TRUE(v2->did_paint_);
EXPECT_FALSE(v21->did_paint_);
}
////////////////////////////////////////////////////////////////////////////////
// Accelerators
////////////////////////////////////////////////////////////////////////////////
bool TestView::AcceleratorPressed(const ui::Accelerator& accelerator) {
accelerator_count_map_[accelerator]++;
return true;
}
namespace {
// A Widget with a TestView in the view hierarchy. Used for accelerator tests.
class TestViewWidget {
public:
TestViewWidget(Widget::InitParams create_params,
ui::Accelerator* initial_accelerator,
bool show_after_init = true) {
auto view = std::make_unique<TestView>();
view->Reset();
// Register a keyboard accelerator before the view is added to a window.
if (initial_accelerator) {
view->AddAccelerator(*initial_accelerator);
EXPECT_EQ(view->accelerator_count_map_[*initial_accelerator], 0);
}
widget_ = std::make_unique<Widget>();
// Create a window and add the view as its child.
Widget::InitParams params = std::move(create_params);
params.bounds = gfx::Rect(0, 0, 100, 100);
widget_->Init(std::move(params));
View* root = widget_->GetRootView();
view_ = root->AddChildView(std::move(view));
if (show_after_init)
widget_->Show();
EXPECT_TRUE(widget_->GetFocusManager());
}
TestViewWidget(const TestViewWidget&) = delete;
TestViewWidget& operator=(const TestViewWidget&) = delete;
TestView* view() { return view_; }
Widget* widget() { return widget_.get(); }
private:
raw_ptr<TestView> view_;
UniqueWidgetPtr widget_;
};
} // namespace
// On non-ChromeOS aura there is extra logic to determine whether a view should
// handle accelerators or not (see View::CanHandleAccelerators for details).
// This test targets that extra logic, but should also work on other platforms.
TEST_F(ViewTest, HandleAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestViewWidget test_widget(CreateParams(Widget::InitParams::TYPE_POPUP),
&return_accelerator);
TestView* view = test_widget.view();
Widget* widget = test_widget.widget();
FocusManager* focus_manager = widget->GetFocusManager();
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// When a non-child view is not active, it shouldn't handle accelerators.
EXPECT_FALSE(widget->IsActive());
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(0, view->accelerator_count_map_[return_accelerator]);
#endif
// TYPE_POPUP widgets default to non-activatable, so the Show() above wouldn't
// have activated the Widget. First, allow activation.
widget->widget_delegate()->SetCanActivate(true);
// When a non-child view is active, it should handle accelerators.
view->accelerator_count_map_[return_accelerator] = 0;
widget->Activate();
EXPECT_TRUE(widget->IsActive());
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
// Add a child view associated with a child widget.
Widget* child_widget = new Widget;
Widget::InitParams child_params =
CreateParams(Widget::InitParams::TYPE_CONTROL);
child_params.parent = widget->GetNativeView();
child_widget->Init(std::move(child_params));
TestView* child_view =
child_widget->SetContentsView(std::make_unique<TestView>());
child_view->Reset();
child_view->AddAccelerator(return_accelerator);
EXPECT_EQ(child_view->accelerator_count_map_[return_accelerator], 0);
FocusManager* child_focus_manager = child_widget->GetFocusManager();
ASSERT_TRUE(child_focus_manager);
// When a child view is in focus, it should handle accelerators.
child_view->accelerator_count_map_[return_accelerator] = 0;
view->accelerator_count_map_[return_accelerator] = 0;
child_focus_manager->SetFocusedView(child_view);
EXPECT_FALSE(child_view->GetWidget()->IsActive());
EXPECT_TRUE(child_focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, child_view->accelerator_count_map_[return_accelerator]);
EXPECT_EQ(0, view->accelerator_count_map_[return_accelerator]);
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// When a child view is not in focus, its parent should handle accelerators.
child_view->accelerator_count_map_[return_accelerator] = 0;
view->accelerator_count_map_[return_accelerator] = 0;
child_focus_manager->ClearFocus();
EXPECT_FALSE(child_view->GetWidget()->IsActive());
EXPECT_TRUE(child_focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(0, child_view->accelerator_count_map_[return_accelerator]);
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
#endif
}
// TODO(themblsha): Bring this up on non-Mac platforms. It currently fails
// because TestView::AcceleratorPressed() is not called. See
// http://crbug.com/667757.
#if BUILDFLAG(IS_MAC)
// Test that BridgedContentView correctly handles Accelerator key events when
// subject to OS event dispatch.
TEST_F(ViewTest, ActivateAcceleratorOnMac) {
// Cmd+1 translates to "noop:" command by interpretKeyEvents.
ui::Accelerator command_accelerator(ui::VKEY_1, ui::EF_COMMAND_DOWN);
TestViewWidget test_widget(CreateParams(Widget::InitParams::TYPE_POPUP),
&command_accelerator);
TestView* view = test_widget.view();
ui::test::EventGenerator event_generator(
test_widget.widget()->GetNativeWindow());
// Emulate normal event dispatch through -[NSWindow sendEvent:].
event_generator.set_target(ui::test::EventGenerator::Target::WINDOW);
event_generator.PressKey(command_accelerator.key_code(),
command_accelerator.modifiers());
event_generator.ReleaseKey(command_accelerator.key_code(),
command_accelerator.modifiers());
EXPECT_EQ(view->accelerator_count_map_[command_accelerator], 1);
// Without an _wantsKeyDownForEvent: override we'll only get a keyUp: event
// for this accelerator.
ui::Accelerator key_up_accelerator(ui::VKEY_TAB,
ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
view->AddAccelerator(key_up_accelerator);
event_generator.PressKey(key_up_accelerator.key_code(),
key_up_accelerator.modifiers());
event_generator.ReleaseKey(key_up_accelerator.key_code(),
key_up_accelerator.modifiers());
EXPECT_EQ(view->accelerator_count_map_[key_up_accelerator], 1);
// We should handle this accelerator inside keyDown: as it doesn't translate
// to any command by default.
ui::Accelerator key_down_accelerator(
ui::VKEY_L, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | ui::EF_SHIFT_DOWN);
view->AddAccelerator(key_down_accelerator);
event_generator.PressKey(key_down_accelerator.key_code(),
key_down_accelerator.modifiers());
event_generator.ReleaseKey(key_down_accelerator.key_code(),
key_down_accelerator.modifiers());
EXPECT_EQ(view->accelerator_count_map_[key_down_accelerator], 1);
}
#endif // BUILDFLAG(IS_MAC)
// TODO(crbug.com/667757): these tests were initially commented out when getting
// aura to run. Figure out if still valuable and either nuke or fix.
#if BUILDFLAG(IS_MAC)
TEST_F(ViewTest, ActivateAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestViewWidget test_widget(CreateParams(Widget::InitParams::TYPE_POPUP),
&return_accelerator);
TestView* view = test_widget.view();
FocusManager* focus_manager = test_widget.widget()->GetFocusManager();
// Hit the return key and see if it takes effect.
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
// Hit the escape key. Nothing should happen.
ui::Accelerator escape_accelerator(ui::VKEY_ESCAPE, ui::EF_NONE);
EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 0);
// Now register the escape key and hit it again.
view->AddAccelerator(escape_accelerator);
EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
// Remove the return key accelerator.
view->RemoveAccelerator(return_accelerator);
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
// Add it again. Hit the return key and the escape key.
view->AddAccelerator(return_accelerator);
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1);
EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
// Remove all the accelerators.
view->ResetAccelerators();
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator));
EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2);
EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2);
}
TEST_F(ViewTest, HiddenViewWithAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestViewWidget test_widget(CreateParams(Widget::InitParams::TYPE_POPUP),
&return_accelerator);
TestView* view = test_widget.view();
FocusManager* focus_manager = test_widget.widget()->GetFocusManager();
view->SetVisible(false);
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
view->SetVisible(true);
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
}
TEST_F(ViewTest, ViewInHiddenWidgetWithAccelerator) {
ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE);
TestViewWidget test_widget(CreateParams(Widget::InitParams::TYPE_POPUP),
&return_accelerator, false);
TestView* view = test_widget.view();
Widget* widget = test_widget.widget();
FocusManager* focus_manager = test_widget.widget()->GetFocusManager();
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(0, view->accelerator_count_map_[return_accelerator]);
widget->Show();
EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
widget->Hide();
EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator));
EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]);
}
#endif // BUILDFLAG(IS_MAC)
////////////////////////////////////////////////////////////////////////////////
// Native view hierachy
////////////////////////////////////////////////////////////////////////////////
class ToplevelWidgetObserverView : public View {
public:
ToplevelWidgetObserverView() = default;
ToplevelWidgetObserverView(const ToplevelWidgetObserverView&) = delete;
ToplevelWidgetObserverView& operator=(const ToplevelWidgetObserverView&) =
delete;
~ToplevelWidgetObserverView() override = default;
// View overrides:
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override {
if (details.is_add) {
toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : nullptr;
} else {
toplevel_ = nullptr;
}
}
void NativeViewHierarchyChanged() override {
toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : nullptr;
}
Widget* toplevel() { return toplevel_; }
private:
raw_ptr<Widget> toplevel_ = nullptr;
};
// Test that
// a) a view can track the current top level widget by overriding
// View::ViewHierarchyChanged() and View::NativeViewHierarchyChanged().
// b) a widget has the correct parent after reparenting.
TEST_F(ViewTest, NativeViewHierarchyChanged) {
UniqueWidgetPtr toplevel1 = std::make_unique<Widget>();
Widget::InitParams toplevel1_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
toplevel1->Init(std::move(toplevel1_params));
UniqueWidgetPtr toplevel2 = std::make_unique<Widget>();
Widget::InitParams toplevel2_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
toplevel2->Init(std::move(toplevel2_params));
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child_params.parent = toplevel1->GetNativeView();
child->Init(std::move(child_params));
EXPECT_EQ(toplevel1.get(), child->parent());
auto owning_observer_view = std::make_unique<ToplevelWidgetObserverView>();
EXPECT_EQ(nullptr, owning_observer_view->toplevel());
ToplevelWidgetObserverView* observer_view =
child->SetContentsView(std::move(owning_observer_view));
EXPECT_EQ(toplevel1.get(), observer_view->toplevel());
Widget::ReparentNativeView(child->GetNativeView(),
toplevel2->GetNativeView());
EXPECT_EQ(toplevel2.get(), observer_view->toplevel());
EXPECT_EQ(toplevel2.get(), child->parent());
owning_observer_view =
observer_view->parent()->RemoveChildViewT(observer_view);
EXPECT_EQ(nullptr, observer_view->toplevel());
// Make |observer_view| |child|'s contents view again so that it gets deleted
// with the widget.
child->SetContentsView(std::move(owning_observer_view));
}
////////////////////////////////////////////////////////////////////////////////
// Transformations
////////////////////////////////////////////////////////////////////////////////
class TransformPaintView : public TestView {
public:
TransformPaintView() = default;
TransformPaintView(const TransformPaintView&) = delete;
TransformPaintView& operator=(const TransformPaintView&) = delete;
~TransformPaintView() override = default;
void ClearScheduledPaintRect() { scheduled_paint_rect_ = gfx::Rect(); }
gfx::Rect scheduled_paint_rect() const { return scheduled_paint_rect_; }
// Overridden from View:
void OnDidSchedulePaint(const gfx::Rect& rect) override {
gfx::Rect xrect = ConvertRectToParent(rect);
scheduled_paint_rect_.Union(xrect);
}
private:
gfx::Rect scheduled_paint_rect_;
};
TEST_F(ViewTest, TransformPaint) {
auto view1 = std::make_unique<TransformPaintView>();
view1->SetBoundsRect(gfx::Rect(0, 0, 500, 300));
auto view2 = std::make_unique<TestView>();
view2->SetBoundsRect(gfx::Rect(100, 100, 200, 100));
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
widget->Show();
View* root = widget->GetRootView();
TransformPaintView* v1 = root->AddChildView(std::move(view1));
TestView* v2 = v1->AddChildView(std::move(view2));
// At this moment, |v2| occupies (100, 100) to (300, 200) in |root|.
v1->ClearScheduledPaintRect();
v2->SchedulePaint();
EXPECT_EQ(gfx::Rect(100, 100, 200, 100), v1->scheduled_paint_rect());
// Rotate |v1| counter-clockwise.
gfx::Transform transform = RotationCounterclockwise();
transform.set_rc(1, 3, 500.0);
v1->SetTransform(transform);
// |v2| now occupies (100, 200) to (200, 400) in |root|.
v1->ClearScheduledPaintRect();
v2->SchedulePaint();
EXPECT_EQ(gfx::Rect(100, 200, 100, 200), v1->scheduled_paint_rect());
}
TEST_F(ViewTest, TransformEvent) {
auto view1 = std::make_unique<TestView>();
view1->SetBoundsRect(gfx::Rect(0, 0, 500, 300));
auto view2 = std::make_unique<TestView>();
view2->SetBoundsRect(gfx::Rect(100, 100, 200, 100));
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
TestView* v1 = root->AddChildView(std::move(view1));
TestView* v2 = v1->AddChildView(std::move(view2));
// At this moment, |v2| occupies (100, 100) to (300, 200) in |root|.
// Rotate |v1| counter-clockwise.
gfx::Transform transform = RotationCounterclockwise();
transform.set_rc(1, 3, 500.0);
v1->SetTransform(transform);
// |v2| now occupies (100, 200) to (200, 400) in |root|.
v1->Reset();
v2->Reset();
gfx::Point p1(110, 210);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
EXPECT_EQ(0, v1->last_mouse_event_type_);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_);
EXPECT_EQ(190, v2->location_.x());
EXPECT_EQ(10, v2->location_.y());
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
root->OnMouseReleased(released);
// Now rotate |v2| inside |v1| clockwise.
transform = RotationClockwise();
transform.set_rc(0, 3, 100.f);
v2->SetTransform(transform);
// Now, |v2| occupies (100, 100) to (200, 300) in |v1|, and (100, 300) to
// (300, 400) in |root|.
v1->Reset();
v2->Reset();
gfx::Point point2(110, 320);
ui::MouseEvent p2(ui::ET_MOUSE_PRESSED, point2, point2, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p2);
EXPECT_EQ(0, v1->last_mouse_event_type_);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_);
EXPECT_EQ(10, v2->location_.x());
EXPECT_EQ(20, v2->location_.y());
root->OnMouseReleased(released);
v1->SetTransform(gfx::Transform());
v2->SetTransform(gfx::Transform());
auto view3 = std::make_unique<TestView>();
view3->SetBoundsRect(gfx::Rect(10, 10, 20, 30));
TestView* v3 = v2->AddChildView(std::move(view3));
// Rotate |v3| clockwise with respect to |v2|.
transform = RotationClockwise();
transform.set_rc(0, 3, 30.f);
v3->SetTransform(transform);
// Scale |v2| with respect to |v1| along both axis.
transform = v2->GetTransform();
transform.set_rc(0, 0, 0.8f);
transform.set_rc(1, 1, 0.5f);
v2->SetTransform(transform);
// |v3| occupies (108, 105) to (132, 115) in |root|.
v1->Reset();
v2->Reset();
v3->Reset();
gfx::Point point(112, 110);
ui::MouseEvent p3(ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p3);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_);
EXPECT_EQ(10, v3->location_.x());
EXPECT_EQ(25, v3->location_.y());
root->OnMouseReleased(released);
v1->SetTransform(gfx::Transform());
v2->SetTransform(gfx::Transform());
v3->SetTransform(gfx::Transform());
v1->Reset();
v2->Reset();
v3->Reset();
// Rotate |v3| clockwise with respect to |v2|, and scale it along both axis.
transform = RotationClockwise();
transform.set_rc(0, 3, 30.f);
// Rotation sets some scaling transformation. Using SetScale would overwrite
// that and pollute the rotation. So combine the scaling with the existing
// transforamtion.
gfx::Transform scale;
scale.Scale(0.8f, 0.5f);
transform.PostConcat(scale);
v3->SetTransform(transform);
// Translate |v2| with respect to |v1|.
transform = v2->GetTransform();
transform.set_rc(0, 3, 10.f);
transform.set_rc(1, 3, 10.f);
v2->SetTransform(transform);
// |v3| now occupies (120, 120) to (144, 130) in |root|.
gfx::Point point3(124, 125);
ui::MouseEvent p4(ui::ET_MOUSE_PRESSED, point3, point3, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(p4);
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_);
EXPECT_EQ(10, v3->location_.x());
EXPECT_EQ(25, v3->location_.y());
root->OnMouseReleased(released);
}
TEST_F(ViewTest, TransformVisibleBound) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = viewport_bounds;
widget->Init(std::move(params));
widget->GetRootView()->SetBoundsRect(viewport_bounds);
View* viewport = widget->SetContentsView(std::make_unique<View>());
View* contents = viewport->AddChildView(std::make_unique<View>());
viewport->SetBoundsRect(viewport_bounds);
contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200));
View* child = contents->AddChildView(std::make_unique<View>());
child->SetBoundsRect(gfx::Rect(10, 90, 50, 50));
EXPECT_EQ(gfx::Rect(0, 0, 50, 10), child->GetVisibleBounds());
// Rotate |child| counter-clockwise
gfx::Transform transform = RotationCounterclockwise();
transform.set_rc(1, 3, 50.f);
child->SetTransform(transform);
EXPECT_EQ(gfx::Rect(40, 0, 10, 50), child->GetVisibleBounds());
}
////////////////////////////////////////////////////////////////////////////////
// OnVisibleBoundsChanged()
class VisibleBoundsView : public View {
public:
VisibleBoundsView() = default;
VisibleBoundsView(const VisibleBoundsView&) = delete;
VisibleBoundsView& operator=(const VisibleBoundsView&) = delete;
~VisibleBoundsView() override = default;
bool received_notification() const { return received_notification_; }
void set_received_notification(bool received) {
received_notification_ = received;
}
private:
// Overridden from View:
bool GetNeedsNotificationWhenVisibleBoundsChange() const override {
return true;
}
void OnVisibleBoundsChanged() override { received_notification_ = true; }
bool received_notification_ = false;
};
TEST_F(ViewTest, OnVisibleBoundsChanged) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = viewport_bounds;
widget->Init(std::move(params));
widget->GetRootView()->SetBoundsRect(viewport_bounds);
View* viewport = widget->SetContentsView(std::make_unique<View>());
View* contents = viewport->AddChildView(std::make_unique<View>());
viewport->SetBoundsRect(viewport_bounds);
contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200));
// Create a view that cares about visible bounds notifications, and position
// it just outside the visible bounds of the viewport.
VisibleBoundsView* child =
contents->AddChildView(std::make_unique<VisibleBoundsView>());
child->SetBoundsRect(gfx::Rect(10, 110, 50, 50));
// The child bound should be fully clipped.
EXPECT_TRUE(child->GetVisibleBounds().IsEmpty());
// Now scroll the contents, but not enough to make the child visible.
contents->SetY(contents->y() - 1);
// We should have received the notification since the visible bounds may have
// changed (even though they didn't).
EXPECT_TRUE(child->received_notification());
EXPECT_TRUE(child->GetVisibleBounds().IsEmpty());
child->set_received_notification(false);
// Now scroll the contents, this time by enough to make the child visible by
// one pixel.
contents->SetY(contents->y() - 10);
EXPECT_TRUE(child->received_notification());
EXPECT_EQ(1, child->GetVisibleBounds().height());
child->set_received_notification(false);
}
TEST_F(ViewTest, SetBoundsPaint) {
auto top_view = std::make_unique<TestView>();
auto child = std::make_unique<TestView>();
top_view->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
top_view->scheduled_paint_rects_.clear();
child->SetBoundsRect(gfx::Rect(10, 10, 20, 20));
TestView* child_view = top_view->AddChildView(std::move(child));
top_view->scheduled_paint_rects_.clear();
child_view->SetBoundsRect(gfx::Rect(30, 30, 20, 20));
EXPECT_EQ(2U, top_view->scheduled_paint_rects_.size());
// There should be 2 rects, spanning from (10, 10) to (50, 50).
gfx::Rect paint_rect = top_view->scheduled_paint_rects_[0];
paint_rect.Union(top_view->scheduled_paint_rects_[1]);
EXPECT_EQ(gfx::Rect(10, 10, 40, 40), paint_rect);
}
// Assertions around painting and focus gain/lost.
TEST_F(ViewTest, FocusBlurPaints) {
auto parent_view = std::make_unique<TestView>();
auto child = std::make_unique<TestView>(); // Owned by |parent_view|.
parent_view->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
child->SetBoundsRect(gfx::Rect(0, 0, 20, 20));
TestView* child_view = parent_view->AddChildView(std::move(child));
parent_view->scheduled_paint_rects_.clear();
child_view->scheduled_paint_rects_.clear();
// Focus change shouldn't trigger paints.
child_view->DoFocus();
EXPECT_TRUE(parent_view->scheduled_paint_rects_.empty());
EXPECT_TRUE(child_view->scheduled_paint_rects_.empty());
child_view->DoBlur();
EXPECT_TRUE(parent_view->scheduled_paint_rects_.empty());
EXPECT_TRUE(child_view->scheduled_paint_rects_.empty());
}
// Verifies SetBounds(same bounds) doesn't trigger a SchedulePaint().
TEST_F(ViewTest, SetBoundsSameBoundsDoesntSchedulePaint) {
auto view = std::make_unique<TestView>();
view->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
view->InvalidateLayout();
view->scheduled_paint_rects_.clear();
view->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
EXPECT_TRUE(view->scheduled_paint_rects_.empty());
}
// Verifies AddChildView() and RemoveChildView() schedule appropriate paints.
TEST_F(ViewTest, AddAndRemoveSchedulePaints) {
gfx::Rect viewport_bounds(0, 0, 100, 100);
// We have to put the View hierarchy into a Widget or no paints will be
// scheduled.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = viewport_bounds;
widget->Init(std::move(params));
widget->GetRootView()->SetBoundsRect(viewport_bounds);
TestView* parent_view = widget->SetContentsView(std::make_unique<TestView>());
parent_view->SetBoundsRect(viewport_bounds);
parent_view->scheduled_paint_rects_.clear();
auto owning_child_view = std::make_unique<View>();
owning_child_view->SetBoundsRect(gfx::Rect(0, 0, 20, 20));
View* child_view = parent_view->AddChildView(std::move(owning_child_view));
ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size());
EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front());
parent_view->scheduled_paint_rects_.clear();
parent_view->RemoveChildView(child_view);
std::unique_ptr<View> child_deleter(child_view);
ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size());
EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front());
}
// Tests conversion methods with a transform.
TEST_F(ViewTest, ConversionsWithTransform) {
TestView top_view;
// View hierarchy used to test scale transforms.
TestView* child = new TestView;
TestView* child_child = new TestView;
// View used to test a rotation transform.
TestView* child_2 = new TestView;
constexpr float kDefaultAllowedConversionError = 0.00001f;
{
top_view.AddChildView(child);
child->AddChildView(child_child);
top_view.SetBoundsRect(gfx::Rect(0, 0, 1000, 1000));
child->SetBoundsRect(gfx::Rect(7, 19, 500, 500));
gfx::Transform transform;
transform.Scale(3.0, 4.0);
child->SetTransform(transform);
child_child->SetBoundsRect(gfx::Rect(17, 13, 100, 100));
transform.MakeIdentity();
transform.Scale(5.0, 7.0);
child_child->SetTransform(transform);
top_view.AddChildView(child_2);
child_2->SetBoundsRect(gfx::Rect(700, 725, 100, 100));
transform = RotationClockwise();
child_2->SetTransform(transform);
}
// Sanity check to make sure basic transforms act as expected.
{
gfx::Transform transform;
transform.Translate(110.0, -110.0);
transform.Scale(100.0, 55.0);
transform.Translate(1.0, 1.0);
// convert to a 3x3 matrix.
SkMatrix matrix = gfx::TransformToFlattenedSkMatrix(transform);
EXPECT_EQ(210, matrix.getTranslateX());
EXPECT_EQ(-55, matrix.getTranslateY());
EXPECT_EQ(100, matrix.getScaleX());
EXPECT_EQ(55, matrix.getScaleY());
EXPECT_EQ(0, matrix.getSkewX());
EXPECT_EQ(0, matrix.getSkewY());
}
{
gfx::Transform transform;
transform.Translate(1.0, 1.0);
gfx::Transform t2;
t2.Scale(100.0, 55.0);
gfx::Transform t3;
t3.Translate(110.0, -110.0);
transform.PostConcat(t2);
transform.PostConcat(t3);
// convert to a 3x3 matrix
SkMatrix matrix = gfx::TransformToFlattenedSkMatrix(transform);
EXPECT_EQ(210, matrix.getTranslateX());
EXPECT_EQ(-55, matrix.getTranslateY());
EXPECT_EQ(100, matrix.getScaleX());
EXPECT_EQ(55, matrix.getScaleY());
EXPECT_EQ(0, matrix.getSkewX());
EXPECT_EQ(0, matrix.getSkewY());
}
// Conversions from child->top and top->child.
{
// child->top
gfx::Point point(5, 5);
View::ConvertPointToTarget(child, &top_view, &point);
EXPECT_EQ(22, point.x());
EXPECT_EQ(39, point.y());
gfx::Rect kSrc(5, 5, 10, 20);
gfx::RectF kSrcF(kSrc);
gfx::Rect kExpected(22, 39, 30, 80);
gfx::Rect kActual = View::ConvertRectToTarget(child, &top_view, kSrc);
EXPECT_EQ(kActual, kExpected);
gfx::RectF kActualF = View::ConvertRectToTarget(child, &top_view, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(child, &top_view, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
// top->child
point.SetPoint(22, 39);
View::ConvertPointToTarget(&top_view, child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
kSrc.SetRect(22, 39, 30, 80);
kSrcF = gfx::RectF(kSrc);
kExpected.SetRect(5, 5, 10, 20);
kActual = View::ConvertRectToTarget(&top_view, child, kSrc);
EXPECT_EQ(kActual, kExpected);
kActualF = View::ConvertRectToTarget(&top_view, child, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(&top_view, child, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
}
// Conversions from child_child->top and top->child_child.
{
// child_child->top
gfx::Point point(5, 5);
View::ConvertPointToTarget(child_child, &top_view, &point);
EXPECT_EQ(133, point.x());
EXPECT_EQ(211, point.y());
gfx::Rect kSrc(5, 5, 10, 20);
gfx::RectF kSrcF(kSrc);
gfx::Rect kExpected(133, 211, 150, 560);
gfx::Rect kActual = View::ConvertRectToTarget(child_child, &top_view, kSrc);
EXPECT_EQ(kActual, kExpected);
gfx::RectF kActualF =
View::ConvertRectToTarget(child_child, &top_view, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(child_child, &top_view, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
// top->child_child
point.SetPoint(133, 211);
View::ConvertPointToTarget(&top_view, child_child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
kSrc.SetRect(133, 211, 150, 560);
kSrcF = gfx::RectF(kSrc);
kExpected.SetRect(5, 5, 10, 20);
kActual = View::ConvertRectToTarget(&top_view, child_child, kSrc);
EXPECT_EQ(kActual, kExpected);
kActualF = View::ConvertRectToTarget(&top_view, child_child, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(&top_view, child_child, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
}
// Conversions from child_child->child and child->child_child
{
// child_child->child
gfx::Point point(5, 5);
View::ConvertPointToTarget(child_child, child, &point);
EXPECT_EQ(42, point.x());
EXPECT_EQ(48, point.y());
gfx::Rect kSrc(5, 5, 10, 20);
gfx::RectF kSrcF(kSrc);
gfx::Rect kExpected(42, 48, 50, 140);
gfx::Rect kActual = View::ConvertRectToTarget(child_child, child, kSrc);
EXPECT_EQ(kActual, kExpected);
gfx::RectF kActualF = View::ConvertRectToTarget(child_child, child, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(child_child, child, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
// child->child_child
point.SetPoint(42, 48);
View::ConvertPointToTarget(child, child_child, &point);
EXPECT_EQ(5, point.x());
EXPECT_EQ(5, point.y());
kSrc.SetRect(42, 48, 50, 140);
kSrcF = gfx::RectF(kSrc);
kExpected.SetRect(5, 5, 10, 20);
kActual = View::ConvertRectToTarget(child, child_child, kSrc);
EXPECT_EQ(kActual, kExpected);
kActualF = View::ConvertRectToTarget(child, child_child, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(child, child_child, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
}
// Conversions from top_view to child with a value that should be negative.
// This ensures we don't round up with negative numbers.
{
gfx::Point point(6, 18);
View::ConvertPointToTarget(&top_view, child, &point);
EXPECT_EQ(-1, point.x());
EXPECT_EQ(-1, point.y());
float error = 0.01f;
gfx::RectF rect(6.0f, 18.0f, 10.0f, 39.0f);
View::ConvertRectToTarget(&top_view, child, &rect);
EXPECT_NEAR(-0.33f, rect.x(), error);
EXPECT_NEAR(-0.25f, rect.y(), error);
EXPECT_NEAR(3.33f, rect.width(), error);
EXPECT_NEAR(9.75f, rect.height(), error);
}
// Rect conversions from top_view->child_2 and child_2->top_view.
{
// top_view->child_2
gfx::Rect kSrc(50, 55, 20, 30);
gfx::RectF kSrcF(kSrc);
gfx::Rect kExpected(615, 775, 30, 20);
gfx::Rect kActual = View::ConvertRectToTarget(child_2, &top_view, kSrc);
EXPECT_EQ(kActual, kExpected);
gfx::RectF kActualF = View::ConvertRectToTarget(child_2, &top_view, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(child_2, &top_view, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
// child_2->top_view
kSrc.SetRect(615, 775, 30, 20);
kSrcF = gfx::RectF(kSrc);
kExpected.SetRect(50, 55, 20, 30);
kActual = View::ConvertRectToTarget(&top_view, child_2, kSrc);
EXPECT_EQ(kActual, kExpected);
kActualF = View::ConvertRectToTarget(&top_view, child_2, kSrcF);
EXPECT_TRUE(kActualF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
View::ConvertRectToTarget(&top_view, child_2, &kSrcF);
EXPECT_TRUE(kSrcF.ApproximatelyEqual(gfx::RectF(kExpected),
kDefaultAllowedConversionError,
kDefaultAllowedConversionError));
}
}
// Tests conversion methods to and from screen coordinates.
TEST_F(ViewTest, ConversionsToFromScreen) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* child = widget->GetRootView()->AddChildView(std::make_unique<View>());
child->SetBounds(10, 10, 100, 200);
gfx::Transform t;
t.Scale(0.5, 0.5);
child->SetTransform(t);
gfx::Size size(10, 10);
gfx::Point point_in_screen(100, 90);
gfx::Point point_in_child(80, 60);
gfx::Rect rect_in_screen(point_in_screen, size);
gfx::Rect rect_in_child(point_in_child, size);
gfx::Point point = point_in_screen;
View::ConvertPointFromScreen(child, &point);
EXPECT_EQ(point_in_child.ToString(), point.ToString());
View::ConvertPointToScreen(child, &point);
EXPECT_EQ(point_in_screen.ToString(), point.ToString());
View::ConvertRectToScreen(child, &rect_in_child);
EXPECT_EQ(rect_in_screen.ToString(), rect_in_child.ToString());
}
// Tests conversion methods for rectangles.
TEST_F(ViewTest, ConvertRectWithTransform) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
TestView* v1 = root->AddChildView(std::make_unique<TestView>());
TestView* v2 = v1->AddChildView(std::make_unique<TestView>());
v1->SetBoundsRect(gfx::Rect(10, 10, 500, 500));
v2->SetBoundsRect(gfx::Rect(20, 20, 100, 200));
// |v2| now occupies (30, 30) to (130, 230) in |widget|
gfx::Rect rect(5, 5, 15, 40);
EXPECT_EQ(gfx::Rect(25, 25, 15, 40), v2->ConvertRectToParent(rect));
EXPECT_EQ(gfx::Rect(35, 35, 15, 40), v2->ConvertRectToWidget(rect));
// Rotate |v2|
gfx::Transform t2 = RotationCounterclockwise();
t2.set_rc(1, 3, 100.f);
v2->SetTransform(t2);
// |v2| now occupies (30, 30) to (230, 130) in |widget|
EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect));
EXPECT_EQ(gfx::Rect(35, 110, 40, 15), v2->ConvertRectToWidget(rect));
// Scale down |v1|
gfx::Transform t1;
t1.Scale(0.5, 0.5);
v1->SetTransform(t1);
// The rectangle should remain the same for |v1|.
EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect));
// |v2| now occupies (20, 20) to (120, 70) in |widget|
EXPECT_EQ(gfx::Rect(22, 60, 21, 8).ToString(),
v2->ConvertRectToWidget(rect).ToString());
}
class ObserverView : public View {
public:
ObserverView();
ObserverView(const ObserverView&) = delete;
ObserverView& operator=(const ObserverView&) = delete;
~ObserverView() override;
void ResetTestState();
bool has_add_details() const { return has_add_details_; }
bool has_remove_details() const { return has_remove_details_; }
const ViewHierarchyChangedDetails& add_details() const {
return add_details_;
}
const ViewHierarchyChangedDetails& remove_details() const {
return remove_details_;
}
private:
// View:
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
bool has_add_details_ = false;
bool has_remove_details_ = false;
ViewHierarchyChangedDetails add_details_;
ViewHierarchyChangedDetails remove_details_;
};
ObserverView::ObserverView() = default;
ObserverView::~ObserverView() = default;
void ObserverView::ResetTestState() {
has_add_details_ = false;
has_remove_details_ = false;
add_details_ = ViewHierarchyChangedDetails();
remove_details_ = ViewHierarchyChangedDetails();
}
void ObserverView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add) {
has_add_details_ = true;
add_details_ = details;
} else {
has_remove_details_ = true;
remove_details_ = details;
}
}
// Verifies that the ViewHierarchyChanged() notification is sent correctly when
// a child view is added or removed to all the views in the hierarchy (up and
// down).
// The tree looks like this:
// v1
// +-- v2(view2)
// +-- v3
// +-- v4 (starts here, then get reparented to v1)
TEST_F(ViewTest, ViewHierarchyChanged) {
auto view1 = std::make_unique<ObserverView>();
ObserverView* v1 = view1.get();
auto view3 = std::make_unique<ObserverView>();
auto view2 = std::make_unique<ObserverView>();
ObserverView* v3 = view2->AddChildView(std::move(view3));
// Make sure both |view2| and |v3| receive the ViewHierarchyChanged()
// notification.
EXPECT_TRUE(view2->has_add_details());
EXPECT_FALSE(view2->has_remove_details());
EXPECT_EQ(view2.get(), view2->add_details().parent);
EXPECT_EQ(v3, view2->add_details().child);
EXPECT_EQ(nullptr, view2->add_details().move_view);
EXPECT_TRUE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
EXPECT_EQ(view2.get(), v3->add_details().parent);
EXPECT_EQ(v3, v3->add_details().child);
EXPECT_EQ(nullptr, v3->add_details().move_view);
// Reset everything to the initial state.
view2->ResetTestState();
v3->ResetTestState();
// Add |view2| to |view1|.
ObserverView* v2 = view1->AddChildView(std::move(view2));
// Verifies that |v2| is the child view *added* and the parent view is
// |v1|. Make sure all the views (v1, v2, v3) received _that_ information.
EXPECT_TRUE(v1->has_add_details());
EXPECT_FALSE(v1->has_remove_details());
EXPECT_EQ(v1, view1->add_details().parent);
EXPECT_EQ(v2, view1->add_details().child);
EXPECT_EQ(nullptr, view1->add_details().move_view);
EXPECT_TRUE(v2->has_add_details());
EXPECT_FALSE(v2->has_remove_details());
EXPECT_EQ(v1, v2->add_details().parent);
EXPECT_EQ(v2, v2->add_details().child);
EXPECT_EQ(nullptr, v2->add_details().move_view);
EXPECT_TRUE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
EXPECT_EQ(v1, v3->add_details().parent);
EXPECT_EQ(v2, v3->add_details().child);
EXPECT_EQ(nullptr, v3->add_details().move_view);
v1->ResetTestState();
v2->ResetTestState();
v3->ResetTestState();
view2 = view1->RemoveChildViewT(v2);
// view2 now owns v2 from here.
// Verifies that |view2| is the child view *removed* and the parent view is
// |v1|. Make sure all the views (v1, v2, v3) received _that_ information.
EXPECT_FALSE(v1->has_add_details());
EXPECT_TRUE(v1->has_remove_details());
EXPECT_EQ(v1, v1->remove_details().parent);
EXPECT_EQ(v2, v1->remove_details().child);
EXPECT_EQ(nullptr, v1->remove_details().move_view);
EXPECT_FALSE(v2->has_add_details());
EXPECT_TRUE(v2->has_remove_details());
EXPECT_EQ(v1, view2->remove_details().parent);
EXPECT_EQ(v2, view2->remove_details().child);
EXPECT_EQ(nullptr, view2->remove_details().move_view);
EXPECT_FALSE(v3->has_add_details());
EXPECT_TRUE(v3->has_remove_details());
EXPECT_EQ(v1, v3->remove_details().parent);
EXPECT_EQ(v3, v3->remove_details().child);
EXPECT_EQ(nullptr, v3->remove_details().move_view);
// Verifies notifications when reparenting a view.
// Add |v4| to |view2|.
auto* v4 = view2->AddChildView(std::make_unique<ObserverView>());
// Reset everything to the initial state.
v1->ResetTestState();
v2->ResetTestState();
v3->ResetTestState();
v4->ResetTestState();
// Reparent |v4| to |view1|.
v1->AddChildView(v4);
// Verifies that all views receive the correct information for all the child,
// parent and move views.
// |v1| is the new parent, |v4| is the child for add, |v2| is the old parent.
EXPECT_TRUE(v1->has_add_details());
EXPECT_FALSE(v1->has_remove_details());
EXPECT_EQ(v1, view1->add_details().parent);
EXPECT_EQ(v4, view1->add_details().child);
EXPECT_EQ(v2, view1->add_details().move_view);
// |v2| is the old parent, |v4| is the child for remove, |v1| is the new
// parent.
EXPECT_FALSE(v2->has_add_details());
EXPECT_TRUE(v2->has_remove_details());
EXPECT_EQ(v2, view2->remove_details().parent);
EXPECT_EQ(v4, view2->remove_details().child);
EXPECT_EQ(v1, view2->remove_details().move_view);
// |v3| is not impacted by this operation, and hence receives no notification.
EXPECT_FALSE(v3->has_add_details());
EXPECT_FALSE(v3->has_remove_details());
// |v4| is the reparented child, so it receives notifications for the remove
// and then the add. |view2| is its old parent, |v1| is its new parent.
EXPECT_TRUE(v4->has_remove_details());
EXPECT_TRUE(v4->has_add_details());
EXPECT_EQ(v2, v4->remove_details().parent);
EXPECT_EQ(v1, v4->add_details().parent);
EXPECT_EQ(v4, v4->add_details().child);
EXPECT_EQ(v4, v4->remove_details().child);
EXPECT_EQ(v1, v4->remove_details().move_view);
EXPECT_EQ(v2, v4->add_details().move_view);
}
class WidgetObserverView : public View {
public:
WidgetObserverView();
WidgetObserverView(const WidgetObserverView&) = delete;
WidgetObserverView& operator=(const WidgetObserverView&) = delete;
~WidgetObserverView() override;
void ResetTestState();
int added_to_widget_count() { return added_to_widget_count_; }
int removed_from_widget_count() { return removed_from_widget_count_; }
private:
void AddedToWidget() override;
void RemovedFromWidget() override;
int added_to_widget_count_ = 0;
int removed_from_widget_count_ = 0;
};
WidgetObserverView::WidgetObserverView() {
ResetTestState();
}
WidgetObserverView::~WidgetObserverView() = default;
void WidgetObserverView::ResetTestState() {
added_to_widget_count_ = 0;
removed_from_widget_count_ = 0;
}
void WidgetObserverView::AddedToWidget() {
++added_to_widget_count_;
}
void WidgetObserverView::RemovedFromWidget() {
++removed_from_widget_count_;
}
// Verifies that AddedToWidget and RemovedFromWidget are called for a view when
// it is added to hierarchy.
// The tree looks like this:
// widget
// +-- root
//
// then v1 is added to root:
//
// v1
// +-- v2
//
// finally v1 is removed from root.
TEST_F(ViewTest, AddedToRemovedFromWidget) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 650, 650);
widget->Init(std::move(params));
View* root = widget->GetRootView();
auto v1 = std::make_unique<WidgetObserverView>();
auto v2 = std::make_unique<WidgetObserverView>();
auto v3 = std::make_unique<WidgetObserverView>();
WidgetObserverView* v2_ptr = v1->AddChildView(std::move(v2));
EXPECT_EQ(0, v2_ptr->added_to_widget_count());
EXPECT_EQ(0, v2_ptr->removed_from_widget_count());
WidgetObserverView* v1_ptr = root->AddChildView(std::move(v1));
EXPECT_EQ(1, v1_ptr->added_to_widget_count());
EXPECT_EQ(0, v1_ptr->removed_from_widget_count());
EXPECT_EQ(1, v2_ptr->added_to_widget_count());
EXPECT_EQ(0, v2_ptr->removed_from_widget_count());
v1_ptr->ResetTestState();
v2_ptr->ResetTestState();
WidgetObserverView* v3_ptr = v2_ptr->AddChildView(std::move(v3));
EXPECT_EQ(0, v1_ptr->added_to_widget_count());
EXPECT_EQ(0, v1_ptr->removed_from_widget_count());
EXPECT_EQ(0, v2_ptr->added_to_widget_count());
EXPECT_EQ(0, v2_ptr->removed_from_widget_count());
v1_ptr->ResetTestState();
v2_ptr->ResetTestState();
v1 = root->RemoveChildViewT(v1_ptr);
EXPECT_EQ(0, v1->added_to_widget_count());
EXPECT_EQ(1, v1->removed_from_widget_count());
EXPECT_EQ(0, v2_ptr->added_to_widget_count());
EXPECT_EQ(1, v2_ptr->removed_from_widget_count());
v2_ptr->ResetTestState();
v2 = v1->RemoveChildViewT(v2_ptr);
EXPECT_EQ(0, v2->removed_from_widget_count());
// Test move between parents in a single Widget.
v3 = v2->RemoveChildViewT(v3_ptr);
v1->ResetTestState();
v2->ResetTestState();
v3->ResetTestState();
v2_ptr = v1->AddChildView(std::move(v2));
v1_ptr = root->AddChildView(std::move(v1));
v3_ptr = root->AddChildView(std::move(v3));
EXPECT_EQ(1, v1_ptr->added_to_widget_count());
EXPECT_EQ(1, v2_ptr->added_to_widget_count());
EXPECT_EQ(1, v3_ptr->added_to_widget_count());
// This should not invoke added or removed to/from the widget.
v1_ptr = v3_ptr->AddChildView(v1_ptr);
EXPECT_EQ(1, v1_ptr->added_to_widget_count());
EXPECT_EQ(0, v1_ptr->removed_from_widget_count());
EXPECT_EQ(1, v2_ptr->added_to_widget_count());
EXPECT_EQ(0, v2_ptr->removed_from_widget_count());
EXPECT_EQ(1, v3_ptr->added_to_widget_count());
EXPECT_EQ(0, v3_ptr->removed_from_widget_count());
// Test move between widgets.
UniqueWidgetPtr second_widget = std::make_unique<Widget>();
params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(150, 150, 650, 650);
second_widget->Init(std::move(params));
View* second_root = second_widget->GetRootView();
v1_ptr->ResetTestState();
v2_ptr->ResetTestState();
v3_ptr->ResetTestState();
v1_ptr =
second_root->AddChildView(v1_ptr->parent()->RemoveChildViewT(v1_ptr));
EXPECT_EQ(1, v1_ptr->removed_from_widget_count());
EXPECT_EQ(1, v1_ptr->added_to_widget_count());
EXPECT_EQ(1, v2_ptr->added_to_widget_count());
EXPECT_EQ(1, v2_ptr->removed_from_widget_count());
EXPECT_EQ(0, v3_ptr->added_to_widget_count());
EXPECT_EQ(0, v3_ptr->removed_from_widget_count());
}
// Verifies if the child views added under the root are all deleted when calling
// RemoveAllChildViews.
// The tree looks like this:
// root
// +-- child1
// +-- foo
// +-- bar0
// +-- bar1
// +-- bar2
// +-- child2
// +-- child3
TEST_F(ViewTest, RemoveAllChildViews) {
auto root = std::make_unique<View>();
View* child1 = root->AddChildView(std::make_unique<View>());
for (size_t i = 0; i < 2; ++i)
root->AddChildView(std::make_unique<View>());
View* foo = child1->AddChildView(std::make_unique<View>());
// Add some nodes to |foo|.
for (size_t i = 0; i < 3; ++i)
foo->AddChildView(std::make_unique<View>());
EXPECT_EQ(3u, root->children().size());
EXPECT_EQ(1u, child1->children().size());
EXPECT_EQ(3u, foo->children().size());
// Now remove all child views from root.
root->RemoveAllChildViews();
EXPECT_TRUE(root->children().empty());
}
TEST_F(ViewTest, Contains) {
auto v1 = std::make_unique<View>();
auto* v2 = v1->AddChildView(std::make_unique<View>());
auto* v3 = v2->AddChildView(std::make_unique<View>());
EXPECT_FALSE(v1->Contains(nullptr));
EXPECT_TRUE(v1->Contains(v1.get()));
EXPECT_TRUE(v1->Contains(v2));
EXPECT_TRUE(v1->Contains(v3));
EXPECT_FALSE(v2->Contains(nullptr));
EXPECT_TRUE(v2->Contains(v2));
EXPECT_FALSE(v2->Contains(v1.get()));
EXPECT_TRUE(v2->Contains(v3));
EXPECT_FALSE(v3->Contains(nullptr));
EXPECT_TRUE(v3->Contains(v3));
EXPECT_FALSE(v3->Contains(v1.get()));
EXPECT_FALSE(v3->Contains(v2));
}
// Verifies if GetIndexOf() returns the correct index for the specified child
// view.
// The tree looks like this:
// root
// +-- child1
// +-- foo1
// +-- child2
TEST_F(ViewTest, GetIndexOf) {
auto root = std::make_unique<View>();
auto* child1 = root->AddChildView(std::make_unique<View>());
auto* child2 = root->AddChildView(std::make_unique<View>());
auto* foo1 = child1->AddChildView(std::make_unique<View>());
EXPECT_FALSE(root->GetIndexOf(nullptr).has_value());
EXPECT_FALSE(root->GetIndexOf(root.get()).has_value());
EXPECT_EQ(0u, root->GetIndexOf(child1));
EXPECT_EQ(1u, root->GetIndexOf(child2));
EXPECT_FALSE(root->GetIndexOf(foo1).has_value());
EXPECT_FALSE(child1->GetIndexOf(nullptr).has_value());
EXPECT_FALSE(child1->GetIndexOf(root.get()).has_value());
EXPECT_FALSE(child1->GetIndexOf(child1).has_value());
EXPECT_FALSE(child1->GetIndexOf(child2).has_value());
EXPECT_EQ(0u, child1->GetIndexOf(foo1));
EXPECT_FALSE(child2->GetIndexOf(nullptr).has_value());
EXPECT_FALSE(child2->GetIndexOf(root.get()).has_value());
EXPECT_FALSE(child2->GetIndexOf(child2).has_value());
EXPECT_FALSE(child2->GetIndexOf(child1).has_value());
EXPECT_FALSE(child2->GetIndexOf(foo1).has_value());
}
// Verifies that the child views can be reordered correctly.
TEST_F(ViewTest, ReorderChildren) {
auto root = std::make_unique<View>();
auto* child = root->AddChildView(std::make_unique<View>());
auto* foo1 = child->AddChildView(std::make_unique<View>());
auto* foo2 = child->AddChildView(std::make_unique<View>());
auto* foo3 = child->AddChildView(std::make_unique<View>());
foo1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
foo2->SetFocusBehavior(View::FocusBehavior::ALWAYS);
foo3->SetFocusBehavior(View::FocusBehavior::ALWAYS);
ASSERT_EQ(0u, child->GetIndexOf(foo1));
ASSERT_EQ(1u, child->GetIndexOf(foo2));
ASSERT_EQ(2u, child->GetIndexOf(foo3));
ASSERT_EQ(foo2, foo1->GetNextFocusableView());
ASSERT_EQ(foo3, foo2->GetNextFocusableView());
ASSERT_EQ(nullptr, foo3->GetNextFocusableView());
// Move |foo2| at the end.
child->ReorderChildView(foo2, child->children().size());
ASSERT_EQ(0u, child->GetIndexOf(foo1));
ASSERT_EQ(1u, child->GetIndexOf(foo3));
ASSERT_EQ(2u, child->GetIndexOf(foo2));
ASSERT_EQ(foo3, foo1->GetNextFocusableView());
ASSERT_EQ(foo2, foo3->GetNextFocusableView());
ASSERT_EQ(nullptr, foo2->GetNextFocusableView());
// Move |foo1| at the end.
child->ReorderChildView(foo1, child->children().size());
ASSERT_EQ(0u, child->GetIndexOf(foo3));
ASSERT_EQ(1u, child->GetIndexOf(foo2));
ASSERT_EQ(2u, child->GetIndexOf(foo1));
ASSERT_EQ(nullptr, foo1->GetNextFocusableView());
ASSERT_EQ(foo2, foo1->GetPreviousFocusableView());
ASSERT_EQ(foo2, foo3->GetNextFocusableView());
ASSERT_EQ(foo1, foo2->GetNextFocusableView());
// Move |foo2| to the front.
child->ReorderChildView(foo2, 0);
ASSERT_EQ(0u, child->GetIndexOf(foo2));
ASSERT_EQ(1u, child->GetIndexOf(foo3));
ASSERT_EQ(2u, child->GetIndexOf(foo1));
ASSERT_EQ(nullptr, foo1->GetNextFocusableView());
ASSERT_EQ(foo3, foo1->GetPreviousFocusableView());
ASSERT_EQ(foo3, foo2->GetNextFocusableView());
ASSERT_EQ(foo1, foo3->GetNextFocusableView());
}
// Verifies that GetViewByID returns the correctly child view from the specified
// ID.
// The tree looks like this:
// v1
// +-- v2
// +-- v3
// +-- v4
TEST_F(ViewTest, GetViewByID) {
View v1;
const int kV1ID = 1;
v1.SetID(kV1ID);
View v2;
const int kV2ID = 2;
v2.SetID(kV2ID);
View v3;
const int kV3ID = 3;
v3.SetID(kV3ID);
View v4;
const int kV4ID = 4;
v4.SetID(kV4ID);
const int kV5ID = 5;
v1.AddChildView(&v2);
v2.AddChildView(&v3);
v2.AddChildView(&v4);
EXPECT_EQ(&v1, v1.GetViewByID(kV1ID));
EXPECT_EQ(&v2, v1.GetViewByID(kV2ID));
EXPECT_EQ(&v4, v1.GetViewByID(kV4ID));
EXPECT_EQ(nullptr, v1.GetViewByID(kV5ID)); // No V5 exists.
EXPECT_EQ(nullptr,
v2.GetViewByID(kV1ID)); // It can get only from child views.
const int kGroup = 1;
v3.SetGroup(kGroup);
v4.SetGroup(kGroup);
View::Views views;
v1.GetViewsInGroup(kGroup, &views);
EXPECT_EQ(2U, views.size());
EXPECT_TRUE(base::Contains(views, &v3));
EXPECT_TRUE(base::Contains(views, &v4));
}
TEST_F(ViewTest, AddExistingChild) {
auto v1 = std::make_unique<View>();
auto* v2 = v1->AddChildView(std::make_unique<View>());
auto* v3 = v1->AddChildView(std::make_unique<View>());
EXPECT_EQ(0u, v1->GetIndexOf(v2));
EXPECT_EQ(1u, v1->GetIndexOf(v3));
// Check that there's no change in order when adding at same index.
v1->AddChildViewAt(v2, 0);
EXPECT_EQ(0u, v1->GetIndexOf(v2));
EXPECT_EQ(1u, v1->GetIndexOf(v3));
v1->AddChildViewAt(v3, 1);
EXPECT_EQ(0u, v1->GetIndexOf(v2));
EXPECT_EQ(1u, v1->GetIndexOf(v3));
// Add it at a different index and check for change in order.
v1->AddChildViewAt(v2, 1);
EXPECT_EQ(1u, v1->GetIndexOf(v2));
EXPECT_EQ(0u, v1->GetIndexOf(v3));
v1->AddChildViewAt(v2, 0);
EXPECT_EQ(0u, v1->GetIndexOf(v2));
EXPECT_EQ(1u, v1->GetIndexOf(v3));
// Check that calling AddChildView() moves to the end.
v1->AddChildView(v2);
EXPECT_EQ(1u, v1->GetIndexOf(v2));
EXPECT_EQ(0u, v1->GetIndexOf(v3));
v1->AddChildView(v3);
EXPECT_EQ(0u, v1->GetIndexOf(v2));
EXPECT_EQ(1u, v1->GetIndexOf(v3));
}
TEST_F(ViewTest, UseMirroredLayoutDisableMirroring) {
base::i18n::SetICUDefaultLocale("ar");
ASSERT_TRUE(base::i18n::IsRTL());
View parent, child1, child2;
parent.SetLayoutManager(
std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal));
child1.SetPreferredSize(gfx::Size(10, 10));
child2.SetPreferredSize(gfx::Size(10, 10));
parent.AddChildView(&child1);
parent.AddChildView(&child2);
parent.SizeToPreferredSize();
EXPECT_EQ(child1.GetNextFocusableView(), &child2);
EXPECT_GT(child1.GetMirroredX(), child2.GetMirroredX());
EXPECT_LT(child1.x(), child2.x());
EXPECT_NE(parent.GetMirroredXInView(5), 5);
parent.SetMirrored(false);
EXPECT_EQ(child1.GetNextFocusableView(), &child2);
EXPECT_GT(child2.GetMirroredX(), child1.GetMirroredX());
EXPECT_LT(child1.x(), child2.x());
EXPECT_EQ(parent.GetMirroredXInView(5), 5);
}
TEST_F(ViewTest, UseMirroredLayoutEnableMirroring) {
base::i18n::SetICUDefaultLocale("en");
ASSERT_FALSE(base::i18n::IsRTL());
View parent, child1, child2;
parent.SetLayoutManager(
std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal));
child1.SetPreferredSize(gfx::Size(10, 10));
child2.SetPreferredSize(gfx::Size(10, 10));
parent.AddChildView(&child1);
parent.AddChildView(&child2);
parent.SizeToPreferredSize();
EXPECT_EQ(child1.GetNextFocusableView(), &child2);
EXPECT_LT(child1.GetMirroredX(), child2.GetMirroredX());
EXPECT_LT(child1.x(), child2.x());
EXPECT_NE(parent.GetMirroredXInView(5), 15);
parent.SetMirrored(true);
EXPECT_EQ(child1.GetNextFocusableView(), &child2);
EXPECT_LT(child2.GetMirroredX(), child1.GetMirroredX());
EXPECT_LT(child1.x(), child2.x());
EXPECT_EQ(parent.GetMirroredXInView(5), 15);
}
////////////////////////////////////////////////////////////////////////////////
// FocusManager
////////////////////////////////////////////////////////////////////////////////
// A widget that always claims to be active, regardless of its real activation
// status.
class ActiveWidget : public Widget {
public:
ActiveWidget() = default;
ActiveWidget(const ActiveWidget&) = delete;
ActiveWidget& operator=(const ActiveWidget&) = delete;
~ActiveWidget() override = default;
bool IsActive() const override { return true; }
};
TEST_F(ViewTest, AdvanceFocusIfNecessaryForUnfocusableView) {
// Create a widget with two views and give the first one focus.
UniqueWidgetPtr widget = std::make_unique<ActiveWidget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
View* view1 = widget->GetRootView()->AddChildView(std::make_unique<View>());
view1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
View* view2 = widget->GetRootView()->AddChildView(std::make_unique<View>());
view2->SetFocusBehavior(View::FocusBehavior::ALWAYS);
FocusManager* focus_manager = widget->GetFocusManager();
ASSERT_TRUE(focus_manager);
focus_manager->SetFocusedView(view1);
EXPECT_EQ(view1, focus_manager->GetFocusedView());
// Disable the focused view and check if the next view gets focused.
view1->SetEnabled(false);
EXPECT_EQ(view2, focus_manager->GetFocusedView());
// Re-enable and re-focus.
view1->SetEnabled(true);
focus_manager->SetFocusedView(view1);
EXPECT_EQ(view1, focus_manager->GetFocusedView());
// Hide the focused view and check it the next view gets focused.
view1->SetVisible(false);
EXPECT_EQ(view2, focus_manager->GetFocusedView());
// Re-show and re-focus.
view1->SetVisible(true);
focus_manager->SetFocusedView(view1);
EXPECT_EQ(view1, focus_manager->GetFocusedView());
// Set the focused view as not focusable and check if the next view gets
// focused.
view1->SetFocusBehavior(View::FocusBehavior::NEVER);
EXPECT_EQ(view2, focus_manager->GetFocusedView());
}
////////////////////////////////////////////////////////////////////////////////
// Layers
////////////////////////////////////////////////////////////////////////////////
namespace {
// Test implementation of LayerAnimator.
class TestLayerAnimator : public ui::LayerAnimator {
public:
TestLayerAnimator();
TestLayerAnimator(const TestLayerAnimator&) = delete;
TestLayerAnimator& operator=(const TestLayerAnimator&) = delete;
const gfx::Rect& last_bounds() const { return last_bounds_; }
// LayerAnimator.
void SetBounds(const gfx::Rect& bounds) override;
protected:
~TestLayerAnimator() override = default;
private:
gfx::Rect last_bounds_;
};
TestLayerAnimator::TestLayerAnimator()
: ui::LayerAnimator(base::Milliseconds(0)) {}
void TestLayerAnimator::SetBounds(const gfx::Rect& bounds) {
last_bounds_ = bounds;
}
class TestingLayerViewObserver : public ViewObserver {
public:
explicit TestingLayerViewObserver(View* view) : view_(view) {
view_->AddObserver(this);
}
TestingLayerViewObserver(const TestingLayerViewObserver&) = delete;
TestingLayerViewObserver& operator=(const TestingLayerViewObserver&) = delete;
~TestingLayerViewObserver() override { view_->RemoveObserver(this); }
gfx::Rect GetLastLayerBoundsAndReset() {
gfx::Rect value = last_layer_bounds_;
last_layer_bounds_ = gfx::Rect();
return value;
}
gfx::Rect GetLastClipRectAndReset() {
gfx::Rect value = last_clip_rect_;
last_clip_rect_ = gfx::Rect();
return value;
}
private:
// ViewObserver:
void OnLayerTargetBoundsChanged(View* view) override {
last_layer_bounds_ = view->layer()->bounds();
}
void OnViewLayerClipRectChanged(View* view) override {
last_clip_rect_ = view->layer()->clip_rect();
}
gfx::Rect last_layer_bounds_;
gfx::Rect last_clip_rect_;
raw_ptr<View> view_;
};
} // namespace
class ViewLayerTest : public ViewsTestBase {
public:
ViewLayerTest() = default;
~ViewLayerTest() override = default;
// Returns the Layer used by the RootView.
ui::Layer* GetRootLayer() { return widget()->GetLayer(); }
void SetUp() override {
SetUpPixelCanvas();
ViewTest::SetUp();
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 200, 200);
widget_->Init(std::move(params));
widget_->Show();
widget_->GetRootView()->SetBounds(0, 0, 200, 200);
}
void TearDown() override {
widget_->CloseNow();
ViewsTestBase::TearDown();
}
Widget* widget() { return widget_; }
virtual void SetUpPixelCanvas() {
scoped_feature_list_.InitAndDisableFeature(
::features::kEnablePixelCanvasRecording);
}
protected:
// Accessors to View internals.
void SchedulePaintOnParent(View* view) { view->SchedulePaintOnParent(); }
private:
raw_ptr<Widget> widget_ = nullptr;
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(ViewLayerTest, LayerCreationAndDestruction) {
View view;
EXPECT_EQ(nullptr, view.layer());
view.SetPaintToLayer();
EXPECT_NE(nullptr, view.layer());
view.DestroyLayer();
EXPECT_EQ(nullptr, view.layer());
}
TEST_F(ViewLayerTest, SetTransformCreatesAndDestroysLayer) {
View view;
EXPECT_EQ(nullptr, view.layer());
// Set an arbitrary non-identity transform, which should cause a layer to be
// created.
gfx::Transform transform;
transform.Translate(1.0, 1.0);
view.SetTransform(transform);
EXPECT_NE(nullptr, view.layer());
// Set the identity transform, which should destroy the layer.
view.SetTransform(gfx::Transform());
EXPECT_EQ(nullptr, view.layer());
}
// Verify that setting an identity transform after SetPaintToLayer() has been
// called doesn't destroy the layer.
TEST_F(ViewLayerTest, IdentityTransformDoesntOverrideSetPaintToLayer) {
View view;
EXPECT_EQ(nullptr, view.layer());
view.SetPaintToLayer();
EXPECT_NE(nullptr, view.layer());
gfx::Transform transform;
transform.Translate(1.0, 1.0);
view.SetTransform(transform);
EXPECT_NE(nullptr, view.layer());
view.SetTransform(transform);
EXPECT_NE(nullptr, view.layer());
}
// Verify that calling DestroyLayer() while a non-identity transform is present
// doesn't destroy the layer.
TEST_F(ViewLayerTest, DestroyLayerDoesntOverrideTransform) {
View view;
EXPECT_EQ(nullptr, view.layer());
view.SetPaintToLayer();
EXPECT_NE(nullptr, view.layer());
gfx::Transform transform;
transform.Translate(1.0, 1.0);
view.SetTransform(transform);
EXPECT_NE(nullptr, view.layer());
view.DestroyLayer();
EXPECT_NE(nullptr, view.layer());
}
TEST_F(ViewLayerTest, LayerToggling) {
// Because we lazily create textures the calls to DrawTree are necessary to
// ensure we trigger creation of textures.
ui::Layer* root_layer = widget()->GetLayer();
View* content_view = widget()->SetContentsView(std::make_unique<View>());
// Create v1, give it a bounds and verify everything is set up correctly.
View* v1 = new View;
v1->SetPaintToLayer();
EXPECT_TRUE(v1->layer() != nullptr);
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
content_view->AddChildView(v1);
ASSERT_TRUE(v1->layer() != nullptr);
EXPECT_EQ(root_layer, v1->layer()->parent());
EXPECT_EQ(gfx::Rect(20, 30, 140, 150), v1->layer()->bounds());
// Create v2 as a child of v1 and do basic assertion testing.
View* v2 = new View;
TestingLayerViewObserver v2_observer(v2);
v1->AddChildView(v2);
EXPECT_TRUE(v2->layer() == nullptr);
v2->SetBoundsRect(gfx::Rect(10, 20, 30, 40));
v2->SetPaintToLayer();
ASSERT_TRUE(v2->layer() != nullptr);
EXPECT_EQ(v1->layer(), v2->layer()->parent());
EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
// Turn off v1s layer. v2 should still have a layer but its parent should have
// changed.
v1->DestroyLayer();
EXPECT_TRUE(v1->layer() == nullptr);
EXPECT_TRUE(v2->layer() != nullptr);
EXPECT_EQ(root_layer, v2->layer()->parent());
ASSERT_EQ(1u, root_layer->children().size());
EXPECT_EQ(root_layer->children()[0], v2->layer());
// The bounds of the layer should have changed to be relative to the root view
// now.
EXPECT_EQ(gfx::Rect(30, 50, 30, 40), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
// Make v1 have a layer again and verify v2s layer is wired up correctly.
gfx::Transform transform;
transform.Scale(2.0, 2.0);
v1->SetTransform(transform);
EXPECT_TRUE(v1->layer() != nullptr);
EXPECT_TRUE(v2->layer() != nullptr);
EXPECT_EQ(root_layer, v1->layer()->parent());
EXPECT_EQ(v1->layer(), v2->layer()->parent());
ASSERT_EQ(1u, root_layer->children().size());
EXPECT_EQ(root_layer->children()[0], v1->layer());
ASSERT_EQ(1u, v1->layer()->children().size());
EXPECT_EQ(v1->layer()->children()[0], v2->layer());
EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
}
// Verifies turning on a layer wires up children correctly.
TEST_F(ViewLayerTest, NestedLayerToggling) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
// Create v1, give it a bounds and verify everything is set up correctly.
View* v1 = content_view->AddChildView(std::make_unique<View>());
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
View* v2 = v1->AddChildView(std::make_unique<View>());
v2->SetBoundsRect(gfx::Rect(10, 10, 100, 100));
View* v3 = v2->AddChildView(std::make_unique<View>());
TestingLayerViewObserver v3_observer(v3);
v3->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
v3->SetPaintToLayer();
ASSERT_TRUE(v3->layer() != nullptr);
EXPECT_EQ(v3->layer()->bounds(), v3_observer.GetLastLayerBoundsAndReset());
// At this point we have v1-v2-v3. v3 has a layer, v1 and v2 don't.
v1->SetPaintToLayer();
EXPECT_EQ(v1->layer(), v3->layer()->parent());
EXPECT_EQ(v3->layer()->bounds(), v3_observer.GetLastLayerBoundsAndReset());
}
TEST_F(ViewLayerTest, LayerAnimator) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
View* v1 = content_view->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
EXPECT_TRUE(v1->layer() != nullptr);
TestLayerAnimator* animator = new TestLayerAnimator();
v1->layer()->SetAnimator(animator);
gfx::Rect bounds(1, 2, 3, 4);
v1->SetBoundsRect(bounds);
EXPECT_EQ(bounds, animator->last_bounds());
// TestLayerAnimator doesn't update the layer.
EXPECT_NE(bounds, v1->layer()->bounds());
}
// Verifies the bounds of a layer are updated if the bounds of ancestor that
// doesn't have a layer change.
TEST_F(ViewLayerTest, BoundsChangeWithLayer) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
View* v1 = content_view->AddChildView(std::make_unique<View>());
v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150));
View* v2 = v1->AddChildView(std::make_unique<View>());
TestingLayerViewObserver v2_observer(v2);
v2->SetBoundsRect(gfx::Rect(10, 11, 40, 50));
v2->SetPaintToLayer();
ASSERT_TRUE(v2->layer() != nullptr);
EXPECT_EQ(gfx::Rect(30, 41, 40, 50), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
v1->SetPosition(gfx::Point(25, 36));
EXPECT_EQ(gfx::Rect(35, 47, 40, 50), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
v2->SetPosition(gfx::Point(11, 12));
EXPECT_EQ(gfx::Rect(36, 48, 40, 50), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
// Bounds of the layer should change even if the view is not invisible.
v1->SetVisible(false);
v1->SetPosition(gfx::Point(20, 30));
EXPECT_EQ(gfx::Rect(31, 42, 40, 50), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
v2->SetVisible(false);
v2->SetBoundsRect(gfx::Rect(10, 11, 20, 30));
EXPECT_EQ(gfx::Rect(30, 41, 20, 30), v2->layer()->bounds());
EXPECT_EQ(v2->layer()->bounds(), v2_observer.GetLastLayerBoundsAndReset());
}
// Verifies the view observer is triggered when the clip rect of view's layer is
// updated.
TEST_F(ViewLayerTest, LayerClipRectChanged) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
View* v1 = content_view->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
auto* v1_layer = v1->layer();
ASSERT_TRUE(v1_layer != nullptr);
TestingLayerViewObserver v1_observer(v1);
v1_layer->SetClipRect(gfx::Rect(10, 10, 20, 20));
EXPECT_EQ(v1_layer->clip_rect(), gfx::Rect(10, 10, 20, 20));
EXPECT_EQ(v1_layer->clip_rect(), v1_observer.GetLastClipRectAndReset());
v1_layer->SetClipRect(gfx::Rect(20, 20, 40, 40));
EXPECT_EQ(v1_layer->clip_rect(), gfx::Rect(20, 20, 40, 40));
EXPECT_EQ(v1_layer->clip_rect(), v1_observer.GetLastClipRectAndReset());
}
// Make sure layers are positioned correctly in RTL.
TEST_F(ViewLayerTest, BoundInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
View* view = widget()->SetContentsView(std::make_unique<View>());
int content_width = view->width();
// |v1| is initially not attached to anything. So its layer will have the same
// bounds as the view.
View* v1 = new View;
v1->SetPaintToLayer();
v1->SetBounds(10, 10, 20, 10);
EXPECT_EQ(gfx::Rect(10, 10, 20, 10), v1->layer()->bounds());
// Once |v1| is attached to the widget, its layer will get RTL-appropriate
// bounds.
view->AddChildView(v1);
EXPECT_EQ(gfx::Rect(content_width - 30, 10, 20, 10), v1->layer()->bounds());
gfx::Rect l1bounds = v1->layer()->bounds();
// Now attach a View to the widget first, then create a layer for it. Make
// sure the bounds are correct.
View* v2 = new View;
v2->SetBounds(50, 10, 30, 10);
EXPECT_FALSE(v2->layer());
view->AddChildView(v2);
v2->SetPaintToLayer();
EXPECT_EQ(gfx::Rect(content_width - 80, 10, 30, 10), v2->layer()->bounds());
gfx::Rect l2bounds = v2->layer()->bounds();
view->SetPaintToLayer();
EXPECT_EQ(l1bounds, v1->layer()->bounds());
EXPECT_EQ(l2bounds, v2->layer()->bounds());
// Move one of the views. Make sure the layer is positioned correctly
// afterwards.
v1->SetBounds(v1->x() - 5, v1->y(), v1->width(), v1->height());
l1bounds.set_x(l1bounds.x() + 5);
EXPECT_EQ(l1bounds, v1->layer()->bounds());
view->DestroyLayer();
EXPECT_EQ(l1bounds, v1->layer()->bounds());
EXPECT_EQ(l2bounds, v2->layer()->bounds());
// Move a view again.
v2->SetBounds(v2->x() + 5, v2->y(), v2->width(), v2->height());
l2bounds.set_x(l2bounds.x() - 5);
EXPECT_EQ(l2bounds, v2->layer()->bounds());
}
// Make sure that resizing a parent in RTL correctly repositions its children.
TEST_F(ViewLayerTest, ResizeParentInRTL) {
base::test::ScopedRestoreICUDefaultLocale scoped_locale_("he");
View* view = widget()->SetContentsView(std::make_unique<View>());
int content_width = view->width();
// Create a paints-to-layer view |v1|.
View* v1 = view->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
v1->SetBounds(10, 10, 20, 10);
EXPECT_EQ(gfx::Rect(content_width - 30, 10, 20, 10), v1->layer()->bounds());
// Attach a paints-to-layer child view to |v1|.
View* v2 = new View;
v2->SetPaintToLayer();
v2->SetBounds(3, 5, 6, 4);
EXPECT_EQ(gfx::Rect(3, 5, 6, 4), v2->layer()->bounds());
v1->AddChildView(v2);
// Check that |v2| now has RTL-appropriate bounds.
EXPECT_EQ(gfx::Rect(11, 5, 6, 4), v2->layer()->bounds());
// Attach a non-layer child view to |v1|, and give it a paints-to-layer child.
View* v3 = new View;
v3->SetBounds(1, 1, 18, 8);
View* v4 = new View;
v4->SetPaintToLayer();
v4->SetBounds(2, 4, 6, 4);
EXPECT_EQ(gfx::Rect(2, 4, 6, 4), v4->layer()->bounds());
v3->AddChildView(v4);
EXPECT_EQ(gfx::Rect(10, 4, 6, 4), v4->layer()->bounds());
v1->AddChildView(v3);
// Check that |v4| now has RTL-appropriate bounds.
EXPECT_EQ(gfx::Rect(11, 5, 6, 4), v4->layer()->bounds());
// Resize |v1|. Make sure that |v2| and |v4|'s layers have been moved
// correctly to RTL-appropriate bounds.
v1->SetSize(gfx::Size(30, 10));
EXPECT_EQ(gfx::Rect(21, 5, 6, 4), v2->layer()->bounds());
EXPECT_EQ(gfx::Rect(21, 5, 6, 4), v4->layer()->bounds());
// Move and resize |v3|. Make sure that |v4|'s layer has been moved correctly
// to RTL-appropriate bounds.
v3->SetBounds(2, 1, 12, 8);
EXPECT_EQ(gfx::Rect(20, 5, 6, 4), v4->layer()->bounds());
}
// Makes sure a transform persists after toggling the visibility.
TEST_F(ViewLayerTest, ToggleVisibilityWithTransform) {
View* view = widget()->SetContentsView(std::make_unique<View>());
gfx::Transform transform;
transform.Scale(2.0, 2.0);
view->SetTransform(transform);
EXPECT_EQ(2.0f, view->GetTransform().rc(0, 0));
view->SetVisible(false);
EXPECT_EQ(2.0f, view->GetTransform().rc(0, 0));
view->SetVisible(true);
EXPECT_EQ(2.0f, view->GetTransform().rc(0, 0));
}
// Verifies a transform persists after removing/adding a view with a transform.
TEST_F(ViewLayerTest, ResetTransformOnLayerAfterAdd) {
View* view = widget()->SetContentsView(std::make_unique<View>());
gfx::Transform transform;
transform.Scale(2.0, 2.0);
view->SetTransform(transform);
EXPECT_EQ(2.0f, view->GetTransform().rc(0, 0));
ASSERT_TRUE(view->layer() != nullptr);
EXPECT_EQ(2.0f, view->layer()->transform().rc(0, 0));
View* parent = view->parent();
parent->RemoveChildView(view);
parent->AddChildView(view);
EXPECT_EQ(2.0f, view->GetTransform().rc(0, 0));
ASSERT_TRUE(view->layer() != nullptr);
EXPECT_EQ(2.0f, view->layer()->transform().rc(0, 0));
}
// Makes sure that layer visibility is correct after toggling View visibility.
TEST_F(ViewLayerTest, ToggleVisibilityWithLayer) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
// The view isn't attached to a widget or a parent view yet. But it should
// still have a layer, but the layer should not be attached to the root
// layer.
View* v1 = new View;
v1->SetPaintToLayer();
EXPECT_TRUE(v1->layer());
EXPECT_FALSE(
LayerIsAncestor(widget()->GetCompositor()->root_layer(), v1->layer()));
// Once the view is attached to a widget, its layer should be attached to the
// root layer and visible.
content_view->AddChildView(v1);
EXPECT_TRUE(
LayerIsAncestor(widget()->GetCompositor()->root_layer(), v1->layer()));
EXPECT_TRUE(v1->layer()->IsVisible());
v1->SetVisible(false);
EXPECT_FALSE(v1->layer()->IsVisible());
v1->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsVisible());
widget()->Hide();
EXPECT_FALSE(v1->layer()->IsVisible());
widget()->Show();
EXPECT_TRUE(v1->layer()->IsVisible());
}
// Tests that the layers in the subtree are orphaned after a View is removed
// from the parent.
TEST_F(ViewLayerTest, OrphanLayerAfterViewRemove) {
View* content_view = widget()->SetContentsView(std::make_unique<View>());
View* v1 = new View;
content_view->AddChildView(v1);
View* v2 = new View;
v1->AddChildView(v2);
v2->SetPaintToLayer();
EXPECT_TRUE(
LayerIsAncestor(widget()->GetCompositor()->root_layer(), v2->layer()));
EXPECT_TRUE(v2->layer()->IsVisible());
content_view->RemoveChildView(v1);
EXPECT_FALSE(
LayerIsAncestor(widget()->GetCompositor()->root_layer(), v2->layer()));
// Reparent |v2|.
v1->RemoveChildView(v2);
content_view->AddChildView(v2);
delete v1;
v1 = nullptr;
EXPECT_TRUE(
LayerIsAncestor(widget()->GetCompositor()->root_layer(), v2->layer()));
EXPECT_TRUE(v2->layer()->IsVisible());
}
class PaintTrackingView : public View {
public:
PaintTrackingView() = default;
PaintTrackingView(const PaintTrackingView&) = delete;
PaintTrackingView& operator=(const PaintTrackingView&) = delete;
bool painted() const { return painted_; }
void set_painted(bool value) { painted_ = value; }
void OnPaint(gfx::Canvas* canvas) override { painted_ = true; }
private:
bool painted_ = false;
};
// Makes sure child views with layers aren't painted when paint starts at an
// ancestor.
TEST_F(ViewLayerTest, DontPaintChildrenWithLayers) {
PaintTrackingView* content_view =
widget()->SetContentsView(std::make_unique<PaintTrackingView>());
content_view->SetPaintToLayer();
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::WaitForCompositingEnded(
GetRootLayer()->GetCompositor());
GetRootLayer()->SchedulePaint(gfx::Rect(0, 0, 10, 10));
content_view->set_painted(false);
// content_view no longer has a dirty rect. Paint from the root and make sure
// PaintTrackingView isn't painted.
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::WaitForCompositingEnded(
GetRootLayer()->GetCompositor());
EXPECT_FALSE(content_view->painted());
// Make content_view have a dirty rect, paint the layers and make sure
// PaintTrackingView is painted.
content_view->layer()->SchedulePaint(gfx::Rect(0, 0, 10, 10));
GetRootLayer()->GetCompositor()->ScheduleDraw();
ui::DrawWaiterForTest::WaitForCompositingEnded(
GetRootLayer()->GetCompositor());
EXPECT_TRUE(content_view->painted());
}
TEST_F(ViewLayerTest, NoCrashWhenParentlessViewSchedulesPaintOnParent) {
TestView v;
SchedulePaintOnParent(&v);
}
TEST_F(ViewLayerTest, ScheduledRectsInParentAfterSchedulingPaint) {
TestView parent_view;
parent_view.SetBounds(10, 10, 100, 100);
TestView* child_view = parent_view.AddChildView(std::make_unique<TestView>());
child_view->SetBounds(5, 6, 10, 20);
parent_view.scheduled_paint_rects_.clear();
SchedulePaintOnParent(child_view);
ASSERT_EQ(1U, parent_view.scheduled_paint_rects_.size());
EXPECT_EQ(gfx::Rect(5, 6, 10, 20),
parent_view.scheduled_paint_rects_.front());
}
TEST_F(ViewLayerTest, ParentPaintWhenSwitchingPaintToLayerFromFalseToTrue) {
TestView parent_view;
parent_view.SetBounds(10, 11, 12, 13);
TestView* child_view = parent_view.AddChildView(std::make_unique<TestView>());
parent_view.scheduled_paint_rects_.clear();
child_view->SetPaintToLayer();
EXPECT_EQ(1U, parent_view.scheduled_paint_rects_.size());
}
TEST_F(ViewLayerTest, NoParentPaintWhenSwitchingPaintToLayerFromTrueToTrue) {
TestView parent_view;
parent_view.SetBounds(10, 11, 12, 13);
TestView* child_view = parent_view.AddChildView(std::make_unique<TestView>());
child_view->SetPaintToLayer();
parent_view.scheduled_paint_rects_.clear();
EXPECT_EQ(0U, parent_view.scheduled_paint_rects_.size());
}
// Tests that the visibility of child layers are updated correctly when a View's
// visibility changes.
TEST_F(ViewLayerTest, VisibilityChildLayers) {
View* v1 = widget()->SetContentsView(std::make_unique<View>());
v1->SetPaintToLayer();
View* v2 = v1->AddChildView(std::make_unique<View>());
View* v3 = v2->AddChildView(std::make_unique<View>());
v3->SetVisible(false);
View* v4 = v3->AddChildView(std::make_unique<View>());
v4->SetPaintToLayer();
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_FALSE(v4->layer()->IsVisible());
v2->SetVisible(false);
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_FALSE(v4->layer()->IsVisible());
v2->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_FALSE(v4->layer()->IsVisible());
v2->SetVisible(false);
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_FALSE(v4->layer()->IsVisible());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
v3->SetVisible(true);
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_FALSE(v4->layer()->IsVisible());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
// Reparent |v3| to |v1|.
v2->RemoveChildView(v3);
v1->AddChildView(v3);
EXPECT_TRUE(v1->layer()->IsVisible());
EXPECT_TRUE(v4->layer()->IsVisible());
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer()));
}
// This test creates a random View tree, and then randomly reorders child views,
// reparents views etc. Unrelated changes can appear to break this test. So
// marking this as FLAKY.
TEST_F(ViewLayerTest, DISABLED_ViewLayerTreesInSync) {
View* content = widget()->SetContentsView(std::make_unique<View>());
content->SetPaintToLayer();
widget()->Show();
ConstructTree(content, 5);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
ScrambleTree(content);
EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer()));
}
// Verifies when views are reordered the layer is also reordered. The widget is
// providing the parent layer.
TEST_F(ViewLayerTest, ReorderUnderWidget) {
View* content = widget()->SetContentsView(std::make_unique<View>());
View* c1 = content->AddChildView(std::make_unique<View>());
c1->SetPaintToLayer();
View* c2 = content->AddChildView(std::make_unique<View>());
c2->SetPaintToLayer();
ui::Layer* parent_layer = c1->layer()->parent();
ASSERT_TRUE(parent_layer);
ASSERT_EQ(2u, parent_layer->children().size());
EXPECT_EQ(c1->layer(), parent_layer->children()[0]);
EXPECT_EQ(c2->layer(), parent_layer->children()[1]);
// Move c1 to the front. The layers should have moved too.
content->ReorderChildView(c1, content->children().size());
EXPECT_EQ(c1->layer(), parent_layer->children()[1]);
EXPECT_EQ(c2->layer(), parent_layer->children()[0]);
}
// Verifies that the layer of a view can be acquired properly.
TEST_F(ViewLayerTest, AcquireLayer) {
View* content = widget()->SetContentsView(std::make_unique<View>());
std::unique_ptr<View> c1(new View);
c1->SetPaintToLayer();
EXPECT_TRUE(c1->layer());
content->AddChildView(c1.get());
std::unique_ptr<ui::Layer> layer(c1->AcquireLayer());
EXPECT_EQ(layer.get(), c1->layer());
std::unique_ptr<ui::Layer> layer2(c1->RecreateLayer());
EXPECT_NE(c1->layer(), layer2.get());
// Destroy view before destroying layer.
c1.reset();
}
// Verify the z-order of the layers as a result of calling RecreateLayer().
TEST_F(ViewLayerTest, RecreateLayerZOrder) {
std::unique_ptr<View> v(new View());
v->SetPaintToLayer();
View* v1 = v->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
View* v2 = v->AddChildView(std::make_unique<View>());
v2->SetPaintToLayer();
// Test the initial z-order.
const std::vector<ui::Layer*>& child_layers_pre = v->layer()->children();
ASSERT_EQ(2u, child_layers_pre.size());
EXPECT_EQ(v1->layer(), child_layers_pre[0]);
EXPECT_EQ(v2->layer(), child_layers_pre[1]);
std::unique_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer());
// Test the new layer order. We expect: |v1| |v1_old_layer| |v2|.
// for |v1| and |v2|.
const std::vector<ui::Layer*>& child_layers_post = v->layer()->children();
ASSERT_EQ(3u, child_layers_post.size());
EXPECT_EQ(v1->layer(), child_layers_post[0]);
EXPECT_EQ(v1_old_layer.get(), child_layers_post[1]);
EXPECT_EQ(v2->layer(), child_layers_post[2]);
}
// Verify the z-order of the layers as a result of calling RecreateLayer when
// the widget is the parent with the layer.
TEST_F(ViewLayerTest, RecreateLayerZOrderWidgetParent) {
View* v = widget()->SetContentsView(std::make_unique<View>());
View* v1 = v->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
View* v2 = v->AddChildView(std::make_unique<View>());
v2->SetPaintToLayer();
ui::Layer* root_layer = GetRootLayer();
// Test the initial z-order.
const std::vector<ui::Layer*>& child_layers_pre = root_layer->children();
ASSERT_EQ(2u, child_layers_pre.size());
EXPECT_EQ(v1->layer(), child_layers_pre[0]);
EXPECT_EQ(v2->layer(), child_layers_pre[1]);
std::unique_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer());
// Test the new layer order. We expect: |v1| |v1_old_layer| |v2|.
const std::vector<ui::Layer*>& child_layers_post = root_layer->children();
ASSERT_EQ(3u, child_layers_post.size());
EXPECT_EQ(v1->layer(), child_layers_post[0]);
EXPECT_EQ(v1_old_layer.get(), child_layers_post[1]);
EXPECT_EQ(v2->layer(), child_layers_post[2]);
}
// Verifies RecreateLayer() moves all Layers over, even those that don't have
// a View.
TEST_F(ViewLayerTest, RecreateLayerMovesNonViewChildren) {
View v;
v.SetPaintToLayer();
View child;
child.SetPaintToLayer();
v.AddChildView(&child);
ASSERT_TRUE(v.layer() != nullptr);
ASSERT_EQ(1u, v.layer()->children().size());
EXPECT_EQ(v.layer()->children()[0], child.layer());
ui::Layer layer(ui::LAYER_NOT_DRAWN);
v.layer()->Add(&layer);
v.layer()->StackAtBottom(&layer);
std::unique_ptr<ui::Layer> old_layer(v.RecreateLayer());
// All children should be moved from old layer to new layer.
ASSERT_TRUE(old_layer.get() != nullptr);
EXPECT_TRUE(old_layer->children().empty());
// And new layer should have the two children.
ASSERT_TRUE(v.layer() != nullptr);
ASSERT_EQ(2u, v.layer()->children().size());
EXPECT_EQ(v.layer()->children()[0], &layer);
EXPECT_EQ(v.layer()->children()[1], child.layer());
}
namespace {
std::string ToString(const gfx::Vector2dF& vector) {
// Explicitly round it because linux uses banker's rounding
// while Windows is using "away-from-zero" in printf.
return base::StringPrintf("%0.2f %0.2f", std::round(vector.x() * 100) / 100.f,
std::round(vector.y() * 100) / 100.f);
}
} // namespace
TEST_F(ViewLayerTest, SnapLayerToPixel) {
viz::ParentLocalSurfaceIdAllocator allocator;
allocator.GenerateId();
View* v1 = widget()->SetContentsView(std::make_unique<View>());
View* v11 = v1->AddChildView(std::make_unique<View>());
const gfx::Size& size = GetRootLayer()->GetCompositor()->size();
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.25f, size, allocator.GetCurrentLocalSurfaceId());
v11->SetBoundsRect(gfx::Rect(1, 1, 10, 10));
v1->SetBoundsRect(gfx::Rect(1, 1, 10, 10));
v11->SetPaintToLayer();
EXPECT_EQ("0.40 0.40", ToString(v11->layer()->GetSubpixelOffset()));
// Creating a layer in parent should update the child view's layer offset.
v1->SetPaintToLayer();
EXPECT_EQ("-0.20 -0.20", ToString(v1->layer()->GetSubpixelOffset()));
EXPECT_EQ("-0.20 -0.20", ToString(v11->layer()->GetSubpixelOffset()));
// DSF change should get propagated and update offsets.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.5f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.33 0.33", ToString(v1->layer()->GetSubpixelOffset()));
EXPECT_EQ("0.33 0.33", ToString(v11->layer()->GetSubpixelOffset()));
// Deleting parent's layer should update the child view's layer's offset.
v1->DestroyLayer();
EXPECT_EQ("0.00 0.00", ToString(v11->layer()->GetSubpixelOffset()));
// Setting parent view should update the child view's layer's offset.
v1->SetBoundsRect(gfx::Rect(2, 2, 10, 10));
EXPECT_EQ("0.33 0.33", ToString(v11->layer()->GetSubpixelOffset()));
// Setting integral DSF should reset the offset.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
2.0f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.00 0.00", ToString(v11->layer()->GetSubpixelOffset()));
// DSF reset followed by DSF change should update the offset.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.0f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.00 0.00", ToString(v11->layer()->GetSubpixelOffset()));
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.5f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.33 0.33", ToString(v11->layer()->GetSubpixelOffset()));
}
TEST_F(ViewLayerTest, LayerBeneathTriggersPaintToLayer) {
View root;
root.SetPaintToLayer();
View* view = root.AddChildView(std::make_unique<View>());
EXPECT_EQ(nullptr, view->layer());
ui::Layer layer1;
ui::Layer layer2;
view->AddLayerToRegion(&layer1, LayerRegion::kBelow);
EXPECT_NE(nullptr, view->layer());
view->AddLayerToRegion(&layer2, LayerRegion::kBelow);
EXPECT_NE(nullptr, view->layer());
view->RemoveLayerFromRegions(&layer1);
EXPECT_NE(nullptr, view->layer());
view->RemoveLayerFromRegions(&layer2);
EXPECT_EQ(nullptr, view->layer());
}
TEST_F(ViewLayerTest, LayerBeneathAddedToTree) {
View root;
root.SetPaintToLayer();
ui::Layer layer;
View* view = root.AddChildView(std::make_unique<View>());
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
ASSERT_NE(nullptr, view->layer());
EXPECT_TRUE(view->layer()->parent()->Contains(&layer));
view->RemoveLayerFromRegions(&layer);
EXPECT_EQ(nullptr, layer.parent());
}
TEST_F(ViewLayerTest, LayerBeneathAtFractionalScale) {
constexpr float device_scale = 1.5f;
viz::ParentLocalSurfaceIdAllocator allocator;
allocator.GenerateId();
const gfx::Size& size = GetRootLayer()->GetCompositor()->size();
GetRootLayer()->GetCompositor()->SetScaleAndSize(
device_scale, size, allocator.GetCurrentLocalSurfaceId());
View* view = widget()->SetContentsView(std::make_unique<View>());
ui::Layer layer;
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
view->SetBoundsRect(gfx::Rect(1, 1, 10, 10));
EXPECT_NE(gfx::Vector2dF(), view->layer()->GetSubpixelOffset());
EXPECT_EQ(view->layer()->GetSubpixelOffset(), layer.GetSubpixelOffset());
view->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewLayerTest, LayerBeneathRemovedOnDestruction) {
View root;
root.SetPaintToLayer();
auto layer = std::make_unique<ui::Layer>();
View* view = root.AddChildView(std::make_unique<View>());
// No assertions, just get coverage of deleting the layer while it is added.
view->AddLayerToRegion(layer.get(), LayerRegion::kBelow);
layer.reset();
root.RemoveChildView(view);
delete view;
}
TEST_F(ViewLayerTest, LayerBeneathVisibilityUpdated) {
View root;
root.SetPaintToLayer();
ui::Layer layer;
// Make a parent view that has no layer, and a child view that has a layer.
View* parent = root.AddChildView(std::make_unique<View>());
View* child = parent->AddChildView(std::make_unique<View>());
child->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_EQ(nullptr, parent->layer());
EXPECT_NE(nullptr, child->layer());
// Test setting the views' visbilities in various orders.
EXPECT_TRUE(layer.visible());
child->SetVisible(false);
EXPECT_FALSE(layer.visible());
child->SetVisible(true);
EXPECT_TRUE(layer.visible());
parent->SetVisible(false);
EXPECT_FALSE(layer.visible());
parent->SetVisible(true);
EXPECT_TRUE(layer.visible());
parent->SetVisible(false);
EXPECT_FALSE(layer.visible());
child->SetVisible(false);
EXPECT_FALSE(layer.visible());
parent->SetVisible(true);
EXPECT_FALSE(layer.visible());
child->SetVisible(true);
EXPECT_TRUE(layer.visible());
child->RemoveLayerFromRegions(&layer);
// Now check the visibility upon adding.
child->SetVisible(false);
child->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_FALSE(layer.visible());
child->SetVisible(true);
EXPECT_TRUE(layer.visible());
child->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewLayerTest, LayerBeneathHasCorrectBounds) {
View root;
root.SetBoundsRect(gfx::Rect(100, 100));
root.SetPaintToLayer();
View* view = root.AddChildView(std::make_unique<View>());
view->SetBoundsRect(gfx::Rect(25, 25, 50, 50));
// The layer's position will be changed, but its size should be respected.
ui::Layer layer;
layer.SetBounds(gfx::Rect(25, 25));
// First check when |view| is already painting to a layer.
view->SetPaintToLayer();
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_NE(nullptr, layer.parent());
EXPECT_EQ(gfx::Rect(25, 25, 25, 25), layer.bounds());
view->RemoveLayerFromRegions(&layer);
EXPECT_EQ(nullptr, layer.parent());
layer.SetBounds(gfx::Rect(25, 25));
// Next check when |view| wasn't painting to a layer.
view->DestroyLayer();
EXPECT_EQ(nullptr, view->layer());
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_NE(nullptr, view->layer());
EXPECT_NE(nullptr, layer.parent());
EXPECT_EQ(gfx::Rect(25, 25, 25, 25), layer.bounds());
// Finally check that moving |view| also moves the layer.
view->SetBoundsRect(gfx::Rect(50, 50, 50, 50));
EXPECT_EQ(gfx::Rect(50, 50, 25, 25), layer.bounds());
view->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewLayerTest, LayerBeneathTransformed) {
View root;
root.SetPaintToLayer();
ui::Layer layer;
View* view = root.AddChildView(std::make_unique<View>());
view->SetPaintToLayer();
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_TRUE(layer.transform().IsIdentity());
gfx::Transform transform;
transform.Rotate(90);
view->SetTransform(transform);
EXPECT_EQ(transform, layer.transform());
view->SetTransform(gfx::Transform());
EXPECT_TRUE(layer.transform().IsIdentity());
}
TEST_F(ViewLayerTest, UpdateChildLayerVisibilityEvenIfLayer) {
View root;
root.SetPaintToLayer();
View* view = root.AddChildView(std::make_unique<View>());
view->SetPaintToLayer();
View* child = view->AddChildView(std::make_unique<View>());
child->SetPaintToLayer();
EXPECT_TRUE(child->layer()->GetAnimator()->GetTargetVisibility());
// Makes the view invisible then destroy the layer.
view->SetVisible(false);
view->DestroyLayer();
EXPECT_FALSE(child->layer()->GetAnimator()->GetTargetVisibility());
view->SetVisible(true);
view->SetPaintToLayer();
EXPECT_TRUE(child->layer()->GetAnimator()->GetTargetVisibility());
// Destroys the layer then make the view invisible.
view->DestroyLayer();
view->SetVisible(false);
EXPECT_FALSE(child->layer()->GetAnimator()->GetTargetVisibility());
}
TEST_F(ViewLayerTest, LayerBeneathStackedCorrectly) {
using ui::test::ChildLayerNamesAsString;
View root;
root.SetPaintToLayer();
ui::Layer layer;
layer.SetName("layer");
View* v1 = root.AddChildView(std::make_unique<View>());
View* v2 = root.AddChildView(std::make_unique<View>());
View* v3 = root.AddChildView(std::make_unique<View>());
// Check that |layer| is stacked correctly as we add more layers to the tree.
v2->AddLayerToRegion(&layer, LayerRegion::kBelow);
v2->layer()->SetName("v2");
EXPECT_EQ(ChildLayerNamesAsString(*root.layer()), "layer v2");
v3->SetPaintToLayer();
v3->layer()->SetName("v3");
EXPECT_EQ(ChildLayerNamesAsString(*root.layer()), "layer v2 v3");
v1->SetPaintToLayer();
v1->layer()->SetName("v1");
EXPECT_EQ(ChildLayerNamesAsString(*root.layer()), "v1 layer v2 v3");
v2->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewLayerTest, LayerBeneathOrphanedOnRemoval) {
View root;
root.SetPaintToLayer();
ui::Layer layer;
View* view = root.AddChildView(std::make_unique<View>());
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_EQ(layer.parent(), root.layer());
// Ensure that the layer beneath is orphaned and re-parented appropriately.
root.RemoveChildView(view);
EXPECT_EQ(layer.parent(), nullptr);
root.AddChildView(view);
EXPECT_EQ(layer.parent(), root.layer());
view->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewLayerTest, LayerBeneathMovedWithView) {
using ui::test::ChildLayerNamesAsString;
View root;
root.SetPaintToLayer();
root.layer()->SetName("root");
ui::Layer layer;
layer.SetName("layer");
View* v1 = root.AddChildView(std::make_unique<View>());
View* v2 = root.AddChildView(std::make_unique<View>());
View* v3 = v1->AddChildView(std::make_unique<View>());
v1->SetPaintToLayer();
v1->layer()->SetName("v1");
v2->SetPaintToLayer();
v2->layer()->SetName("v2");
v3->SetPaintToLayer();
v3->layer()->SetName("v3");
// Verify that |layer| is stacked correctly.
v3->AddLayerToRegion(&layer, LayerRegion::kBelow);
EXPECT_EQ(ChildLayerNamesAsString(*v1->layer()), "layer v3");
// Move |v3| to under |v2| and check |layer|'s stacking.
v1->RemoveChildView(v3);
v2->AddChildView(std::unique_ptr<View>(v3));
EXPECT_EQ(ChildLayerNamesAsString(*v2->layer()), "layer v3");
}
namespace {
class PaintLayerView : public View {
public:
PaintLayerView() = default;
PaintLayerView(const PaintLayerView&) = delete;
PaintLayerView& operator=(const PaintLayerView&) = delete;
void PaintChildren(const PaintInfo& info) override {
last_paint_info_ = std::make_unique<PaintInfo>(info);
View::PaintChildren(info);
}
std::unique_ptr<PaintInfo> GetLastPaintInfo() {
return std::move(last_paint_info_);
}
private:
std::unique_ptr<PaintInfo> last_paint_info_;
};
} // namespace
class ViewLayerPixelCanvasTest : public ViewLayerTest {
public:
ViewLayerPixelCanvasTest() = default;
ViewLayerPixelCanvasTest(const ViewLayerPixelCanvasTest&) = delete;
ViewLayerPixelCanvasTest& operator=(const ViewLayerPixelCanvasTest&) = delete;
~ViewLayerPixelCanvasTest() override = default;
void SetUpPixelCanvas() override {
scoped_feature_list_.InitAndEnableFeature(
::features::kEnablePixelCanvasRecording);
}
// Test if the recording rects are same with and without layer.
void PaintRecordingSizeTest(PaintLayerView* v3,
const gfx::Size& expected_size) {
v3->DestroyLayer();
ui::Compositor* compositor = widget()->GetCompositor();
auto list = base::MakeRefCounted<cc::DisplayItemList>();
ui::PaintContext context(list.get(), compositor->device_scale_factor(),
gfx::Rect(compositor->size()), true);
widget()->GetRootView()->PaintFromPaintRoot(context);
EXPECT_EQ(expected_size, v3->GetLastPaintInfo()->paint_recording_size());
v3->SetPaintToLayer();
v3->OnPaintLayer(context);
EXPECT_EQ(expected_size, v3->GetLastPaintInfo()->paint_recording_size());
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(ViewLayerPixelCanvasTest, SnapLayerToPixel) {
viz::ParentLocalSurfaceIdAllocator allocator;
allocator.GenerateId();
View* v1 = widget()->SetContentsView(std::make_unique<View>());
View* v2 = v1->AddChildView(std::make_unique<View>());
PaintLayerView* v3 = v2->AddChildView(std::make_unique<PaintLayerView>());
const gfx::Size& size = GetRootLayer()->GetCompositor()->size();
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.6f, size, allocator.GetCurrentLocalSurfaceId());
v3->SetBoundsRect(gfx::Rect(14, 13, 13, 5));
v2->SetBoundsRect(gfx::Rect(7, 7, 50, 50));
v1->SetBoundsRect(gfx::Rect(9, 9, 100, 100));
PaintRecordingSizeTest(v3, gfx::Size(21, 8)); // Enclosing Rect = (21, 8)
EXPECT_EQ("-0.63 -0.25", ToString(v3->layer()->GetSubpixelOffset()));
// Creating a layer in parent should update the child view's layer offset.
v1->SetPaintToLayer();
EXPECT_EQ("-0.25 -0.25", ToString(v1->layer()->GetSubpixelOffset()));
EXPECT_EQ("-0.37 -0.00", ToString(v3->layer()->GetSubpixelOffset()));
// DSF change should get propagated and update offsets.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.5f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.33 0.33", ToString(v1->layer()->GetSubpixelOffset()));
EXPECT_EQ("0.33 0.67", ToString(v3->layer()->GetSubpixelOffset()));
v1->DestroyLayer();
PaintRecordingSizeTest(v3, gfx::Size(20, 7)); // Enclosing Rect = (20, 8)
v1->SetPaintToLayer();
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.33f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.02 0.02", ToString(v1->layer()->GetSubpixelOffset()));
EXPECT_EQ("0.05 -0.45", ToString(v3->layer()->GetSubpixelOffset()));
v1->DestroyLayer();
PaintRecordingSizeTest(v3, gfx::Size(17, 7)); // Enclosing Rect = (18, 7)
// Deleting parent's layer should update the child view's layer's offset.
EXPECT_EQ("0.08 -0.43", ToString(v3->layer()->GetSubpixelOffset()));
// Setting parent view should update the child view's layer's offset.
v1->SetBoundsRect(gfx::Rect(3, 3, 10, 10));
EXPECT_EQ("0.06 -0.44", ToString(v3->layer()->GetSubpixelOffset()));
// Setting integral DSF should reset the offset.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
2.0f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.00 0.00", ToString(v3->layer()->GetSubpixelOffset()));
// DSF reset followed by DSF change should update the offset.
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.0f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.00 0.00", ToString(v3->layer()->GetSubpixelOffset()));
GetRootLayer()->GetCompositor()->SetScaleAndSize(
1.33f, size, allocator.GetCurrentLocalSurfaceId());
EXPECT_EQ("0.06 -0.44", ToString(v3->layer()->GetSubpixelOffset()));
}
TEST_F(ViewLayerPixelCanvasTest, LayerBeneathOnPixelCanvas) {
constexpr float device_scale = 1.5f;
viz::ParentLocalSurfaceIdAllocator allocator;
allocator.GenerateId();
const gfx::Size& size = GetRootLayer()->GetCompositor()->size();
GetRootLayer()->GetCompositor()->SetScaleAndSize(
device_scale, size, allocator.GetCurrentLocalSurfaceId());
View* view = widget()->SetContentsView(std::make_unique<View>());
ui::Layer layer;
view->AddLayerToRegion(&layer, LayerRegion::kBelow);
view->SetBoundsRect(gfx::Rect(1, 1, 10, 10));
EXPECT_NE(gfx::Vector2dF(), view->layer()->GetSubpixelOffset());
EXPECT_EQ(view->layer()->GetSubpixelOffset(), layer.GetSubpixelOffset());
view->RemoveLayerFromRegions(&layer);
}
TEST_F(ViewTest, FocusableAssertions) {
// View subclasses may change insets based on whether they are focusable,
// which effects the preferred size. To avoid preferred size changing around
// these Views need to key off the last value set to SetFocusBehavior(), not
// whether the View is focusable right now. For this reason it's important
// that the return value of GetFocusBehavior() depends on the last value
// passed to SetFocusBehavior and not whether the View is focusable right now.
TestView view;
view.SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_EQ(View::FocusBehavior::ALWAYS, view.GetFocusBehavior());
view.SetEnabled(false);
EXPECT_EQ(View::FocusBehavior::ALWAYS, view.GetFocusBehavior());
view.SetFocusBehavior(View::FocusBehavior::NEVER);
EXPECT_EQ(View::FocusBehavior::NEVER, view.GetFocusBehavior());
view.SetFocusBehavior(View::FocusBehavior::ACCESSIBLE_ONLY);
EXPECT_EQ(View::FocusBehavior::ACCESSIBLE_ONLY, view.GetFocusBehavior());
}
////////////////////////////////////////////////////////////////////////////////
// NativeTheme
////////////////////////////////////////////////////////////////////////////////
void TestView::OnThemeChanged() {
View::OnThemeChanged();
native_theme_ = GetNativeTheme();
}
TEST_F(ViewTest, OnThemeChanged) {
auto test_view = std::make_unique<TestView>();
EXPECT_FALSE(test_view->native_theme_);
// Child view added before the widget hierarchy exists should get the
// new native theme notification.
TestView* test_view_child =
test_view->AddChildView(std::make_unique<TestView>());
EXPECT_FALSE(test_view_child->native_theme_);
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(params));
TestView* test_view_ptr =
widget->GetRootView()->AddChildView(std::move(test_view));
EXPECT_TRUE(test_view_ptr->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view_ptr->native_theme_);
EXPECT_TRUE(test_view_child->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view_child->native_theme_);
// Child view added after the widget hierarchy exists should also get the
// notification.
TestView* test_view_child_2 =
test_view_ptr->AddChildView(std::make_unique<TestView>());
EXPECT_TRUE(test_view_child_2->native_theme_);
EXPECT_EQ(widget->GetNativeTheme(), test_view_child_2->native_theme_);
}
class TestEventHandler : public ui::EventHandler {
public:
explicit TestEventHandler(TestView* view) : view_(view) {}
~TestEventHandler() override = default;
void OnMouseEvent(ui::MouseEvent* event) override {
// The |view_| should have received the event first.
EXPECT_EQ(ui::ET_MOUSE_PRESSED, view_->last_mouse_event_type_);
had_mouse_event_ = true;
}
raw_ptr<TestView> view_;
bool had_mouse_event_ = false;
};
TEST_F(ViewTest, ScopedTargetHandlerReceivesEvents) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 350, 350);
widget->Init(std::move(params));
View* root = widget->GetRootView();
TestView* v = root->AddChildView(std::make_unique<TestView>());
v->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
v->Reset();
{
TestEventHandler handler(v);
ui::ScopedTargetHandler scoped_target_handler(v, &handler);
// View's target EventHandler should be set to the |scoped_target_handler|.
EXPECT_EQ(&scoped_target_handler,
v->SetTargetHandler(&scoped_target_handler));
EXPECT_EQ(ui::ET_UNKNOWN, v->last_mouse_event_type_);
gfx::Point p(10, 120);
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p, p, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
root->OnMousePressed(pressed);
// Both the View |v| and the |handler| should have received the event.
EXPECT_EQ(ui::ET_MOUSE_PRESSED, v->last_mouse_event_type_);
EXPECT_TRUE(handler.had_mouse_event_);
}
// The View should continue receiving events after the |handler| is deleted.
v->Reset();
ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
root->OnMouseReleased(released);
EXPECT_EQ(ui::ET_MOUSE_RELEASED, v->last_mouse_event_type_);
}
// See comment above test for details.
class WidgetWithCustomTheme : public Widget {
public:
explicit WidgetWithCustomTheme(ui::TestNativeTheme* theme) : theme_(theme) {}
WidgetWithCustomTheme(const WidgetWithCustomTheme&) = delete;
WidgetWithCustomTheme& operator=(const WidgetWithCustomTheme&) = delete;
~WidgetWithCustomTheme() override = default;
// Widget:
const ui::NativeTheme* GetNativeTheme() const override { return theme_; }
private:
raw_ptr<ui::TestNativeTheme> theme_;
};
// See comment above test for details.
class ViewThatAddsViewInOnThemeChanged : public View {
public:
ViewThatAddsViewInOnThemeChanged() { SetPaintToLayer(); }
ViewThatAddsViewInOnThemeChanged(const ViewThatAddsViewInOnThemeChanged&) =
delete;
ViewThatAddsViewInOnThemeChanged& operator=(
const ViewThatAddsViewInOnThemeChanged&) = delete;
~ViewThatAddsViewInOnThemeChanged() override = default;
bool on_native_theme_changed_called() const {
return on_native_theme_changed_called_;
}
// View:
void OnThemeChanged() override {
View::OnThemeChanged();
on_native_theme_changed_called_ = true;
GetWidget()->GetRootView()->AddChildView(std::make_unique<View>());
}
private:
bool on_native_theme_changed_called_ = false;
};
// Creates and adds a new child view to |parent| that has a layer.
void AddViewWithChildLayer(View* parent) {
View* child = parent->AddChildView(std::make_unique<View>());
child->SetPaintToLayer();
}
// This test does the following:
// . creates a couple of views with layers added to the root.
// . Add a view that overrides OnThemeChanged(). In OnThemeChanged() another
// view is added. This sequence triggered DCHECKs or crashes previously. This
// tests verifies that doesn't happen. Reason for crash was OnThemeChanged() was
// called before the layer hierarchy was updated. OnThemeChanged() should be
// called after the layer hierarchy matches the view hierarchy.
TEST_F(ViewTest, CrashOnAddFromFromOnThemeChanged) {
ui::TestNativeTheme theme;
UniqueWidgetPtr widget = std::make_unique<WidgetWithCustomTheme>(&theme);
test::WidgetDestroyedWaiter waiter(widget.get());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(50, 50, 350, 350);
widget->Init(std::move(params));
AddViewWithChildLayer(widget->GetRootView());
ViewThatAddsViewInOnThemeChanged* v = widget->GetRootView()->AddChildView(
std::make_unique<ViewThatAddsViewInOnThemeChanged>());
EXPECT_TRUE(v->on_native_theme_changed_called());
// Initiate an explicit close and wait to ensure the |theme| outlives the
// |widget|.
widget->Close();
waiter.Wait();
}
// A View that removes its Layer when hidden.
class NoLayerWhenHiddenView : public View {
public:
using RemovedFromWidgetCallback = base::OnceCallback<void()>;
explicit NoLayerWhenHiddenView(RemovedFromWidgetCallback removed_from_widget)
: removed_from_widget_(std::move(removed_from_widget)) {
SetPaintToLayer();
SetBounds(0, 0, 100, 100);
}
NoLayerWhenHiddenView(const NoLayerWhenHiddenView&) = delete;
NoLayerWhenHiddenView& operator=(const NoLayerWhenHiddenView&) = delete;
bool was_hidden() const { return was_hidden_; }
// View:
void VisibilityChanged(View* starting_from, bool is_visible) override {
if (!is_visible) {
was_hidden_ = true;
DestroyLayer();
}
}
void RemovedFromWidget() override {
if (removed_from_widget_)
std::move(removed_from_widget_).Run();
}
private:
bool was_hidden_ = false;
RemovedFromWidgetCallback removed_from_widget_;
};
// Test that Views can safely manipulate Layers during Widget closure.
TEST_F(ViewTest, DestroyLayerInClose) {
bool removed_from_widget = false;
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(params));
widget->SetBounds(gfx::Rect(0, 0, 100, 100));
auto* view = widget->GetContentsView()->AddChildView(
std::make_unique<NoLayerWhenHiddenView>(base::BindOnce(
[](bool* removed_from_widget) { *removed_from_widget = true; },
&removed_from_widget)));
widget->Show();
EXPECT_TRUE(view->layer());
EXPECT_TRUE(view->GetWidget());
EXPECT_FALSE(view->was_hidden());
// Release and close the widget. It will be destroyed once it closes.
widget.reset();
EXPECT_FALSE(view->layer());
// Ensure the layer went away via VisibilityChanged().
EXPECT_TRUE(view->was_hidden());
// Not removed from Widget until Close() completes.
EXPECT_FALSE(removed_from_widget);
base::RunLoop().RunUntilIdle(); // Let the Close() complete.
EXPECT_TRUE(removed_from_widget);
}
// A View that keeps the children with a special ID above other children.
class OrderableView : public View {
public:
// ID used by the children that are stacked above other children.
static constexpr int VIEW_ID_RAISED = 1000;
OrderableView() = default;
OrderableView(const OrderableView&) = delete;
OrderableView& operator=(const OrderableView&) = delete;
~OrderableView() override = default;
View::Views GetChildrenInZOrder() override {
View::Views children_in_z_order = children();
std::stable_partition(
children_in_z_order.begin(), children_in_z_order.end(),
[](const View* child) { return child->GetID() != VIEW_ID_RAISED; });
return children_in_z_order;
}
};
TEST_F(ViewTest, ChildViewZOrderChanged) {
const size_t kNumChildren = 4;
auto view = std::make_unique<OrderableView>();
view->SetPaintToLayer();
for (size_t i = 0; i < kNumChildren; ++i)
AddViewWithChildLayer(view.get());
View::Views children = view->GetChildrenInZOrder();
const std::vector<ui::Layer*>& layers = view->layer()->children();
ASSERT_EQ(kNumChildren, children.size());
ASSERT_EQ(kNumChildren, layers.size());
for (size_t i = 0; i < kNumChildren; ++i) {
EXPECT_EQ(view->children()[i], children[i]);
EXPECT_EQ(view->children()[i]->layer(), layers[i]);
}
// Raise one of the children in z-order and add another child to reorder.
view->children()[2]->SetID(OrderableView::VIEW_ID_RAISED);
AddViewWithChildLayer(view.get());
// 2nd child should be now on top, i.e. the last element in the array returned
// by GetChildrenInZOrder(). Its layer should also be above the others.
// The rest of the children and layers order should be unchanged.
const size_t expected_order[] = {0, 1, 3, 4, 2};
children = view->GetChildrenInZOrder();
EXPECT_EQ(kNumChildren + 1, children.size());
EXPECT_EQ(kNumChildren + 1, layers.size());
for (size_t i = 0; i < kNumChildren + 1; ++i) {
EXPECT_EQ(view->children()[expected_order[i]], children[i]);
EXPECT_EQ(view->children()[expected_order[i]]->layer(), layers[i]);
}
}
TEST_F(ViewTest, AttachChildViewWithComplicatedLayers) {
std::unique_ptr<View> grand_parent_view = std::make_unique<View>();
grand_parent_view->SetPaintToLayer();
auto parent_view = std::make_unique<OrderableView>();
parent_view->SetPaintToLayer();
// child_view1 has layer and has id OrderableView::VIEW_ID_RAISED.
View* child_view1 = parent_view->AddChildView(std::make_unique<View>());
child_view1->SetPaintToLayer();
child_view1->SetID(OrderableView::VIEW_ID_RAISED);
// child_view2 has no layer.
View* child_view2 = parent_view->AddChildView(std::make_unique<View>());
// grand_child_view has layer.
View* grand_child_view = child_view2->AddChildView(std::make_unique<View>());
grand_child_view->SetPaintToLayer();
const std::vector<ui::Layer*>& layers = parent_view->layer()->children();
EXPECT_EQ(2u, layers.size());
EXPECT_EQ(layers[0], grand_child_view->layer());
EXPECT_EQ(layers[1], child_view1->layer());
// Attach parent_view to grand_parent_view. children layers of parent_view
// should not change.
OrderableView* parent_view_ptr =
grand_parent_view->AddChildView(std::move(parent_view));
const std::vector<ui::Layer*>& layers_after_attached =
parent_view_ptr->layer()->children();
EXPECT_EQ(2u, layers_after_attached.size());
EXPECT_EQ(layers_after_attached[0], grand_child_view->layer());
EXPECT_EQ(layers_after_attached[1], child_view1->layer());
}
TEST_F(ViewTest, TestEnabledPropertyMetadata) {
auto test_view = std::make_unique<View>();
bool enabled_changed = false;
auto subscription = test_view->AddEnabledChangedCallback(base::BindRepeating(
[](bool* enabled_changed) { *enabled_changed = true; },
&enabled_changed));
ui::metadata::ClassMetaData* view_metadata = View::MetaData();
ASSERT_TRUE(view_metadata);
ui::metadata::MemberMetaDataBase* enabled_property =
view_metadata->FindMemberData("Enabled");
ASSERT_TRUE(enabled_property);
std::u16string false_value = u"false";
enabled_property->SetValueAsString(test_view.get(), false_value);
EXPECT_TRUE(enabled_changed);
EXPECT_FALSE(test_view->GetEnabled());
EXPECT_EQ(enabled_property->GetValueAsString(test_view.get()), false_value);
}
TEST_F(ViewTest, TestMarginsPropertyMetadata) {
auto test_view = std::make_unique<View>();
ui::metadata::ClassMetaData* view_metadata = View::MetaData();
ASSERT_TRUE(view_metadata);
ui::metadata::MemberMetaDataBase* insets_property =
view_metadata->FindMemberData("kMarginsKey");
ASSERT_TRUE(insets_property);
std::u16string insets_value = u"8,8,8,8";
insets_property->SetValueAsString(test_view.get(), insets_value);
EXPECT_EQ(insets_property->GetValueAsString(test_view.get()), insets_value);
}
TEST_F(ViewTest, TestEnabledChangedCallback) {
auto test_view = std::make_unique<View>();
bool enabled_changed = false;
auto subscription = test_view->AddEnabledChangedCallback(base::BindRepeating(
[](bool* enabled_changed) { *enabled_changed = true; },
&enabled_changed));
test_view->SetEnabled(false);
EXPECT_TRUE(enabled_changed);
EXPECT_FALSE(test_view->GetEnabled());
}
TEST_F(ViewTest, TestVisibleChangedCallback) {
auto test_view = std::make_unique<View>();
bool visibility_changed = false;
auto subscription = test_view->AddVisibleChangedCallback(base::BindRepeating(
[](bool* visibility_changed) { *visibility_changed = true; },
&visibility_changed));
test_view->SetVisible(false);
EXPECT_TRUE(visibility_changed);
EXPECT_FALSE(test_view->GetVisible());
}
TEST_F(ViewTest, TooltipShowsForDisabledView) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(params));
widget->SetBounds(gfx::Rect(0, 0, 100, 100));
View enabled_parent;
View* const disabled_child =
enabled_parent.AddChildView(std::make_unique<View>());
disabled_child->SetEnabled(false);
enabled_parent.SetBoundsRect(gfx::Rect(0, 0, 100, 100));
disabled_child->SetBoundsRect(gfx::Rect(0, 0, 100, 100));
widget->GetContentsView()->AddChildView(&enabled_parent);
widget->Show();
EXPECT_EQ(disabled_child,
enabled_parent.GetTooltipHandlerForPoint(gfx::Point(50, 50)));
}
TEST_F(ViewTest, DefaultFocusListIsInChildOrder) {
View parent;
View* const first = parent.AddChildView(std::make_unique<View>());
EXPECT_EQ(first->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), nullptr);
View* const second = parent.AddChildView(std::make_unique<View>());
EXPECT_EQ(first->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), second);
EXPECT_EQ(second->GetPreviousFocusableView(), first);
EXPECT_EQ(second->GetNextFocusableView(), nullptr);
View* const last = parent.AddChildView(std::make_unique<View>());
EXPECT_EQ(first->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), second);
EXPECT_EQ(second->GetPreviousFocusableView(), first);
EXPECT_EQ(second->GetNextFocusableView(), last);
EXPECT_EQ(last->GetPreviousFocusableView(), second);
EXPECT_EQ(last->GetNextFocusableView(), nullptr);
}
TEST_F(ViewTest, RemoveFromFocusList) {
View parent;
View* const first = parent.AddChildView(std::make_unique<View>());
View* const second = parent.AddChildView(std::make_unique<View>());
View* const last = parent.AddChildView(std::make_unique<View>());
second->RemoveFromFocusList();
EXPECT_EQ(second->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(second->GetNextFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), last);
EXPECT_EQ(last->GetPreviousFocusableView(), first);
}
TEST_F(ViewTest, RemoveChildUpdatesFocusList) {
View parent;
View* const first = parent.AddChildView(std::make_unique<View>());
View* const second = parent.AddChildView(std::make_unique<View>());
View* const last = parent.AddChildView(std::make_unique<View>());
std::unique_ptr<View> removed = parent.RemoveChildViewT(second);
EXPECT_EQ(removed->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(removed->GetNextFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), last);
EXPECT_EQ(last->GetPreviousFocusableView(), first);
}
TEST_F(ViewTest, RemoveAllChildViewsNullsFocusListPointers) {
View parent;
View* const first = parent.AddChildView(std::make_unique<View>());
View* const second = parent.AddChildView(std::make_unique<View>());
View* const last = parent.AddChildView(std::make_unique<View>());
parent.RemoveAllChildViewsWithoutDeleting();
EXPECT_EQ(first->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(first->GetNextFocusableView(), nullptr);
EXPECT_EQ(second->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(second->GetNextFocusableView(), nullptr);
EXPECT_EQ(last->GetPreviousFocusableView(), nullptr);
EXPECT_EQ(last->GetNextFocusableView(), nullptr);
// The former child views must be deleted manually since the
// RemoveAllChildViews released ownership.
delete first;
delete second;
delete last;
}
TEST_F(ViewTest, InsertBeforeInFocusList) {
View parent;
View* const v1 = parent.AddChildView(std::make_unique<View>());
View* const v2 = parent.AddChildView(std::make_unique<View>());
View* const v3 = parent.AddChildView(std::make_unique<View>());
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v1, v2, v3));
v2->InsertBeforeInFocusList(v1);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v1, v3));
v3->InsertBeforeInFocusList(v1);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v3, v1));
v1->InsertBeforeInFocusList(v2);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v1, v2, v3));
v1->InsertBeforeInFocusList(v3);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v1, v3));
v1->InsertBeforeInFocusList(v3);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v1, v3));
}
TEST_F(ViewTest, InsertAfterInFocusList) {
View parent;
View* const v1 = parent.AddChildView(std::make_unique<View>());
View* const v2 = parent.AddChildView(std::make_unique<View>());
View* const v3 = parent.AddChildView(std::make_unique<View>());
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v1, v2, v3));
v1->InsertAfterInFocusList(v2);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v1, v3));
v1->InsertAfterInFocusList(v3);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v3, v1));
v2->InsertAfterInFocusList(v1);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v3, v1, v2));
v3->InsertAfterInFocusList(v2);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v1, v2, v3));
v1->InsertAfterInFocusList(v3);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v3, v1));
v1->InsertAfterInFocusList(v3);
EXPECT_THAT(parent.GetChildrenFocusList(), ElementsAre(v2, v3, v1));
}
////////////////////////////////////////////////////////////////////////////////
// Observer tests.
////////////////////////////////////////////////////////////////////////////////
class ViewObserverTest : public ViewTest, public ViewObserver {
public:
ViewObserverTest() = default;
ViewObserverTest(const ViewObserverTest&) = delete;
ViewObserverTest& operator=(const ViewObserverTest&) = delete;
~ViewObserverTest() override = default;
// ViewObserver:
void OnChildViewAdded(View* parent, View* child) override {
child_view_added_times_++;
child_view_added_ = child;
child_view_added_parent_ = parent;
}
void OnChildViewRemoved(View* parent, View* child) override {
child_view_removed_times_++;
child_view_removed_ = child;
child_view_removed_parent_ = parent;
}
void OnViewVisibilityChanged(View* view, View* starting_view) override {
view_visibility_changed_ = view;
view_visibility_changed_starting_ = starting_view;
}
void OnViewBoundsChanged(View* view) override { view_bounds_changed_ = view; }
void OnChildViewReordered(View* parent, View* view) override {
view_reordered_ = view;
}
void reset() {
child_view_added_times_ = 0;
child_view_removed_times_ = 0;
child_view_added_ = nullptr;
child_view_added_parent_ = nullptr;
child_view_removed_ = nullptr;
child_view_removed_parent_ = nullptr;
view_visibility_changed_ = nullptr;
view_bounds_changed_ = nullptr;
view_reordered_ = nullptr;
}
std::unique_ptr<View> NewView() {
auto view = std::make_unique<View>();
view->AddObserver(this);
return view;
}
int child_view_added_times() { return child_view_added_times_; }
int child_view_removed_times() { return child_view_removed_times_; }
const View* child_view_added() const { return child_view_added_; }
const View* child_view_added_parent() const {
return child_view_added_parent_;
}
const View* child_view_removed() const { return child_view_removed_; }
const View* child_view_removed_parent() const {
return child_view_removed_parent_;
}
const View* view_visibility_changed() const {
return view_visibility_changed_;
}
const View* view_visibility_changed_starting() const {
return view_visibility_changed_starting_;
}
const View* view_bounds_changed() const { return view_bounds_changed_; }
const View* view_reordered() const { return view_reordered_; }
private:
int child_view_added_times_ = 0;
int child_view_removed_times_ = 0;
raw_ptr<View> child_view_added_parent_ = nullptr;
raw_ptr<View> child_view_added_ = nullptr;
raw_ptr<View> child_view_removed_ = nullptr;
raw_ptr<View> child_view_removed_parent_ = nullptr;
raw_ptr<View> view_visibility_changed_ = nullptr;
raw_ptr<View> view_visibility_changed_starting_ = nullptr;
raw_ptr<View> view_bounds_changed_ = nullptr;
raw_ptr<View> view_reordered_ = nullptr;
};
TEST_F(ViewObserverTest, ViewParentChanged) {
std::unique_ptr<View> parent1 = NewView();
std::unique_ptr<View> parent2 = NewView();
std::unique_ptr<View> child_view = NewView();
parent1->AddChildView(child_view.get());
EXPECT_EQ(0, child_view_removed_times());
EXPECT_EQ(1, child_view_added_times());
EXPECT_EQ(child_view.get(), child_view_added());
EXPECT_EQ(child_view->parent(), child_view_added_parent());
EXPECT_EQ(child_view->parent(), parent1.get());
reset();
// Removed from parent1, added to parent2
parent1->RemoveChildView(child_view.get());
parent2->AddChildView(child_view.get());
EXPECT_EQ(1, child_view_removed_times());
EXPECT_EQ(1, child_view_added_times());
EXPECT_EQ(child_view.get(), child_view_removed());
EXPECT_EQ(parent1.get(), child_view_removed_parent());
EXPECT_EQ(child_view.get(), child_view_added());
EXPECT_EQ(child_view->parent(), parent2.get());
reset();
parent2->RemoveChildView(child_view.get());
EXPECT_EQ(1, child_view_removed_times());
EXPECT_EQ(0, child_view_added_times());
EXPECT_EQ(child_view.get(), child_view_removed());
EXPECT_EQ(parent2.get(), child_view_removed_parent());
}
TEST_F(ViewObserverTest, ViewVisibilityChanged) {
std::unique_ptr<View> parent(new View);
View* view = parent->AddChildView(NewView());
// Ensure setting |view| itself not visible calls the observer.
view->SetVisible(false);
EXPECT_EQ(view, view_visibility_changed());
EXPECT_EQ(view, view_visibility_changed_starting());
reset();
// Ditto for setting it visible.
view->SetVisible(true);
EXPECT_EQ(view, view_visibility_changed());
EXPECT_EQ(view, view_visibility_changed_starting());
reset();
// Ensure setting |parent| not visible also calls the
// observer. |view->GetVisible()| should still return true however.
parent->SetVisible(false);
EXPECT_EQ(view, view_visibility_changed());
EXPECT_EQ(parent.get(), view_visibility_changed_starting());
}
TEST_F(ViewObserverTest, ViewBoundsChanged) {
std::unique_ptr<View> view = NewView();
gfx::Rect bounds(2, 2, 2, 2);
view->SetBoundsRect(bounds);
EXPECT_EQ(view.get(), view_bounds_changed());
EXPECT_EQ(bounds, view->bounds());
reset();
gfx::Rect new_bounds(1, 1, 1, 1);
view->SetBoundsRect(new_bounds);
EXPECT_EQ(view.get(), view_bounds_changed());
EXPECT_EQ(new_bounds, view->bounds());
}
TEST_F(ViewObserverTest, ChildViewReordered) {
std::unique_ptr<View> view = NewView();
view->AddChildView(NewView());
View* child_view2 = view->AddChildView(NewView());
view->ReorderChildView(child_view2, 0);
EXPECT_EQ(child_view2, view_reordered());
}
// Provides a simple parent view implementation which tracks layer change
// notifications from child views.
class TestParentView : public View {
public:
TestParentView() = default;
TestParentView(const TestParentView&) = delete;
TestParentView& operator=(const TestParentView&) = delete;
void Reset() {
received_layer_change_notification_ = false;
layer_change_count_ = 0;
}
bool received_layer_change_notification() const {
return received_layer_change_notification_;
}
int layer_change_count() const { return layer_change_count_; }
// View overrides.
void OnChildLayerChanged(View* child) override {
received_layer_change_notification_ = true;
layer_change_count_++;
}
private:
// Set to true if we receive the OnChildLayerChanged() notification for a
// child.
bool received_layer_change_notification_ = false;
// Contains the number of OnChildLayerChanged() notifications for a child.
int layer_change_count_ = 0;
};
// Tests the following cases.
// 1. We receive the OnChildLayerChanged() notification when a layer change
// occurs in a child view.
// 2. We don't receive two layer changes when a child with an existing layer
// creates a new layer.
TEST_F(ViewObserverTest, ChildViewLayerNotificationTest) {
std::unique_ptr<TestParentView> parent_view(new TestParentView);
std::unique_ptr<View> child_view = NewView();
parent_view->AddChildView(child_view.get());
EXPECT_FALSE(parent_view->received_layer_change_notification());
EXPECT_EQ(0, parent_view->layer_change_count());
child_view->SetPaintToLayer(ui::LAYER_TEXTURED);
EXPECT_TRUE(parent_view->received_layer_change_notification());
EXPECT_EQ(1, parent_view->layer_change_count());
parent_view->Reset();
child_view->SetPaintToLayer(ui::LAYER_SOLID_COLOR);
EXPECT_TRUE(parent_view->received_layer_change_notification());
EXPECT_EQ(1, parent_view->layer_change_count());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_unittest.cc | C++ | unknown | 229,053 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view.h"
#include <memory>
#include "ui/aura/window.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/compositor/test/test_layers.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view_constants_aura.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/window_util.h"
namespace views {
namespace {
// Creates a widget of TYPE_CONTROL.
// The caller takes ownership of the returned widget.
Widget* CreateControlWidget(aura::Window* parent, const gfx::Rect& bounds) {
Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
params.parent = parent;
params.bounds = bounds;
Widget* widget = new Widget();
widget->Init(std::move(params));
return widget;
}
// Returns a view with a layer with the passed in |bounds| and |layer_name|.
// The caller takes ownership of the returned view.
View* CreateViewWithLayer(const gfx::Rect& bounds, const char* layer_name) {
View* view = new View();
view->SetBoundsRect(bounds);
view->SetPaintToLayer();
view->layer()->SetName(layer_name);
return view;
}
} // namespace
class ViewAuraTest : public ViewsTestBase {
public:
ViewAuraTest() = default;
ViewAuraTest(const ViewAuraTest&) = delete;
ViewAuraTest& operator=(const ViewAuraTest&) = delete;
~ViewAuraTest() override = default;
const View::Views& GetViewsWithLayers(Widget* widget) {
return widget->GetViewsWithLayers();
}
};
// Test that wm::RecreateLayers() recreates the layers for all child windows and
// all child views and that the z-order of the recreated layers matches that of
// the original layers.
// Test hierarchy:
// w1
// +-- v1
// +-- v2 (no layer)
// +-- v3 (no layer)
// +-- v4
// +-- w2
// +-- v5
// +-- v6
// +-- v7
// +-- v8
// +-- v9
TEST_F(ViewAuraTest, RecreateLayersWithWindows) {
Widget* w1 = CreateControlWidget(GetContext(), gfx::Rect(0, 0, 100, 100));
w1->GetNativeView()->layer()->SetName("w1");
View* v2 = new View();
v2->SetBounds(0, 1, 100, 101);
View* v3 = new View();
v3->SetBounds(0, 2, 100, 102);
View* w2_host_view = new View();
View* v1 = CreateViewWithLayer(gfx::Rect(0, 3, 100, 103), "v1");
ui::Layer* v1_layer = v1->layer();
w1->GetRootView()->AddChildView(v1);
w1->GetRootView()->AddChildView(v2);
v2->AddChildView(v3);
View* v4 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v4");
ui::Layer* v4_layer = v4->layer();
v2->AddChildView(v4);
w1->GetRootView()->AddChildView(w2_host_view);
View* v7 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v7");
ui::Layer* v7_layer = v7->layer();
w1->GetRootView()->AddChildView(v7);
View* v8 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v8");
ui::Layer* v8_layer = v8->layer();
v7->AddChildView(v8);
View* v9 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v9");
ui::Layer* v9_layer = v9->layer();
v7->AddChildView(v9);
Widget* w2 =
CreateControlWidget(w1->GetNativeView(), gfx::Rect(0, 5, 100, 105));
w2->GetNativeView()->layer()->SetName("w2");
w2->GetNativeView()->SetProperty(kHostViewKey, w2_host_view);
View* v5 = CreateViewWithLayer(gfx::Rect(0, 6, 100, 106), "v5");
w2->GetRootView()->AddChildView(v5);
View* v6 = CreateViewWithLayer(gfx::Rect(0, 7, 100, 107), "v6");
ui::Layer* v6_layer = v6->layer();
v5->AddChildView(v6);
// Test the initial order of the layers.
ui::Layer* w1_layer = w1->GetNativeView()->layer();
ASSERT_EQ("w1", w1_layer->name());
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer));
ui::Layer* w2_layer = w1_layer->children()[2];
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer));
ui::Layer* v5_layer = w2_layer->children()[0];
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer));
// Verify the value of Widget::GetRootLayers(). It should only include layers
// from layer-backed Views descended from the Widget's root View.
View::Views old_w1_views_with_layers = GetViewsWithLayers(w1);
ASSERT_EQ(3u, old_w1_views_with_layers.size());
EXPECT_EQ(v1, old_w1_views_with_layers[0]);
EXPECT_EQ(v4, old_w1_views_with_layers[1]);
EXPECT_EQ(v7, old_w1_views_with_layers[2]);
{
std::unique_ptr<ui::LayerTreeOwner> cloned_owner(
wm::RecreateLayers(w1->GetNativeView()));
EXPECT_EQ(w1_layer, cloned_owner->root());
EXPECT_NE(w1_layer, w1->GetNativeView()->layer());
// The old layers should still exist and have the same hierarchy.
ASSERT_EQ("w1", w1_layer->name());
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer));
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer));
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer));
EXPECT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_layer));
ASSERT_EQ(4u, w1_layer->children().size());
EXPECT_EQ(v1_layer, w1_layer->children()[0]);
EXPECT_EQ(v4_layer, w1_layer->children()[1]);
EXPECT_EQ(w2_layer, w1_layer->children()[2]);
EXPECT_EQ(v7_layer, w1_layer->children()[3]);
ASSERT_EQ(1u, w2_layer->children().size());
EXPECT_EQ(v5_layer, w2_layer->children()[0]);
ASSERT_EQ(1u, v5_layer->children().size());
EXPECT_EQ(v6_layer, v5_layer->children()[0]);
ASSERT_EQ(0u, v6_layer->children().size());
EXPECT_EQ(2u, v7_layer->children().size());
EXPECT_EQ(v8_layer, v7_layer->children()[0]);
EXPECT_EQ(v9_layer, v7_layer->children()[1]);
// The cloned layers should have the same hierarchy as old, but with new
// ui::Layer instances.
ui::Layer* w1_new_layer = w1->GetNativeView()->layer();
EXPECT_EQ("w1", w1_new_layer->name());
EXPECT_NE(w1_layer, w1_new_layer);
ui::Layer* v1_new_layer = w1_new_layer->children()[0];
ui::Layer* v4_new_layer = w1_new_layer->children()[1];
ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_new_layer));
EXPECT_NE(v1_layer, v1_new_layer);
EXPECT_NE(v4_layer, v4_new_layer);
ui::Layer* w2_new_layer = w1_new_layer->children()[2];
ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_new_layer));
ui::Layer* v5_new_layer = w2_new_layer->children()[0];
ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_new_layer));
ui::Layer* v7_new_layer = w1_new_layer->children()[3];
ASSERT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_new_layer));
EXPECT_NE(v7_layer, v7_new_layer);
// Ensure Widget::GetViewsWithLayers() is correctly updated.
View::Views new_w1_views_with_layers = GetViewsWithLayers(w1);
ASSERT_EQ(3u, new_w1_views_with_layers.size());
EXPECT_EQ(v1, new_w1_views_with_layers[0]);
EXPECT_EQ(v4, new_w1_views_with_layers[1]);
EXPECT_EQ(v7, new_w1_views_with_layers[2]);
}
w1->CloseNow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_unittest_aura.cc | C++ | unknown | 6,957 |
// 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/view.h"
#include "base/memory/raw_ptr.h"
#import <Cocoa/Cocoa.h>
#import "base/mac/scoped_nsobject.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/events/gesture_event_details.h"
#include "ui/views/test/widget_test.h"
// We can't create NSEventTypeSwipe using normal means, and rely on duck typing
// instead.
@interface FakeSwipeEvent : NSEvent
@property CGFloat deltaX;
@property CGFloat deltaY;
@property(assign) NSWindow* window;
@property NSPoint locationInWindow;
@property NSEventModifierFlags modifierFlags;
@property NSTimeInterval timestamp;
@end
@implementation FakeSwipeEvent
@synthesize deltaX;
@synthesize deltaY;
@synthesize window;
@synthesize locationInWindow;
@synthesize modifierFlags;
@synthesize timestamp;
- (NSEventType)type {
return NSEventTypeSwipe;
}
- (NSEventSubtype)subtype {
// themblsha: In my testing, all native three-finger NSEventTypeSwipe events
// all had 0 as their subtype.
return static_cast<NSEventSubtype>(0);
}
@end
namespace views {
namespace {
// Stores last received swipe gesture direction vector in
// |last_swipe_gesture()|.
class ThreeFingerSwipeView : public View {
public:
ThreeFingerSwipeView() = default;
ThreeFingerSwipeView(const ThreeFingerSwipeView&) = delete;
ThreeFingerSwipeView& operator=(const ThreeFingerSwipeView&) = delete;
// View:
void OnGestureEvent(ui::GestureEvent* event) override {
EXPECT_EQ(ui::ET_GESTURE_SWIPE, event->details().type());
int dx = 0, dy = 0;
if (event->details().swipe_left())
dx = -1;
if (event->details().swipe_right()) {
EXPECT_EQ(0, dx);
dx = 1;
}
if (event->details().swipe_down())
dy = 1;
if (event->details().swipe_up()) {
EXPECT_EQ(0, dy);
dy = -1;
}
last_swipe_gesture_ = gfx::Point(dx, dy);
}
absl::optional<gfx::Point> last_swipe_gesture() const {
return last_swipe_gesture_;
}
private:
absl::optional<gfx::Point> last_swipe_gesture_;
};
} // namespace
class ViewMacTest : public test::WidgetTest {
public:
ViewMacTest() = default;
ViewMacTest(const ViewMacTest&) = delete;
ViewMacTest& operator=(const ViewMacTest&) = delete;
absl::optional<gfx::Point> SwipeGestureVector(int dx, int dy) {
base::scoped_nsobject<FakeSwipeEvent> swipe_event(
[[FakeSwipeEvent alloc] init]);
[swipe_event setDeltaX:dx];
[swipe_event setDeltaY:dy];
[swipe_event setWindow:widget_->GetNativeWindow().GetNativeNSWindow()];
[swipe_event setLocationInWindow:NSMakePoint(50, 50)];
[swipe_event setTimestamp:[[NSProcessInfo processInfo] systemUptime]];
// BridgedContentView should create an appropriate ui::GestureEvent and pass
// it to the Widget.
[[widget_->GetNativeWindow().GetNativeNSWindow() contentView]
swipeWithEvent:swipe_event];
return view_->last_swipe_gesture();
}
// testing::Test:
void SetUp() override {
WidgetTest::SetUp();
widget_ = CreateTopLevelPlatformWidget();
widget_->SetBounds(gfx::Rect(0, 0, 100, 100));
widget_->Show();
view_ = new ThreeFingerSwipeView;
view_->SetSize(widget_->GetClientAreaBoundsInScreen().size());
widget_->non_client_view()->frame_view()->AddChildView(view_.get());
}
void TearDown() override {
widget_->CloseNow();
WidgetTest::TearDown();
}
private:
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<ThreeFingerSwipeView> view_ = nullptr;
};
// Three-finger swipes send immediate events and they cannot be tracked.
TEST_F(ViewMacTest, HandlesThreeFingerSwipeGestures) {
// Note that positive delta is left and up for NSEvent, which is the inverse
// of ui::GestureEventDetails.
EXPECT_EQ(gfx::Point(1, 0), *SwipeGestureVector(-1, 0));
EXPECT_EQ(gfx::Point(-1, 0), *SwipeGestureVector(1, 0));
EXPECT_EQ(gfx::Point(0, 1), *SwipeGestureVector(0, -1));
EXPECT_EQ(gfx::Point(0, -1), *SwipeGestureVector(0, 1));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_unittest_mac.mm | Objective-C++ | unknown | 4,103 |
// 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/view_utils.h"
#include <sstream>
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "ui/views/views_switches.h"
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT, base::debug::StackTrace*)
namespace views {
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(base::debug::StackTrace,
kViewStackTraceKey,
nullptr)
namespace {
std::string GetViewTreeAsString(View* view) {
if (!view->parent())
return view->GetClassName();
return GetViewTreeAsString(view->parent()) + " -> " + view->GetClassName();
}
} // namespace
ViewDebugWrapperImpl::ViewDebugWrapperImpl(View* view) : view_(view) {}
ViewDebugWrapperImpl::~ViewDebugWrapperImpl() = default;
std::string ViewDebugWrapperImpl::GetViewClassName() {
return view_->GetClassName();
}
int ViewDebugWrapperImpl::GetID() {
return view_->GetID();
}
debug::ViewDebugWrapper::BoundsTuple ViewDebugWrapperImpl::GetBounds() {
const auto& bounds = view_->bounds();
return BoundsTuple(bounds.x(), bounds.y(), bounds.width(), bounds.height());
}
bool ViewDebugWrapperImpl::GetVisible() {
return view_->GetVisible();
}
bool ViewDebugWrapperImpl::GetNeedsLayout() {
return view_->needs_layout();
}
bool ViewDebugWrapperImpl::GetEnabled() {
return view_->GetEnabled();
}
std::vector<debug::ViewDebugWrapper*> ViewDebugWrapperImpl::GetChildren() {
children_.clear();
for (auto* child : view_->children())
children_.push_back(std::make_unique<ViewDebugWrapperImpl>(child));
std::vector<debug::ViewDebugWrapper*> child_ptrs;
for (auto& child : children_)
child_ptrs.push_back(child.get());
return child_ptrs;
}
void ViewDebugWrapperImpl::ForAllProperties(PropCallback callback) {
views::View* view = const_cast<views::View*>(view_.get());
for (auto* member : *(view->GetClassMetaData())) {
auto flags = member->GetPropertyFlags();
if (!!(flags & ui::metadata::PropertyFlags::kSerializable)) {
callback.Run(member->member_name(),
base::UTF16ToUTF8(member->GetValueAsString(view)));
}
}
}
void PrintViewHierarchy(View* view, bool verbose, int depth) {
ViewDebugWrapperImpl debug_view(view);
std::ostringstream out;
debug::PrintViewHierarchy(&out, &debug_view, verbose, depth);
LOG(ERROR) << '\n' << out.str();
}
std::string GetViewDebugInfo(View* view) {
std::string debug_string =
std::string("View: ") + view->GetClassName() + "\n";
debug_string += std::string("Hierarchy:\n ") + GetViewTreeAsString(view);
debug_string += "\nView created here:\n";
static bool has_stack_trace =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kViewStackTraces);
if (has_stack_trace) {
debug_string += view->GetProperty(kViewStackTraceKey)->ToString();
} else {
debug_string += std::string(" Run with --") + switches::kViewStackTraces +
" to get a stack trace for when this View was created.";
}
return "\n" + debug_string;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/view_utils.cc | C++ | unknown | 3,230 |
// 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_VIEW_UTILS_H_
#define UI_VIEWS_VIEW_UTILS_H_
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
#include "base/debug/stack_trace.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/class_property.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/views/debug/debugger_utils.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace views {
VIEWS_EXPORT extern const ui::ClassProperty<base::debug::StackTrace*>* const
kViewStackTraceKey;
class ViewDebugWrapperImpl : public debug::ViewDebugWrapper {
public:
explicit ViewDebugWrapperImpl(View* view);
ViewDebugWrapperImpl(const ViewDebugWrapperImpl&) = delete;
ViewDebugWrapperImpl& operator=(const ViewDebugWrapperImpl&) = delete;
~ViewDebugWrapperImpl() override;
// debug::ViewDebugWrapper:
std::string GetViewClassName() override;
int GetID() override;
debug::ViewDebugWrapper::BoundsTuple GetBounds() override;
bool GetVisible() override;
bool GetNeedsLayout() override;
bool GetEnabled() override;
std::vector<debug::ViewDebugWrapper*> GetChildren() override;
void ForAllProperties(PropCallback callback) override;
private:
const raw_ptr<const View> view_;
std::vector<std::unique_ptr<ViewDebugWrapperImpl>> children_;
};
template <typename V>
bool IsViewClass(const View* view) {
static_assert(std::is_base_of<View, V>::value, "Only View classes supported");
const ui::metadata::ClassMetaData* parent = V::MetaData();
const ui::metadata::ClassMetaData* child = view->GetClassMetaData();
while (child && child != parent)
child = child->parent_class_meta_data();
return !!child;
}
template <typename V>
V* AsViewClass(View* view) {
if (!IsViewClass<V>(view))
return nullptr;
return static_cast<V*>(view);
}
template <typename V>
const V* AsViewClass(const View* view) {
if (!IsViewClass<V>(view))
return nullptr;
return static_cast<const V*>(view);
}
VIEWS_EXPORT void PrintViewHierarchy(View* view,
bool verbose = false,
int depth = -1);
VIEWS_EXPORT std::string GetViewDebugInfo(View* view);
} // namespace views
#endif // UI_VIEWS_VIEW_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/view_utils.h | C++ | unknown | 2,374 |
// 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/views_delegate.h"
#include <utility>
#include "base/command_line.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/views/views_touch_selection_controller_factory.h"
#include "ui/views/widget/native_widget_private.h"
#if defined(USE_AURA)
#include "ui/views/touchui/touch_selection_menu_runner_views.h"
#endif
namespace views {
namespace {
ViewsDelegate* views_delegate = nullptr;
} // namespace
ViewsDelegate::ViewsDelegate()
: editing_controller_factory_(new ViewsTouchEditingControllerFactory) {
DCHECK(!views_delegate);
views_delegate = this;
ui::TouchEditingControllerFactory::SetInstance(
editing_controller_factory_.get());
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_CHROMEOS_ASH)
// TouchSelectionMenuRunnerViews is not supported on Mac or Cast.
// It is also not used on Ash (the ChromeViewsDelegate() for Ash will
// immediately replace this). But tests running without the Chrome layer
// will not get the replacement.
touch_selection_menu_runner_ =
std::make_unique<TouchSelectionMenuRunnerViews>();
#endif
}
ViewsDelegate::~ViewsDelegate() {
ui::TouchEditingControllerFactory::SetInstance(nullptr);
DCHECK_EQ(this, views_delegate);
views_delegate = nullptr;
}
ViewsDelegate* ViewsDelegate::GetInstance() {
return views_delegate;
}
void ViewsDelegate::SaveWindowPlacement(const Widget* widget,
const std::string& window_name,
const gfx::Rect& bounds,
ui::WindowShowState show_state) {}
bool ViewsDelegate::GetSavedWindowPlacement(
const Widget* widget,
const std::string& window_name,
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
return false;
}
void ViewsDelegate::NotifyMenuItemFocused(const std::u16string& menu_name,
const std::u16string& menu_item_name,
int item_index,
int item_count,
bool has_submenu) {}
ViewsDelegate::ProcessMenuAcceleratorResult
ViewsDelegate::ProcessAcceleratorWhileMenuShowing(
const ui::Accelerator& accelerator) {
return ProcessMenuAcceleratorResult::LEAVE_MENU_OPEN;
}
bool ViewsDelegate::ShouldCloseMenuIfMouseCaptureLost() const {
return true;
}
#if BUILDFLAG(IS_WIN)
HICON ViewsDelegate::GetDefaultWindowIcon() const {
return nullptr;
}
HICON ViewsDelegate::GetSmallWindowIcon() const {
return nullptr;
}
bool ViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {
return false;
}
#elif BUILDFLAG(ENABLE_DESKTOP_AURA) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS))
gfx::ImageSkia* ViewsDelegate::GetDefaultWindowIcon() const {
return nullptr;
}
#endif
std::unique_ptr<NonClientFrameView>
ViewsDelegate::CreateDefaultNonClientFrameView(Widget* widget) {
return nullptr;
}
bool ViewsDelegate::IsShuttingDown() const {
return false;
}
void ViewsDelegate::AddRef() {}
void ViewsDelegate::ReleaseRef() {}
void ViewsDelegate::OnBeforeWidgetInit(
Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) {}
bool ViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {
return false;
}
#if BUILDFLAG(IS_MAC)
ui::ContextFactory* ViewsDelegate::GetContextFactory() {
return nullptr;
}
#endif
std::string ViewsDelegate::GetApplicationName() {
base::FilePath program = base::CommandLine::ForCurrentProcess()->GetProgram();
return program.BaseName().AsUTF8Unsafe();
}
#if BUILDFLAG(IS_WIN)
int ViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor,
base::OnceClosure callback) {
return EDGE_BOTTOM;
}
#endif
#if defined(USE_AURA)
void ViewsDelegate::SetTouchSelectionMenuRunner(
std::unique_ptr<TouchSelectionMenuRunnerViews> menu_runner) {
touch_selection_menu_runner_ = std::move(menu_runner);
}
#endif
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/views_delegate.cc | C++ | unknown | 4,210 |
// 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_VIEWS_DELEGATE_H_
#define UI_VIEWS_VIEWS_DELEGATE_H_
#include <memory>
#include <string>
#include <utility>
#include "build/build_config.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif
#include "base/functional/callback.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/buildflags.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
namespace gfx {
class ImageSkia;
class Rect;
} // namespace gfx
namespace ui {
#if BUILDFLAG(IS_MAC)
class ContextFactory;
#endif
class TouchEditingControllerFactory;
} // namespace ui
namespace views {
class NativeWidget;
class NonClientFrameView;
class Widget;
#if defined(USE_AURA)
class TouchSelectionMenuRunnerViews;
#endif
namespace internal {
class NativeWidgetDelegate;
}
// ViewsDelegate is an interface implemented by an object using the views
// framework. It is used to obtain various high level application utilities
// and perform some actions such as window placement saving.
//
// The embedding app must set the ViewsDelegate instance by instantiating an
// implementation of ViewsDelegate (the constructor will set the instance).
class VIEWS_EXPORT ViewsDelegate {
public:
using NativeWidgetFactory =
base::RepeatingCallback<NativeWidget*(const Widget::InitParams&,
internal::NativeWidgetDelegate*)>;
#if BUILDFLAG(IS_WIN)
enum AppbarAutohideEdge {
EDGE_TOP = 1 << 0,
EDGE_LEFT = 1 << 1,
EDGE_BOTTOM = 1 << 2,
EDGE_RIGHT = 1 << 3,
};
#endif
enum class ProcessMenuAcceleratorResult {
// The accelerator was handled while the menu was showing. No further action
// is needed and the menu should be kept open.
LEAVE_MENU_OPEN,
// The accelerator was not handled. The menu should be closed and event
// handling should stop for this event.
CLOSE_MENU,
};
ViewsDelegate(const ViewsDelegate&) = delete;
ViewsDelegate& operator=(const ViewsDelegate&) = delete;
virtual ~ViewsDelegate();
// Returns the ViewsDelegate instance. This should never return non-null
// unless the binary has not yet initialized the delegate, so callers should
// not generally null-check.
static ViewsDelegate* GetInstance();
// Call this method to set a factory callback that will be used to construct
// NativeWidget implementations overriding the platform defaults.
void set_native_widget_factory(NativeWidgetFactory factory) {
native_widget_factory_ = std::move(factory);
}
const NativeWidgetFactory& native_widget_factory() const {
return native_widget_factory_;
}
// Saves the position, size and "show" state for the window with the
// specified name.
virtual void SaveWindowPlacement(const Widget* widget,
const std::string& window_name,
const gfx::Rect& bounds,
ui::WindowShowState show_state);
// Retrieves the saved position and size and "show" state for the window with
// the specified name.
virtual bool GetSavedWindowPlacement(const Widget* widget,
const std::string& window_name,
gfx::Rect* bounds,
ui::WindowShowState* show_state) const;
// For accessibility, notify the delegate that a menu item was focused
// so that alternate feedback (speech / magnified text) can be provided.
virtual void NotifyMenuItemFocused(const std::u16string& menu_name,
const std::u16string& menu_item_name,
int item_index,
int item_count,
bool has_submenu);
// If |accelerator| can be processed while a menu is showing, it will be
// processed now and LEAVE_MENU_OPEN is returned. Otherwise, |accelerator|
// will be reposted for processing later after the menu closes and CLOSE_MENU
// will be returned.
virtual ProcessMenuAcceleratorResult ProcessAcceleratorWhileMenuShowing(
const ui::Accelerator& accelerator);
// If a menu is showing and its window loses mouse capture, it will close if
// this returns true.
virtual bool ShouldCloseMenuIfMouseCaptureLost() const;
#if BUILDFLAG(IS_WIN)
// Retrieves the default window icon to use for windows if none is specified.
virtual HICON GetDefaultWindowIcon() const;
// Retrieves the small window icon to use for windows if none is specified.
virtual HICON GetSmallWindowIcon() const;
// Returns true if the window passed in is in the Windows 8 metro
// environment.
virtual bool IsWindowInMetro(gfx::NativeWindow window) const;
#elif BUILDFLAG(ENABLE_DESKTOP_AURA) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS))
virtual gfx::ImageSkia* GetDefaultWindowIcon() const;
#endif
// Creates a default NonClientFrameView to be used for windows that don't
// specify their own. If this function returns NULL, the
// views::CustomFrameView type will be used.
virtual std::unique_ptr<NonClientFrameView> CreateDefaultNonClientFrameView(
Widget* widget);
// AddRef/ReleaseRef are invoked while a menu is visible. They are used to
// ensure we don't attempt to exit while a menu is showing.
virtual void AddRef();
virtual void ReleaseRef();
// Returns true if the application is shutting down. AddRef/Release should not
// be called in this situation.
virtual bool IsShuttingDown() const;
// Gives the platform a chance to modify the properties of a Widget.
virtual void OnBeforeWidgetInit(Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate);
// Returns true if the operating system's window manager will always provide a
// title bar with caption buttons (ignoring the setting to
// |remove_standard_frame| in InitParams). If |maximized|, this applies to
// maximized windows; otherwise to restored windows.
virtual bool WindowManagerProvidesTitleBar(bool maximized);
#if BUILDFLAG(IS_MAC)
// Returns the context factory for new windows.
virtual ui::ContextFactory* GetContextFactory();
#endif
// Returns the user-visible name of the application.
virtual std::string GetApplicationName();
#if BUILDFLAG(IS_WIN)
// Starts a query for the appbar autohide edges of the specified monitor and
// returns the current value. If the query finds the edges have changed from
// the current value, |callback| is subsequently invoked. If the edges have
// not changed, |callback| is never run.
//
// The return value is a bitmask of AppbarAutohideEdge.
virtual int GetAppbarAutohideEdges(HMONITOR monitor,
base::OnceClosure callback);
#endif
protected:
ViewsDelegate();
#if defined(USE_AURA)
void SetTouchSelectionMenuRunner(
std::unique_ptr<TouchSelectionMenuRunnerViews> menu_runner);
#endif
private:
std::unique_ptr<ui::TouchEditingControllerFactory>
editing_controller_factory_;
#if defined(USE_AURA)
std::unique_ptr<TouchSelectionMenuRunnerViews> touch_selection_menu_runner_;
#endif
NativeWidgetFactory native_widget_factory_;
};
} // namespace views
#endif // UI_VIEWS_VIEWS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_delegate.h | C++ | unknown | 7,484 |
// 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_VIEWS_EXPORT_H_
#define UI_VIEWS_VIEWS_EXPORT_H_
// Defines VIEWS_EXPORT so that functionality implemented by the Views module
// can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(VIEWS_IMPLEMENTATION)
#define VIEWS_EXPORT __declspec(dllexport)
#else
#define VIEWS_EXPORT __declspec(dllimport)
#endif // defined(VIEWS_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(VIEWS_IMPLEMENTATION)
#define VIEWS_EXPORT __attribute__((visibility("default")))
#else
#define VIEWS_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define VIEWS_EXPORT
#endif
#endif // UI_VIEWS_VIEWS_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_export.h | C | unknown | 801 |
// 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/views_features.h"
#include "base/feature_list.h"
#include "build/build_config.h"
namespace views::features {
// Please keep alphabetized.
// Use a high-contrast style for ink drops when in platform high-contrast mode,
// including full opacity and a high-contrast color
BASE_FEATURE(kEnablePlatformHighContrastInkDrop,
"EnablePlatformHighContrastInkDrop",
base::FEATURE_DISABLED_BY_DEFAULT);
// Only paint views that are invalidated/dirty (i.e. a paint was directly
// scheduled on those views) as opposed to painting all views that intersect
// an invalid rectangle on the layer.
BASE_FEATURE(kEnableViewPaintOptimization,
"EnableViewPaintOptimization",
base::FEATURE_DISABLED_BY_DEFAULT);
// When enabled, widgets will be shown based on their z-order level
BASE_FEATURE(kWidgetLayering,
"WidgetLayering",
base::FEATURE_ENABLED_BY_DEFAULT);
} // namespace views::features
| Zhao-PengFei35/chromium_src_4 | ui/views/views_features.cc | C++ | unknown | 1,122 |
// 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_VIEWS_FEATURES_H_
#define UI_VIEWS_VIEWS_FEATURES_H_
#include "base/feature_list.h"
#include "build/build_config.h"
#include "ui/views/views_export.h"
namespace views::features {
// Please keep alphabetized.
VIEWS_EXPORT BASE_DECLARE_FEATURE(kEnablePlatformHighContrastInkDrop);
VIEWS_EXPORT BASE_DECLARE_FEATURE(kEnableViewPaintOptimization);
VIEWS_EXPORT BASE_DECLARE_FEATURE(kWidgetLayering);
} // namespace views::features
#endif // UI_VIEWS_VIEWS_FEATURES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_features.h | C++ | unknown | 632 |
// 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 "base/functional/bind.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "mojo/core/embedder/embedder.h"
#include "ui/views/views_test_suite.h"
int main(int argc, char** argv) {
views::ViewsTestSuite test_suite(argc, argv);
mojo::core::Init();
return base::LaunchUnitTestsSerially(
argc, argv,
base::BindOnce(&views::ViewsTestSuite::Run,
base::Unretained(&test_suite)));
}
| Zhao-PengFei35/chromium_src_4 | ui/views/views_perftests.cc | C++ | unknown | 578 |
// 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/views_switches.h"
#include "build/build_config.h"
namespace views::switches {
// Please keep alphabetized.
// Disables the disregarding of potentially unintended input events such as
// button clicks that happen instantly after the button is shown. Use this for
// integration tests that do automated clicks etc.
const char kDisableInputEventActivationProtectionForTesting[] =
"disable-input-event-activation-protection";
// Draws a semitransparent rect to indicate the bounds of each view.
const char kDrawViewBoundsRects[] = "draw-view-bounds-rects";
// Captures stack traces on View construction to provide better debug info.
const char kViewStackTraces[] = "view-stack-traces";
} // namespace views::switches
| Zhao-PengFei35/chromium_src_4 | ui/views/views_switches.cc | C++ | unknown | 888 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_VIEWS_SWITCHES_H_
#define UI_VIEWS_VIEWS_SWITCHES_H_
#include "build/build_config.h"
#include "ui/views/views_export.h"
namespace views::switches {
// Please keep alphabetized.
VIEWS_EXPORT extern const char
kDisableInputEventActivationProtectionForTesting[];
VIEWS_EXPORT extern const char kDrawViewBoundsRects[];
VIEWS_EXPORT extern const char kViewStackTraces[];
} // namespace views::switches
#endif // UI_VIEWS_VIEWS_SWITCHES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_switches.h | C++ | unknown | 606 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/views_test_suite.h"
#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
#include "build/chromeos_buildflags.h"
#include "gpu/ipc/service/image_transport_surface.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gl/test/gl_surface_test_support.h"
#if defined(USE_AURA)
#include <memory>
#include "ui/aura/env.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "base/command_line.h"
#include "ui/gl/gl_switches.h"
#endif
namespace views {
ViewsTestSuite::ViewsTestSuite(int argc, char** argv)
: base::TestSuite(argc, argv), argc_(argc), argv_(argv) {}
ViewsTestSuite::~ViewsTestSuite() = default;
int ViewsTestSuite::RunTests() {
return base::LaunchUnitTests(
argc_, argv_,
base::BindOnce(&ViewsTestSuite::Run, base::Unretained(this)));
}
int ViewsTestSuite::RunTestsSerially() {
return base::LaunchUnitTestsSerially(
argc_, argv_,
base::BindOnce(&ViewsTestSuite::Run, base::Unretained(this)));
}
void ViewsTestSuite::Initialize() {
base::TestSuite::Initialize();
#if BUILDFLAG(IS_CHROMEOS_ASH) && defined(MEMORY_SANITIZER)
// Force software-gl. This is necessary for mus tests to avoid an msan warning
// in gl init.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kOverrideUseSoftwareGLForTests);
#endif
gl::GLSurfaceTestSupport::InitializeOneOff();
ui::RegisterPathProvider();
base::FilePath ui_test_pak_path;
ASSERT_TRUE(base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
#if defined(USE_AURA)
InitializeEnv();
#endif
}
void ViewsTestSuite::Shutdown() {
#if defined(USE_AURA)
DestroyEnv();
#endif
ui::ResourceBundle::CleanupSharedInstance();
base::TestSuite::Shutdown();
}
#if defined(USE_AURA)
void ViewsTestSuite::InitializeEnv() {
env_ = aura::Env::CreateInstance();
}
void ViewsTestSuite::DestroyEnv() {
env_.reset();
}
#endif
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/views_test_suite.cc | C++ | unknown | 2,326 |
// 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_VIEWS_TEST_SUITE_H_
#define UI_VIEWS_VIEWS_TEST_SUITE_H_
#include "base/memory/raw_ptr.h"
#include "base/test/test_suite.h"
#include "build/build_config.h"
#if defined(USE_AURA)
#include <memory>
namespace aura {
class Env;
}
#endif
namespace views {
class ViewsTestSuite : public base::TestSuite {
public:
ViewsTestSuite(int argc, char** argv);
ViewsTestSuite(const ViewsTestSuite&) = delete;
ViewsTestSuite& operator=(const ViewsTestSuite&) = delete;
~ViewsTestSuite() override;
int RunTests();
int RunTestsSerially();
protected:
// base::TestSuite:
void Initialize() override;
void Shutdown() override;
#if defined(USE_AURA)
// Different test suites may wish to create Env differently.
virtual void InitializeEnv();
virtual void DestroyEnv();
#endif
private:
#if defined(USE_AURA)
std::unique_ptr<aura::Env> env_;
#endif
int argc_;
raw_ptr<char*> argv_;
};
} // namespace views
#endif // UI_VIEWS_VIEWS_TEST_SUITE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_test_suite.h | C++ | unknown | 1,131 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_VIEWS_TOUCH_SELECTION_CONTROLLER_FACTORY_H_
#define UI_VIEWS_VIEWS_TOUCH_SELECTION_CONTROLLER_FACTORY_H_
#include "ui/base/pointer/touch_editing_controller.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT ViewsTouchEditingControllerFactory
: public ui::TouchEditingControllerFactory {
public:
ViewsTouchEditingControllerFactory();
// Overridden from ui::TouchEditingControllerFactory.
ui::TouchEditingControllerDeprecated* Create(
ui::TouchEditable* client_view) override;
};
} // namespace views
#endif // UI_VIEWS_VIEWS_TOUCH_SELECTION_CONTROLLER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/views_touch_selection_controller_factory.h | C++ | unknown | 772 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/views_touch_selection_controller_factory.h"
#include "ui/views/touchui/touch_selection_controller_impl.h"
namespace views {
ViewsTouchEditingControllerFactory::ViewsTouchEditingControllerFactory() =
default;
ui::TouchEditingControllerDeprecated*
ViewsTouchEditingControllerFactory::Create(ui::TouchEditable* client_view) {
return new views::TouchSelectionControllerImpl(client_view);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/views_touch_selection_controller_factory_aura.cc | C++ | unknown | 582 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/views_touch_selection_controller_factory.h"
namespace views {
ViewsTouchEditingControllerFactory::ViewsTouchEditingControllerFactory() =
default;
ui::TouchEditingControllerDeprecated*
ViewsTouchEditingControllerFactory::Create(ui::TouchEditable* client_view) {
return nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/views_touch_selection_controller_factory_mac.cc | C++ | unknown | 474 |
// 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/widget/any_widget_observer.h"
#include "base/functional/bind.h"
#include "ui/views/widget/any_widget_observer_singleton.h"
#include "ui/views/widget/widget.h"
namespace views {
AnyWidgetObserver::AnyWidgetObserver(AnyWidgetPasskey passkey)
: AnyWidgetObserver() {}
AnyWidgetObserver::AnyWidgetObserver(test::AnyWidgetTestPasskey passkey)
: AnyWidgetObserver() {}
AnyWidgetObserver::AnyWidgetObserver() {
internal::AnyWidgetObserverSingleton::GetInstance()->AddObserver(this);
}
AnyWidgetObserver::~AnyWidgetObserver() {
internal::AnyWidgetObserverSingleton::GetInstance()->RemoveObserver(this);
}
#define PROPAGATE_NOTIFICATION(method, callback) \
void AnyWidgetObserver::method(Widget* widget) { \
if (callback) \
(callback).Run(widget); \
}
PROPAGATE_NOTIFICATION(OnAnyWidgetInitialized, initialized_callback_)
PROPAGATE_NOTIFICATION(OnAnyWidgetShown, shown_callback_)
PROPAGATE_NOTIFICATION(OnAnyWidgetHidden, hidden_callback_)
PROPAGATE_NOTIFICATION(OnAnyWidgetClosing, closing_callback_)
#undef PROPAGATE_NOTIFICATION
NamedWidgetShownWaiter::NamedWidgetShownWaiter(AnyWidgetPasskey passkey,
const std::string& name)
: NamedWidgetShownWaiter(name) {}
NamedWidgetShownWaiter::NamedWidgetShownWaiter(
test::AnyWidgetTestPasskey passkey,
const std::string& name)
: NamedWidgetShownWaiter(name) {}
NamedWidgetShownWaiter::~NamedWidgetShownWaiter() = default;
Widget* NamedWidgetShownWaiter::WaitIfNeededAndGet() {
run_loop_.Run();
DCHECK(widget_);
return widget_;
}
NamedWidgetShownWaiter::NamedWidgetShownWaiter(const std::string& name)
: observer_(views::AnyWidgetPasskey{}), name_(name) {
observer_.set_shown_callback(base::BindRepeating(
&NamedWidgetShownWaiter::OnAnyWidgetShown, base::Unretained(this)));
}
void NamedWidgetShownWaiter::OnAnyWidgetShown(Widget* widget) {
if (widget->GetName() == name_) {
widget_ = widget;
run_loop_.Quit();
}
}
AnyWidgetPasskey::AnyWidgetPasskey() = default;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/any_widget_observer.cc | C++ | unknown | 2,274 |
// 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_WIDGET_ANY_WIDGET_OBSERVER_H_
#define UI_VIEWS_WIDGET_ANY_WIDGET_OBSERVER_H_
#include <string>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list_types.h"
#include "base/run_loop.h"
#include "ui/views/views_export.h"
namespace views {
namespace internal {
class AnyWidgetObserverSingleton;
}
namespace test {
class AnyWidgetTestPasskey;
}
class AnyWidgetPasskey;
class Widget;
// AnyWidgetObserver is used when you want to observe widget changes but don't
// have an easy way to get a reference to the Widget in question, usually
// because it is created behind a layer of abstraction that hides the Widget.
//
// This class should only be used as a last resort - if you find yourself
// reaching for it in production code, it probably means some parts of your
// system aren't coupled enough or your API boundaries are hiding too much. You
// will need review from an owner of this class to add new uses of it, because
// it requires a Passkey to construct it - see //docs/patterns/passkey.md for
// details. Uses in tests can be done freely using
// views::test::AnyWidgetTestPasskey.
//
// This class can be used for waiting for a particular View being shown, as in:
//
// RunLoop run_loop;
// AnyWidgetCallbackObserver observer(views::test::AnyWidgetTestPasskey{});
// Widget* widget;
// observer.set_initialized_callback(
// base::BindLambdaForTesting([&](Widget* w) {
// if (w->GetName() == "MyWidget") {
// widget = w;
// run_loop.Quit();
// }
// }));
// ThingThatCreatesWidget();
// run_loop.Run();
//
// with your widget getting the name "MyWidget" via InitParams::name.
//
// Note: if you're trying to wait for a named widget to be *shown*, there is an
// ergonomic wrapper for that - see NamedWidgetShownWaiter below. You use it
// like this:
//
// NamedWidgetShownWaiter waiter(
// views::test::AnyWidgetTestPasskey{}, "MyWidget");
// ThingThatCreatesAndShowsWidget();
// Widget* widget = waiter.WaitIfNeededAndGet();
//
// This class can also be used to make sure a named widget is _not_ shown, as
// this particular example (intended for testing code) shows:
//
// AnyWidgetCallbackObserver observer(views::test::AnyWidgetTestPasskey{});
// observer.set_shown_callback(
// base::BindLambdaForTesting([&](views::Widget* widget) {
// ASSERT_FALSE(widget->GetName() == "MyWidget");
// }));
//
// TODO(ellyjones): Add Widget::SetDebugName and add a remark about that here.
//
// This allows you to create a test that is robust even if
// ThingThatCreatesAndShowsWidget() later becomes asynchronous, takes a few
// milliseconds, etc.
class VIEWS_EXPORT AnyWidgetObserver : public base::CheckedObserver {
public:
using AnyWidgetCallback = base::RepeatingCallback<void(Widget*)>;
// Using this in production requires an AnyWidgetPasskey, which can only be
// constructed by a list of allowed friend classes...
explicit AnyWidgetObserver(AnyWidgetPasskey passkey);
// ... but for tests or debugging, anyone can construct a
// views::test::AnyWidgetTestPasskey.
explicit AnyWidgetObserver(test::AnyWidgetTestPasskey passkey);
~AnyWidgetObserver() override;
AnyWidgetObserver(const AnyWidgetObserver& other) = delete;
AnyWidgetObserver& operator=(const AnyWidgetObserver& other) = delete;
// This sets the callback for when the Widget has finished initialization and
// is ready to use. This is the first point at which the widget is useable.
void set_initialized_callback(const AnyWidgetCallback& callback) {
initialized_callback_ = callback;
}
// These set the callbacks for when the backing native widget has just been
// asked to change visibility. Note that the native widget may or may not
// actually be drawn on the screen when these callbacks are run, because there
// are more layers of asynchronousness at the OS layer.
void set_shown_callback(const AnyWidgetCallback& callback) {
// Check out NamedWidgetShownWaiter for an alternative to this method.
shown_callback_ = callback;
}
void set_hidden_callback(const AnyWidgetCallback& callback) {
hidden_callback_ = callback;
}
// This sets the callback for when the Widget has decided that it is about to
// close, but not yet begun to tear down the backing native Widget or the
// RootView. This is the last point at which the Widget is in a consistent,
// useable state.
void set_closing_callback(const AnyWidgetCallback& callback) {
closing_callback_ = callback;
}
// These two methods deliberately don't exist:
// void set_created_callback(...)
// void set_destroyed_callback(...)
// They would be called respectively too early and too late in the Widget's
// lifecycle for it to be usefully identified - at construction time the
// Widget has no properties or contents yet (and therefore can't be
// meaningfully identified as "your widget" for test purposes), and at
// destruction time the Widget's state is already partly destroyed by the
// closure process. Both methods are deliberately left out to avoid dangerous
// designs based on them.
private:
friend class internal::AnyWidgetObserverSingleton;
AnyWidgetObserver();
// Called from the singleton to propagate events to each AnyWidgetObserver.
void OnAnyWidgetInitialized(Widget* widget);
void OnAnyWidgetShown(Widget* widget);
void OnAnyWidgetHidden(Widget* widget);
void OnAnyWidgetClosing(Widget* widget);
AnyWidgetCallback initialized_callback_;
AnyWidgetCallback shown_callback_;
AnyWidgetCallback hidden_callback_;
AnyWidgetCallback closing_callback_;
};
// NamedWidgetShownWaiter provides a more ergonomic way to do the most common
// thing clients want to use AnyWidgetObserver for: waiting for a Widget with a
// specific name to be shown. Use it like:
//
// NamedWidgetShownWaiter waiter(Passkey{}, "MyDialogView");
// ThingThatShowsDialog();
// Widget* dialog_widget = waiter.WaitIfNeededAndGet();
//
// It is important that NamedWidgetShownWaiter be constructed before any code
// that might show the named Widget, because if the Widget is shown before the
// waiter is constructed, the waiter won't have observed the show and will
// instead hang forever. Worse, if the widget *sometimes* shows before the
// waiter is constructed and sometimes doesn't, you will be introducing flake.
// THIS IS A DANGEROUS PATTERN, DON'T DO THIS:
//
// ThingThatShowsDialogAsynchronously();
// NamedWidgetShownWaiter waiter(...);
// waiter.WaitIfNeededAndGet();
class VIEWS_EXPORT NamedWidgetShownWaiter {
public:
NamedWidgetShownWaiter(AnyWidgetPasskey passkey, const std::string& name);
NamedWidgetShownWaiter(test::AnyWidgetTestPasskey passkey,
const std::string& name);
virtual ~NamedWidgetShownWaiter();
Widget* WaitIfNeededAndGet();
private:
explicit NamedWidgetShownWaiter(const std::string& name);
void OnAnyWidgetShown(Widget* widget);
AnyWidgetObserver observer_;
raw_ptr<Widget, DanglingUntriaged> widget_ = nullptr;
base::RunLoop run_loop_;
const std::string name_;
};
class AnyWidgetPasskey {
private:
AnyWidgetPasskey(); // NOLINT
// Add friend classes here that are allowed to use AnyWidgetObserver in
// production code.
friend class NamedWidgetShownWaiter;
};
namespace test {
// A passkey class to allow tests to use AnyWidgetObserver without needing a
// views owner signoff.
class AnyWidgetTestPasskey {
public:
AnyWidgetTestPasskey() = default;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_WIDGET_ANY_WIDGET_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/any_widget_observer.h | C++ | unknown | 7,844 |
// 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/widget/any_widget_observer_singleton.h"
#include "ui/views/widget/any_widget_observer.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
namespace views::internal {
// static
AnyWidgetObserverSingleton* AnyWidgetObserverSingleton::GetInstance() {
static base::NoDestructor<AnyWidgetObserverSingleton> observer;
return observer.get();
}
#define PROPAGATE_NOTIFICATION(method) \
void AnyWidgetObserverSingleton::method(Widget* widget) { \
for (AnyWidgetObserver & obs : observers_) \
obs.method(widget); \
}
PROPAGATE_NOTIFICATION(OnAnyWidgetInitialized)
PROPAGATE_NOTIFICATION(OnAnyWidgetShown)
PROPAGATE_NOTIFICATION(OnAnyWidgetHidden)
PROPAGATE_NOTIFICATION(OnAnyWidgetClosing)
#undef PROPAGATE_NOTIFICATION
void AnyWidgetObserverSingleton::AddObserver(AnyWidgetObserver* observer) {
observers_.AddObserver(observer);
}
void AnyWidgetObserverSingleton::RemoveObserver(AnyWidgetObserver* observer) {
observers_.RemoveObserver(observer);
}
AnyWidgetObserverSingleton::AnyWidgetObserverSingleton() = default;
AnyWidgetObserverSingleton::~AnyWidgetObserverSingleton() = default;
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/any_widget_observer_singleton.cc | C++ | unknown | 1,387 |
// 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_WIDGET_ANY_WIDGET_OBSERVER_SINGLETON_H_
#define UI_VIEWS_WIDGET_ANY_WIDGET_OBSERVER_SINGLETON_H_
#include "base/no_destructor.h"
#include "base/observer_list.h"
namespace views {
class AnyWidgetObserver;
class Widget;
namespace internal {
// This is not the class you want - go look at AnyWidgetObserver.
// This class serves as the "thing being observed" by AnyWidgetObservers,
// since there is no relevant singleton for Widgets. Every Widget notifies the
// singleton instance of this class of its creation, and it handles notifying
// all AnyWidgetObservers of that.
class AnyWidgetObserverSingleton {
public:
static AnyWidgetObserverSingleton* GetInstance();
void OnAnyWidgetInitialized(Widget* widget);
void OnAnyWidgetShown(Widget* widget);
void OnAnyWidgetHidden(Widget* widget);
void OnAnyWidgetClosing(Widget* widget);
void AddObserver(AnyWidgetObserver* observer);
void RemoveObserver(AnyWidgetObserver* observer);
private:
friend class base::NoDestructor<AnyWidgetObserverSingleton>;
AnyWidgetObserverSingleton();
~AnyWidgetObserverSingleton();
base::ObserverList<AnyWidgetObserver> observers_;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_WIDGET_ANY_WIDGET_OBSERVER_SINGLETON_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/any_widget_observer_singleton.h | C++ | unknown | 1,415 |
// 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/widget/any_widget_observer.h"
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
namespace {
using views::Widget;
using AnyWidgetObserverTest = views::test::WidgetTest;
TEST_F(AnyWidgetObserverTest, ObservesInitialize) {
views::AnyWidgetObserver observer(views::test::AnyWidgetTestPasskey{});
bool initialized = false;
observer.set_initialized_callback(
base::BindLambdaForTesting([&](Widget*) { initialized = true; }));
EXPECT_FALSE(initialized);
WidgetAutoclosePtr w0(WidgetTest::CreateTopLevelPlatformWidget());
EXPECT_TRUE(initialized);
}
TEST_F(AnyWidgetObserverTest, ObservesClose) {
views::AnyWidgetObserver observer(views::test::AnyWidgetTestPasskey{});
bool closing = false;
observer.set_closing_callback(
base::BindLambdaForTesting([&](Widget*) { closing = true; }));
EXPECT_FALSE(closing);
{ WidgetAutoclosePtr w0(WidgetTest::CreateTopLevelPlatformWidget()); }
EXPECT_TRUE(closing);
}
TEST_F(AnyWidgetObserverTest, ObservesShow) {
views::AnyWidgetObserver observer(views::test::AnyWidgetTestPasskey{});
bool shown = false;
observer.set_shown_callback(
base::BindLambdaForTesting([&](Widget*) { shown = true; }));
EXPECT_FALSE(shown);
WidgetAutoclosePtr w0(WidgetTest::CreateTopLevelPlatformWidget());
w0->Show();
EXPECT_TRUE(shown);
}
TEST_F(AnyWidgetObserverTest, ObservesHide) {
views::AnyWidgetObserver observer(views::test::AnyWidgetTestPasskey{});
bool hidden = false;
observer.set_hidden_callback(
base::BindLambdaForTesting([&](Widget*) { hidden = true; }));
EXPECT_FALSE(hidden);
WidgetAutoclosePtr w0(WidgetTest::CreateTopLevelPlatformWidget());
w0->Hide();
EXPECT_TRUE(hidden);
}
class NamedWidgetShownWaiterTest : public views::test::WidgetTest {
public:
NamedWidgetShownWaiterTest() = default;
~NamedWidgetShownWaiterTest() override = default;
views::Widget* CreateNamedWidget(const std::string& name) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget = views::test::CreatePlatformNativeWidgetImpl(
widget, views::test::kStubCapture, nullptr);
params.name = name;
widget->Init(std::move(params));
return widget;
}
};
TEST_F(NamedWidgetShownWaiterTest, ShownAfterWait) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"TestWidget");
WidgetAutoclosePtr w0(CreateNamedWidget("TestWidget"));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce([](views::Widget* widget) { widget->Show(); },
base::Unretained(w0.get())));
EXPECT_EQ(waiter.WaitIfNeededAndGet(), w0.get());
}
TEST_F(NamedWidgetShownWaiterTest, ShownBeforeWait) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"TestWidget");
WidgetAutoclosePtr w0(CreateNamedWidget("TestWidget"));
w0->Show();
EXPECT_EQ(waiter.WaitIfNeededAndGet(), w0.get());
}
TEST_F(NamedWidgetShownWaiterTest, ShownInactive) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"TestWidget");
WidgetAutoclosePtr w0(CreateNamedWidget("TestWidget"));
w0->ShowInactive();
EXPECT_EQ(waiter.WaitIfNeededAndGet(), w0.get());
}
TEST_F(NamedWidgetShownWaiterTest, OtherWidgetShown) {
views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
"TestWidget");
WidgetAutoclosePtr w0(CreateNamedWidget("NotTestWidget"));
WidgetAutoclosePtr w1(CreateNamedWidget("TestWidget"));
w0->Show();
w1->Show();
EXPECT_EQ(waiter.WaitIfNeededAndGet(), w1.get());
}
} // namespace
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/any_widget_observer_unittest.cc | C++ | unknown | 4,185 |
// 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 <memory>
#import <Accessibility/Accessibility.h>
#import <Cocoa/Cocoa.h>
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#import "testing/gtest_mac.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#import "ui/accessibility/platform/ax_platform_node_mac.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/models/combobox_model.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
NSString* const kTestPlaceholderText = @"Test placeholder text";
NSString* const kTestStringValue = @"Test string value";
constexpr int kTestStringLength = 17;
NSString* const kTestRTLStringValue = @"אבגדהוזאבגדהוז";
NSString* const kTestTitle = @"Test textfield";
id<NSAccessibility> ToNSAccessibility(id obj) {
return [obj conformsToProtocol:@protocol(NSAccessibility)] ? obj : nil;
}
id<NSAccessibility> AXParentOf(id<NSAccessibility> child) {
return ToNSAccessibility(child.accessibilityParent);
}
bool AXObjectHandlesSelector(id<NSAccessibility> ax_obj, SEL action) {
return [ax_obj respondsToSelector:action] &&
[ax_obj isAccessibilitySelectorAllowed:action];
}
class FlexibleRoleTestView : public View {
public:
explicit FlexibleRoleTestView(ax::mojom::Role role) : role_(role) {}
FlexibleRoleTestView(const FlexibleRoleTestView&) = delete;
FlexibleRoleTestView& operator=(const FlexibleRoleTestView&) = delete;
void set_role(ax::mojom::Role role) { role_ = role; }
// Add a child view and resize to fit the child.
void FitBoundsToNewChild(View* view) {
AddChildView(view);
// Fit the parent widget to the size of the child for accurate hit tests.
SetBoundsRect(view->bounds());
}
bool mouse_was_pressed() const { return mouse_was_pressed_; }
// View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
View::GetAccessibleNodeData(node_data);
node_data->role = role_;
}
bool OnMousePressed(const ui::MouseEvent& event) override {
mouse_was_pressed_ = true;
return false;
}
private:
ax::mojom::Role role_;
bool mouse_was_pressed_ = false;
};
class TestLabelButton : public LabelButton {
public:
TestLabelButton() {
// Make sure the label doesn't cover the hit test co-ordinates.
label()->SetSize(gfx::Size(1, 1));
}
TestLabelButton(const TestLabelButton&) = delete;
TestLabelButton& operator=(const TestLabelButton&) = delete;
using LabelButton::label;
};
class TestWidgetDelegate : public test::TestDesktopWidgetDelegate {
public:
TestWidgetDelegate() = default;
TestWidgetDelegate(const TestWidgetDelegate&) = delete;
TestWidgetDelegate& operator=(const TestWidgetDelegate&) = delete;
static constexpr char16_t kAccessibleWindowTitle[] = u"My Accessible Window";
// WidgetDelegate:
std::u16string GetAccessibleWindowTitle() const override {
return kAccessibleWindowTitle;
}
};
constexpr char16_t TestWidgetDelegate::kAccessibleWindowTitle[];
// Widget-level tests for accessibility properties - these are actually mostly
// tests of accessibility behavior for individual Views *as they appear* in
// Widgets.
class AXNativeWidgetMacTest : public test::WidgetTest {
public:
AXNativeWidgetMacTest() = default;
AXNativeWidgetMacTest(const AXNativeWidgetMacTest&) = delete;
AXNativeWidgetMacTest& operator=(const AXNativeWidgetMacTest&) = delete;
void SetUp() override {
test::WidgetTest::SetUp();
widget_delegate_.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
widget()->Show();
}
void TearDown() override {
widget()->CloseNow();
test::WidgetTest::TearDown();
}
id<NSAccessibility> A11yElementAtMidpoint() {
// Accessibility hit tests come in Cocoa screen coordinates.
NSPoint midpoint_in_screen_ = gfx::ScreenPointToNSPoint(
widget()->GetWindowBoundsInScreen().CenterPoint());
return ToNSAccessibility([widget()->GetNativeWindow().GetNativeNSWindow()
accessibilityHitTest:midpoint_in_screen_]);
}
Textfield* AddChildTextfield(const gfx::Size& size) {
Textfield* textfield = new Textfield;
textfield->SetText(base::SysNSStringToUTF16(kTestStringValue));
textfield->SetAccessibleName(base::SysNSStringToUTF16(kTestTitle));
textfield->SetSize(size);
widget()->GetContentsView()->AddChildView(textfield);
return textfield;
}
Widget* widget() { return widget_delegate_.GetWidget(); }
gfx::Rect GetWidgetBounds() {
return widget()->GetClientAreaBoundsInScreen();
}
private:
TestWidgetDelegate widget_delegate_;
};
} // namespace
// Test that all methods in the NSAccessibility informal protocol can be called
// on a retained accessibility object after the source view is deleted.
TEST_F(AXNativeWidgetMacTest, Lifetime) {
Textfield* view = AddChildTextfield(widget()->GetContentsView()->size());
base::scoped_nsobject<NSObject> ax_node(view->GetNativeViewAccessible(),
base::scoped_policy::RETAIN);
id<NSAccessibility> ax_obj = ToNSAccessibility(ax_node.get());
EXPECT_TRUE(AXObjectHandlesSelector(ax_obj, @selector(accessibilityValue)));
EXPECT_NSEQ(kTestStringValue, ax_obj.accessibilityValue);
EXPECT_TRUE(
AXObjectHandlesSelector(ax_obj, @selector(setAccessibilityValue:)));
EXPECT_TRUE(
AXObjectHandlesSelector(ax_obj, @selector(accessibilityPerformShowMenu)));
EXPECT_TRUE(ax_obj.isAccessibilityElement);
EXPECT_TRUE(
AXObjectHandlesSelector(ax_obj, @selector(accessibilityStringForRange:)));
NSRange range = NSMakeRange(0, kTestStringLength);
EXPECT_NSEQ(kTestStringValue, [ax_obj accessibilityStringForRange:range]);
// The following is also "not implemented", but the informal protocol category
// provides a default implementation.
EXPECT_EQ(NSNotFound, static_cast<NSInteger>(
[ax_node accessibilityIndexOfChild:ax_node]));
// The only usually available array attribute is AXChildren, so go up a level
// to the Widget to test that a bit. The default implementation just gets the
// attribute normally and returns its size (if it's an array).
base::scoped_nsprotocol<id<NSAccessibility>> ax_parent(
ax_obj.accessibilityParent, base::scoped_policy::RETAIN);
// There are two children: a NativeFrameView and the TextField.
EXPECT_EQ(2u, ax_parent.get().accessibilityChildren.count);
EXPECT_EQ(ax_node.get(), ax_parent.get().accessibilityChildren[1]);
// If it is not an array, the default implementation throws an exception, so
// it's impossible to test these methods further on |ax_node|, apart from the
// following, before deleting the view.
EXPECT_EQ(0u, ax_obj.accessibilityChildren.count);
delete view;
// ax_obj should still respond to setAccessibilityValue: (because the NSObject
// is still live), but isAccessibilitySelectorAllowed: should return NO
// because the backing View is gone. Invoking those selectors, which AppKit
// sometimes does even if the object returns NO from
// isAccessibilitySelectorAllowed:, should not crash.
EXPECT_TRUE([ax_obj respondsToSelector:@selector(setAccessibilityValue:)]);
EXPECT_FALSE(
AXObjectHandlesSelector(ax_obj, @selector(setAccessibilityValue:)));
[ax_obj setAccessibilityValue:kTestStringValue];
EXPECT_FALSE(
AXObjectHandlesSelector(ax_obj, @selector(accessibilityPerformShowMenu)));
[ax_obj accessibilityPerformShowMenu];
EXPECT_FALSE([ax_obj isAccessibilityElement]);
EXPECT_EQ(nil, [ax_node accessibilityHitTest:NSZeroPoint]);
EXPECT_EQ(nil, [ax_node accessibilityFocusedUIElement]);
EXPECT_NSEQ(nil, [ax_obj accessibilityStringForRange:range]);
// Test the attributes with default implementations provided.
EXPECT_EQ(NSNotFound, static_cast<NSInteger>(
[ax_node accessibilityIndexOfChild:ax_node]));
// The Widget is currently still around, but the TextField should be gone,
// leaving just the NativeFrameView.
EXPECT_EQ(1u, ax_parent.get().accessibilityChildren.count);
}
// Check that potentially keyboard-focusable elements are always leaf nodes.
TEST_F(AXNativeWidgetMacTest, FocusableElementsAreLeafNodes) {
// LabelButtons will have a label inside the button. The label should be
// ignored because the button is potentially keyboard focusable.
TestLabelButton* button = new TestLabelButton();
button->SetSize(widget()->GetContentsView()->size());
widget()->GetContentsView()->AddChildView(button);
id<NSAccessibility> ax_button =
ToNSAccessibility(button->GetNativeViewAccessible());
EXPECT_NSEQ(NSAccessibilityButtonRole, ax_button.accessibilityRole);
id<NSAccessibility> ax_label =
ToNSAccessibility(button->label()->GetNativeViewAccessible());
EXPECT_EQ(0u, ax_button.accessibilityChildren.count);
// The exception is if the child is explicitly marked accessibility focusable.
button->label()->SetFocusBehavior(View::FocusBehavior::ACCESSIBLE_ONLY);
EXPECT_EQ(1u, ax_button.accessibilityChildren.count);
EXPECT_NSEQ(ax_label, ax_button.accessibilityChildren[0]);
// If the child is disabled, it should still be traversable.
button->label()->SetEnabled(false);
EXPECT_EQ(1u, ax_button.accessibilityChildren.count);
EXPECT_EQ(ax_label, ax_button.accessibilityChildren[0]);
}
// Test for NSAccessibilityChildrenAttribute, and ensure it excludes ignored
// children from the accessibility tree.
TEST_F(AXNativeWidgetMacTest, ChildrenAttribute) {
// The ContentsView initially has a single child, a NativeFrameView.
id<NSAccessibility> ax_node =
widget()->GetContentsView()->GetNativeViewAccessible();
EXPECT_EQ(1u, ax_node.accessibilityChildren.count);
const size_t kNumChildren = 3;
for (size_t i = 0; i < kNumChildren; ++i) {
// Make sure the labels won't interfere with the hit test.
AddChildTextfield(gfx::Size());
}
// Having added three non-ignored children, the count is four.
EXPECT_EQ(kNumChildren + 1, ax_node.accessibilityChildren.count);
// Check ignored children don't show up in the accessibility tree.
widget()->GetContentsView()->AddChildView(
new FlexibleRoleTestView(ax::mojom::Role::kNone));
EXPECT_EQ(kNumChildren + 1, ax_node.accessibilityChildren.count);
}
// Test for NSAccessibilityParentAttribute, including for a Widget with no
// parent.
TEST_F(AXNativeWidgetMacTest, ParentAttribute) {
Textfield* child = AddChildTextfield(widget()->GetContentsView()->size());
id<NSAccessibility> ax_child = A11yElementAtMidpoint();
id<NSAccessibility> ax_parent = AXParentOf(ax_child);
// Views with Widget parents will have a NSAccessibilityGroupRole parent.
// See https://crbug.com/875843 for more information.
ASSERT_NSNE(nil, ax_parent);
EXPECT_NSEQ(NSAccessibilityGroupRole, ax_parent.accessibilityRole);
// Views with non-Widget parents will have the role of the parent view.
widget()->GetContentsView()->RemoveChildView(child);
FlexibleRoleTestView* parent =
new FlexibleRoleTestView(ax::mojom::Role::kGroup);
parent->FitBoundsToNewChild(child);
widget()->GetContentsView()->AddChildView(parent);
// These might have been invalidated by the View gyrations just above, so
// recompute them.
ax_child = A11yElementAtMidpoint();
ax_parent = AXParentOf(ax_child);
EXPECT_NSEQ(NSAccessibilityGroupRole, ax_parent.accessibilityRole);
// Test an ignored role parent is skipped in favor of the grandparent.
parent->set_role(ax::mojom::Role::kNone);
ASSERT_NSNE(nil, AXParentOf(ax_child));
EXPECT_NSEQ(NSAccessibilityGroupRole, AXParentOf(ax_child).accessibilityRole);
}
// Test for NSAccessibilityPositionAttribute, including on Widget movement
// updates.
TEST_F(AXNativeWidgetMacTest, PositionAttribute) {
NSPoint widget_origin =
gfx::ScreenPointToNSPoint(GetWidgetBounds().bottom_left());
EXPECT_NSEQ(widget_origin, A11yElementAtMidpoint().accessibilityFrame.origin);
// Check the attribute is updated when the Widget is moved.
gfx::Rect new_bounds(60, 80, 100, 100);
widget()->SetBounds(new_bounds);
widget_origin = gfx::ScreenPointToNSPoint(new_bounds.bottom_left());
EXPECT_NSEQ(widget_origin, A11yElementAtMidpoint().accessibilityFrame.origin);
}
// Test for surfacing information in TooltipText.
TEST_F(AXNativeWidgetMacTest, TooltipText) {
Label* label = new Label(base::SysNSStringToUTF16(kTestStringValue));
label->SetSize(GetWidgetBounds().size());
EXPECT_NSEQ(nil, A11yElementAtMidpoint().accessibilityHelp);
label->SetTooltipText(base::SysNSStringToUTF16(kTestPlaceholderText));
widget()->GetContentsView()->AddChildView(label);
// The tooltip is exposed in accessibilityHelp only before macOS 11. After,
// it is accessibilityCustomContent. This is because the DescriptionFrom
// for the ToolTip string has been been set to kAriaDescription, and
// `aria-description` is exposed in AXCustomContent.
id<NSAccessibility> element = A11yElementAtMidpoint();
if (@available(macOS 11.0, *)) {
NSString* description = nil;
ASSERT_TRUE(
[element conformsToProtocol:@protocol(AXCustomContentProvider)]);
auto element_with_content =
static_cast<id<AXCustomContentProvider>>(element);
for (AXCustomContent* content in element_with_content
.accessibilityCustomContent) {
if ([content.label isEqualToString:@"description"]) {
// There should be only one AXCustomContent with the label
// "description".
EXPECT_EQ(description, nil);
description = content.value;
}
}
EXPECT_NSEQ(kTestPlaceholderText, description);
} else {
EXPECT_NSEQ(kTestPlaceholderText, element.accessibilityHelp);
}
}
// Test view properties that should report the native NSWindow, and test
// specific properties on that NSWindow.
TEST_F(AXNativeWidgetMacTest, NativeWindowProperties) {
FlexibleRoleTestView* view =
new FlexibleRoleTestView(ax::mojom::Role::kGroup);
view->SetSize(GetWidgetBounds().size());
widget()->GetContentsView()->AddChildView(view);
id<NSAccessibility> ax_view = A11yElementAtMidpoint();
// Make sure it's |view| in the hit test by checking its accessibility role.
EXPECT_EQ(NSAccessibilityGroupRole, ax_view.accessibilityRole);
NSWindow* window = widget()->GetNativeWindow().GetNativeNSWindow();
EXPECT_NSEQ(window, ax_view.accessibilityWindow);
EXPECT_NSEQ(window, ax_view.accessibilityTopLevelUIElement);
EXPECT_NSEQ(
base::SysUTF16ToNSString(TestWidgetDelegate::kAccessibleWindowTitle),
window.accessibilityTitle);
}
// Tests for accessibility attributes on a views::Textfield.
// TODO(patricialor): Test against Cocoa-provided attributes as well to ensure
// consistency between Cocoa and toolkit-views.
TEST_F(AXNativeWidgetMacTest, TextfieldGenericAttributes) {
Textfield* textfield = AddChildTextfield(GetWidgetBounds().size());
id<NSAccessibility> ax_obj = A11yElementAtMidpoint();
// NSAccessibilityEnabledAttribute.
textfield->SetEnabled(false);
EXPECT_EQ(NO, ax_obj.isAccessibilityEnabled);
textfield->SetEnabled(true);
EXPECT_EQ(YES, ax_obj.isAccessibilityEnabled);
// NSAccessibilityFocusedAttribute.
EXPECT_EQ(NO, ax_obj.isAccessibilityFocused);
textfield->RequestFocus();
EXPECT_EQ(YES, ax_obj.isAccessibilityFocused);
// NSAccessibilityTitleAttribute, NSAccessibilityLabelAttribute.
// https://developer.apple.com/documentation/appkit/nsaccessibilityprotocol
// * accessibilityTitle() returns the title of the accessibility element,
// for example a button's visible text.
// * accessibilityLabel() returns a short description of the accessibility
// element.
// Textfield::SetAssociatedLabel() is what should be used if the textfield
// has a visible label. Because AddChildTextfield() uses SetAccessibleName()
// to set the accessible name to a flat string, the title should be exposed
// via accessibilityLabel() instead of accessibilityTitle();
EXPECT_NSEQ(@"", ax_obj.accessibilityTitle);
EXPECT_NSEQ(kTestTitle, ax_obj.accessibilityLabel);
EXPECT_NSEQ(kTestStringValue, ax_obj.accessibilityValue);
// NSAccessibilityRoleAttribute,
// NSAccessibilitySubroleAttribute and
// NSAccessibilityRoleDescriptionAttribute.
EXPECT_NSEQ(NSAccessibilityTextFieldRole, ax_obj.accessibilityRole);
EXPECT_NSEQ(nil, ax_obj.accessibilitySubrole);
NSString* role_description =
NSAccessibilityRoleDescription(NSAccessibilityTextFieldRole, nil);
EXPECT_NSEQ(role_description, ax_obj.accessibilityRoleDescription);
// Test accessibility clients can see subroles as well.
textfield->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
EXPECT_NSEQ(NSAccessibilitySecureTextFieldSubrole,
ax_obj.accessibilitySubrole);
role_description = NSAccessibilityRoleDescription(
NSAccessibilityTextFieldRole, NSAccessibilitySecureTextFieldSubrole);
EXPECT_NSEQ(role_description, ax_obj.accessibilityRoleDescription);
// Expect to see the action to show a context menu.
EXPECT_TRUE(AXObjectHandlesSelector(A11yElementAtMidpoint(),
@selector(accessibilityPerformShowMenu)));
// NSAccessibilitySizeAttribute.
EXPECT_EQ(GetWidgetBounds().size(),
gfx::Size(ax_obj.accessibilityFrame.size));
// Check the attribute is updated when the Widget is resized.
gfx::Size new_size(200, 40);
textfield->SetSize(new_size);
EXPECT_EQ(new_size, gfx::Size(ax_obj.accessibilityFrame.size));
}
TEST_F(AXNativeWidgetMacTest, TextfieldEditableAttributes) {
Textfield* textfield = AddChildTextfield(GetWidgetBounds().size());
textfield->SetPlaceholderText(base::SysNSStringToUTF16(kTestPlaceholderText));
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
// NSAccessibilityInsertionPointLineNumberAttribute.
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
// NSAccessibilityNumberOfCharactersAttribute.
EXPECT_EQ(kTestStringValue.length,
static_cast<NSUInteger>(ax_node.accessibilityNumberOfCharacters));
// NSAccessibilityPlaceholderAttribute.
EXPECT_NSEQ(kTestPlaceholderText, ax_node.accessibilityPlaceholderValue);
// NSAccessibilitySelectedTextAttribute and
// NSAccessibilitySelectedTextRangeAttribute.
EXPECT_NSEQ(@"", ax_node.accessibilitySelectedText);
// The cursor will be at the end of the textfield, so the selection range will
// span 0 characters and be located at the index after the last character.
EXPECT_NSEQ(NSMakeRange(kTestStringValue.length, 0),
ax_node.accessibilitySelectedTextRange);
// Select some text in the middle of the textfield.
const gfx::Range forward_range(2, 6);
const NSRange ns_range = forward_range.ToNSRange();
textfield->SetSelectedRange(forward_range);
EXPECT_NSEQ([kTestStringValue substringWithRange:ns_range],
ax_node.accessibilitySelectedText);
EXPECT_EQ(textfield->GetSelectedText(),
base::SysNSStringToUTF16(ax_node.accessibilitySelectedText));
EXPECT_EQ(forward_range, gfx::Range(ax_node.accessibilitySelectedTextRange));
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
const gfx::Range reversed_range(6, 2);
textfield->SetSelectedRange(reversed_range);
// NSRange has no direction, so these are unchanged from the forward range.
EXPECT_NSEQ([kTestStringValue substringWithRange:ns_range],
ax_node.accessibilitySelectedText);
EXPECT_EQ(textfield->GetSelectedText(),
base::SysNSStringToUTF16(ax_node.accessibilitySelectedText));
EXPECT_EQ(forward_range, gfx::Range(ax_node.accessibilitySelectedTextRange));
// NSAccessibilityVisibleCharacterRangeAttribute.
EXPECT_EQ(gfx::Range(0, kTestStringValue.length),
gfx::Range(ax_node.accessibilityVisibleCharacterRange));
// accessibilityLineForIndex:
EXPECT_EQ(0, [ax_node accessibilityLineForIndex:3]);
// accessibilityStringForRange:
EXPECT_NSEQ(@"string",
[ax_node accessibilityStringForRange:NSMakeRange(5, 6)]);
// Test an RTL string.
textfield->SetText(base::SysNSStringToUTF16(kTestRTLStringValue));
textfield->SetSelectedRange(forward_range);
EXPECT_EQ(textfield->GetSelectedText(),
base::SysNSStringToUTF16(ax_node.accessibilitySelectedText));
textfield->SetSelectedRange(reversed_range);
EXPECT_EQ(textfield->GetSelectedText(),
base::SysNSStringToUTF16(ax_node.accessibilitySelectedText));
}
// Test writing accessibility attributes via an accessibility client for normal
// Views.
TEST_F(AXNativeWidgetMacTest, ViewWritableAttributes) {
FlexibleRoleTestView* view =
new FlexibleRoleTestView(ax::mojom::Role::kGroup);
view->SetSize(GetWidgetBounds().size());
widget()->GetContentsView()->AddChildView(view);
// Make sure the accessibility object tested is the correct one.
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
EXPECT_NSEQ(NSAccessibilityGroupRole, ax_node.accessibilityRole);
// Make sure |view| is focusable, then focus/unfocus it.
view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_FALSE(view->HasFocus());
EXPECT_FALSE(ax_node.accessibilityFocused);
EXPECT_TRUE(
AXObjectHandlesSelector(ax_node, @selector(setAccessibilityFocused:)));
ax_node.accessibilityFocused = YES;
EXPECT_TRUE(ax_node.accessibilityFocused);
EXPECT_TRUE(view->HasFocus());
}
// Test writing accessibility attributes via an accessibility client for
// editable controls (in this case, views::Textfields).
TEST_F(AXNativeWidgetMacTest, TextfieldWritableAttributes) {
Textfield* textfield = AddChildTextfield(GetWidgetBounds().size());
// Get the Textfield accessibility object.
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
// Make sure it's the correct accessibility object.
EXPECT_NSEQ(kTestStringValue, ax_node.accessibilityValue);
// Write a new NSAccessibilityValueAttribute.
EXPECT_TRUE(
AXObjectHandlesSelector(ax_node, @selector(setAccessibilityValue:)));
ax_node.accessibilityValue = kTestPlaceholderText;
EXPECT_NSEQ(kTestPlaceholderText, ax_node.accessibilityValue);
EXPECT_EQ(base::SysNSStringToUTF16(kTestPlaceholderText),
textfield->GetText());
// Test a read-only textfield.
textfield->SetReadOnly(true);
EXPECT_FALSE([ax_node
isAccessibilitySelectorAllowed:@selector(setAccessibilityValue:)]);
ax_node.accessibilityValue = kTestStringValue;
EXPECT_NSEQ(kTestPlaceholderText, ax_node.accessibilityValue);
EXPECT_EQ(base::SysNSStringToUTF16(kTestPlaceholderText),
textfield->GetText());
textfield->SetReadOnly(false);
// Change the selection text when there is no selected text.
textfield->SetSelectedRange(gfx::Range(0, 0));
EXPECT_TRUE(AXObjectHandlesSelector(
ax_node, @selector(setAccessibilitySelectedText:)));
NSString* new_string =
[kTestStringValue stringByAppendingString:kTestPlaceholderText];
ax_node.accessibilitySelectedText = kTestStringValue;
EXPECT_NSEQ(new_string, ax_node.accessibilityValue);
EXPECT_EQ(base::SysNSStringToUTF16(new_string), textfield->GetText());
// Replace entire selection.
gfx::Range test_range(0, [new_string length]);
textfield->SetSelectedRange(test_range);
ax_node.accessibilitySelectedText = kTestStringValue;
EXPECT_NSEQ(kTestStringValue, ax_node.accessibilityValue);
EXPECT_EQ(base::SysNSStringToUTF16(kTestStringValue), textfield->GetText());
// Make sure the cursor is at the end of the Textfield.
EXPECT_EQ(gfx::Range([kTestStringValue length]),
textfield->GetSelectedRange());
// Replace a middle section only (with a backwards selection range).
std::u16string front = u"Front ";
std::u16string middle = u"middle";
std::u16string back = u" back";
std::u16string replacement = u"replaced";
textfield->SetText(front + middle + back);
test_range = gfx::Range(front.length() + middle.length(), front.length());
new_string = base::SysUTF16ToNSString(front + replacement + back);
textfield->SetSelectedRange(test_range);
ax_node.accessibilitySelectedText = base::SysUTF16ToNSString(replacement);
EXPECT_NSEQ(new_string, ax_node.accessibilityValue);
EXPECT_EQ(base::SysNSStringToUTF16(new_string), textfield->GetText());
// Make sure the cursor is at the end of the replacement.
EXPECT_EQ(gfx::Range(front.length() + replacement.length()),
textfield->GetSelectedRange());
// Check it's not possible to change the selection range when read-only. Note
// that this behavior is inconsistent with Cocoa - selections can be set via
// a11y in selectable NSTextfields (unless they are password fields).
// https://crbug.com/692362
textfield->SetReadOnly(true);
EXPECT_FALSE([ax_node isAccessibilitySelectorAllowed:@selector
(setAccessibilitySelectedTextRange:)]);
textfield->SetReadOnly(false);
EXPECT_TRUE([ax_node isAccessibilitySelectorAllowed:@selector
(setAccessibilitySelectedTextRange:)]);
// Check whether it's possible to change text in a selection when read-only.
textfield->SetReadOnly(true);
EXPECT_FALSE([ax_node isAccessibilitySelectorAllowed:@selector
(setAccessibilitySelectedTextRange:)]);
textfield->SetReadOnly(false);
EXPECT_TRUE([ax_node isAccessibilitySelectorAllowed:@selector
(setAccessibilitySelectedTextRange:)]);
// Change the selection to a valid range within the text.
ax_node.accessibilitySelectedTextRange = NSMakeRange(2, 5);
EXPECT_EQ(gfx::Range(2, 7), textfield->GetSelectedRange());
// If the length is longer than the value length, default to the max possible.
ax_node.accessibilitySelectedTextRange = NSMakeRange(0, 1000);
EXPECT_EQ(gfx::Range(0, textfield->GetText().length()),
textfield->GetSelectedRange());
// Check just moving the cursor works, too.
ax_node.accessibilitySelectedTextRange = NSMakeRange(5, 0);
EXPECT_EQ(gfx::Range(5, 5), textfield->GetSelectedRange());
}
// Test parameterized text attributes.
TEST_F(AXNativeWidgetMacTest, TextParameterizedAttributes) {
AddChildTextfield(GetWidgetBounds().size());
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
NSInteger line = [ax_node accessibilityLineForIndex:5];
EXPECT_EQ(0, line);
EXPECT_NSEQ(NSMakeRange(0, kTestStringLength),
[ax_node accessibilityRangeForLine:line]);
// The substring "est st" of kTestStringValue.
NSRange test_range = NSMakeRange(1, 6);
EXPECT_NSEQ(@"est st", [ax_node accessibilityStringForRange:test_range]);
EXPECT_NSEQ(
@"est st",
[[ax_node accessibilityAttributedStringForRange:test_range] string]);
// Not implemented yet. Update these tests when they are.
EXPECT_NSEQ(NSMakeRange(0, 0),
[ax_node accessibilityRangeForPosition:NSZeroPoint]);
EXPECT_NSEQ(NSMakeRange(0, 0), [ax_node accessibilityRangeForIndex:4]);
EXPECT_NSEQ(NSZeroRect, [ax_node accessibilityFrameForRange:test_range]);
EXPECT_NSEQ(nil, [ax_node accessibilityRTFForRange:test_range]);
EXPECT_NSEQ(NSMakeRange(0, kTestStringLength),
[ax_node accessibilityStyleRangeForIndex:4]);
}
// Test performing a 'click' on Views with clickable roles work.
TEST_F(AXNativeWidgetMacTest, PressAction) {
FlexibleRoleTestView* view =
new FlexibleRoleTestView(ax::mojom::Role::kButton);
widget()->GetContentsView()->AddChildView(view);
view->SetSize(GetWidgetBounds().size());
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_NSEQ(NSAccessibilityButtonRole, ax_node.accessibilityRole);
[ax_node accessibilityPerformPress];
EXPECT_TRUE(view->mouse_was_pressed());
}
// Test text-specific attributes that should not be supported for protected
// textfields.
TEST_F(AXNativeWidgetMacTest, ProtectedTextfields) {
Textfield* textfield = AddChildTextfield(GetWidgetBounds().size());
textfield->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
// Get the Textfield accessibility object.
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
// Create a native Cocoa NSSecureTextField to compare against.
base::scoped_nsobject<NSSecureTextField> cocoa_secure_textfield(
[[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 10, 10)]);
const SEL expected_supported_selectors[] = {
@selector(accessibilityValue),
@selector(accessibilityPlaceholderValue),
@selector(accessibilityNumberOfCharacters),
@selector(accessibilitySelectedText),
@selector(accessibilitySelectedTextRange),
@selector(accessibilityVisibleCharacterRange),
@selector(accessibilityInsertionPointLineNumber)
};
for (auto* sel : expected_supported_selectors) {
EXPECT_TRUE(AXObjectHandlesSelector(ax_node, sel));
EXPECT_TRUE(AXObjectHandlesSelector(cocoa_secure_textfield.get(), sel));
}
// TODO(https://crbug.com/939965): This should assert the same behavior of
// Views textfields and NSSecureTextField, but right now it can't.
EXPECT_TRUE(
AXObjectHandlesSelector(ax_node, @selector(setAccessibilityValue:)));
EXPECT_NSEQ(NSAccessibilityTextFieldRole, ax_node.accessibilityRole);
// Explicit checks done without comparing to NSTextField.
EXPECT_TRUE(
AXObjectHandlesSelector(ax_node, @selector(setAccessibilityValue:)));
EXPECT_NSEQ(NSAccessibilityTextFieldRole, ax_node.accessibilityRole);
NSString* kShownValue =
@"•"
@"••••••••••••••••";
// Sanity check.
EXPECT_EQ(static_cast<NSUInteger>(kTestStringLength), [kShownValue length]);
EXPECT_NSEQ(kShownValue, ax_node.accessibilityValue);
// Cursor currently at the end of input.
EXPECT_NSEQ(@"", ax_node.accessibilitySelectedText);
EXPECT_NSEQ(NSMakeRange(kTestStringLength, 0),
ax_node.accessibilitySelectedTextRange);
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
EXPECT_EQ(kTestStringLength, ax_node.accessibilityNumberOfCharacters);
EXPECT_NSEQ(NSMakeRange(0, kTestStringLength),
ax_node.accessibilityVisibleCharacterRange);
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
// Test replacing text.
textfield->SetText(u"123");
EXPECT_NSEQ(@"•••", ax_node.accessibilityValue);
EXPECT_EQ(3, ax_node.accessibilityNumberOfCharacters);
textfield->SetSelectedRange(gfx::Range(2, 3)); // Selects "3".
ax_node.accessibilitySelectedText = @"ab";
EXPECT_EQ(u"12ab", textfield->GetText());
EXPECT_NSEQ(@"••••", ax_node.accessibilityValue);
EXPECT_EQ(4, ax_node.accessibilityNumberOfCharacters);
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
}
// Test text-specific attributes of Labels.
TEST_F(AXNativeWidgetMacTest, Label) {
Label* label = new Label;
label->SetText(base::SysNSStringToUTF16(kTestStringValue));
label->SetSize(GetWidgetBounds().size());
widget()->GetContentsView()->AddChildView(label);
// Get the Label's accessibility object.
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
EXPECT_NSEQ(NSAccessibilityStaticTextRole, ax_node.accessibilityRole);
EXPECT_NSEQ(kTestStringValue, ax_node.accessibilityValue);
// Title and label for StaticTextRole should always be empty.
EXPECT_NSEQ(@"", ax_node.accessibilityTitle);
EXPECT_NSEQ(@"", ax_node.accessibilityLabel);
// No selection by default. TODO(tapted): Test selection when views::Label
// uses RenderTextHarfBuzz on Mac. See http://crbug.com/454835.
// For now, this tests that the codepaths are valid for views::Label.
EXPECT_NSEQ(@"", ax_node.accessibilitySelectedText);
EXPECT_NSEQ(NSMakeRange(0, 0), ax_node.accessibilitySelectedTextRange);
EXPECT_EQ(kTestStringLength, ax_node.accessibilityNumberOfCharacters);
EXPECT_NSEQ(NSMakeRange(0, kTestStringLength),
ax_node.accessibilityVisibleCharacterRange);
EXPECT_EQ(0, ax_node.accessibilityInsertionPointLineNumber);
// Test parameterized attributes for Static Text.
NSInteger line = [ax_node accessibilityLineForIndex:5];
EXPECT_EQ(0, line);
EXPECT_NSEQ(NSMakeRange(0, kTestStringLength),
[ax_node accessibilityRangeForLine:line]);
NSRange test_range = NSMakeRange(1, 6);
EXPECT_NSEQ(@"est st", [ax_node accessibilityStringForRange:test_range]);
EXPECT_NSEQ(
@"est st",
[[ax_node accessibilityAttributedStringForRange:test_range] string]);
// TODO(tapted): Add a test for multiline Labels (currently not supported).
}
// Labels used as title bars should be exposed as normal static text on Mac.
TEST_F(AXNativeWidgetMacTest, LabelUsedAsTitleBar) {
Label* label = new Label(base::SysNSStringToUTF16(kTestStringValue),
style::CONTEXT_DIALOG_TITLE, style::STYLE_PRIMARY);
label->SetSize(GetWidgetBounds().size());
widget()->GetContentsView()->AddChildView(label);
// Get the Label's accessibility object.
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
EXPECT_NSEQ(NSAccessibilityStaticTextRole, ax_node.accessibilityRole);
EXPECT_NSEQ(kTestStringValue, ax_node.accessibilityValue);
}
class TestComboboxModel : public ui::ComboboxModel {
public:
TestComboboxModel() = default;
TestComboboxModel(const TestComboboxModel&) = delete;
TestComboboxModel& operator=(const TestComboboxModel&) = delete;
// ui::ComboboxModel:
size_t GetItemCount() const override { return 2; }
std::u16string GetItemAt(size_t index) const override {
return index == 0 ? base::SysNSStringToUTF16(kTestStringValue)
: u"Second Item";
}
};
// Test a11y attributes of Comboboxes.
TEST_F(AXNativeWidgetMacTest, Combobox) {
Combobox* combobox = new Combobox(std::make_unique<TestComboboxModel>());
combobox->SetSize(GetWidgetBounds().size());
widget()->GetContentsView()->AddChildView(combobox);
id<NSAccessibility> ax_node = A11yElementAtMidpoint();
EXPECT_TRUE(ax_node);
EXPECT_NSEQ(NSAccessibilityPopUpButtonRole, ax_node.accessibilityRole);
// The initial value should be the first item in the menu.
EXPECT_NSEQ(kTestStringValue, ax_node.accessibilityValue);
combobox->SetSelectedIndex(1);
EXPECT_NSEQ(@"Second Item", ax_node.accessibilityValue);
// Expect to see both a press action and a show menu action. This matches
// Cocoa behavior.
EXPECT_TRUE(
AXObjectHandlesSelector(ax_node, @selector(accessibilityPerformPress)));
EXPECT_TRUE(AXObjectHandlesSelector(ax_node,
@selector(accessibilityPerformShowMenu)));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/ax_native_widget_mac_unittest.mm | Objective-C++ | unknown | 35,085 |
specific_include_rules = {
"desktop_window_tree_host_lacros.*": [
"+chromeos/ui/base",
],
}
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/DEPS | Python | unknown | 100 |
// 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/widget/desktop_aura/desktop_capture_client.h"
#include "base/containers/cxx20_erase.h"
#include "base/observer_list.h"
#include "ui/aura/client/capture_client_observer.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tracker.h"
#include "ui/aura/window_tree_host.h"
namespace views {
namespace {
// This comparator facilitates constructing DesktopCaptureClient WeakPtr sets.
bool CompareWeakPtrs(const base::WeakPtr<DesktopCaptureClient>& lhs,
const base::WeakPtr<DesktopCaptureClient>& rhs) {
return lhs.get() < rhs.get();
}
} // namespace
// static
DesktopCaptureClient::ClientSet* DesktopCaptureClient::clients_ = nullptr;
// static
aura::Window* DesktopCaptureClient::GetCaptureWindowGlobal() {
for (const auto& client : *clients_) {
if (client && client->capture_window_)
return client->capture_window_;
}
return nullptr;
}
DesktopCaptureClient::DesktopCaptureClient(aura::Window* root) : root_(root) {
if (!clients_)
clients_ = new ClientSet(&CompareWeakPtrs);
clients_->insert(weak_factory_.GetWeakPtr());
aura::client::SetCaptureClient(root, this);
}
DesktopCaptureClient::~DesktopCaptureClient() {
aura::client::SetCaptureClient(root_, nullptr);
base::EraseIf(*clients_, [this](const auto& c) { return c.get() == this; });
}
void DesktopCaptureClient::SetCapture(aura::Window* new_capture_window) {
if (capture_window_ == new_capture_window)
return;
// We should only ever be told to capture a child of |root_|. Otherwise
// things are going to be really confused.
DCHECK(!new_capture_window || (new_capture_window->GetRootWindow() == root_));
DCHECK(!capture_window_ || capture_window_->GetRootWindow());
aura::Window* old_capture_window = capture_window_;
// If we're starting a new capture, cancel all touches that aren't
// targeted to the capturing window.
if (new_capture_window) {
// Cancelling touches might cause |new_capture_window| to get deleted.
// Track |new_capture_window| and check if it still exists before
// committing |capture_window_|.
aura::WindowTracker tracker;
tracker.Add(new_capture_window);
aura::Env::GetInstance()->gesture_recognizer()->CancelActiveTouchesExcept(
new_capture_window);
if (!tracker.Contains(new_capture_window))
new_capture_window = nullptr;
}
capture_window_ = new_capture_window;
aura::client::CaptureDelegate* delegate = root_->GetHost()->dispatcher();
delegate->UpdateCapture(old_capture_window, new_capture_window);
// Initiate native capture updating.
if (!capture_window_) {
delegate->ReleaseNativeCapture();
} else if (!old_capture_window) {
delegate->SetNativeCapture();
// Notify the other roots that we got capture. This is important so that
// they reset state. Clients may be destroyed during the loop.
ClientSet clients(*clients_);
for (auto client : clients) {
if (client && client.get() != this) {
aura::client::CaptureDelegate* client_delegate =
client->root_->GetHost()->dispatcher();
client_delegate->OnOtherRootGotCapture();
}
}
} // else case is capture is remaining in our root, nothing to do.
for (auto& observer : observers_)
observer.OnCaptureChanged(old_capture_window, capture_window_);
}
void DesktopCaptureClient::ReleaseCapture(aura::Window* window) {
if (capture_window_ == window)
SetCapture(nullptr);
}
aura::Window* DesktopCaptureClient::GetCaptureWindow() {
return capture_window_;
}
aura::Window* DesktopCaptureClient::GetGlobalCaptureWindow() {
return GetCaptureWindowGlobal();
}
void DesktopCaptureClient::AddObserver(
aura::client::CaptureClientObserver* observer) {
observers_.AddObserver(observer);
}
void DesktopCaptureClient::RemoveObserver(
aura::client::CaptureClientObserver* observer) {
observers_.RemoveObserver(observer);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_capture_client.cc | C++ | unknown | 4,146 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_CAPTURE_CLIENT_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_CAPTURE_CLIENT_H_
#include <set>
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "ui/aura/client/capture_client.h"
#include "ui/views/views_export.h"
namespace aura {
class RootWindow;
}
namespace views {
// Desktop implementation of CaptureClient. There is one CaptureClient per
// DesktopNativeWidgetAura.
//
// DesktopCaptureClient and CaptureController (used by ash) differ slightly in
// how they handle capture. CaptureController is a singleton shared among all
// RootWindows created by ash. An implication of this is that all RootWindows
// know which window has capture. This is not the case with
// DesktopCaptureClient. Instead each RootWindow has its own
// DesktopCaptureClient. This means only the RootWindow of the Window that has
// capture knows which window has capture. All others think no one has
// capture. This behavior is necessitated by Windows occassionally delivering
// mouse events to a window other than the capture window and expecting that
// window to get the event. If we shared the capture window on the desktop this
// behavior would not be possible.
class VIEWS_EXPORT DesktopCaptureClient : public aura::client::CaptureClient {
public:
explicit DesktopCaptureClient(aura::Window* root);
DesktopCaptureClient(const DesktopCaptureClient&) = delete;
DesktopCaptureClient& operator=(const DesktopCaptureClient&) = delete;
~DesktopCaptureClient() override;
// Exactly the same as GetGlobalCaptureWindow() but static.
static aura::Window* GetCaptureWindowGlobal();
// Overridden from aura::client::CaptureClient:
void SetCapture(aura::Window* window) override;
void ReleaseCapture(aura::Window* window) override;
aura::Window* GetCaptureWindow() override;
aura::Window* GetGlobalCaptureWindow() override;
void AddObserver(aura::client::CaptureClientObserver* observer) override;
void RemoveObserver(aura::client::CaptureClientObserver* observer) override;
private:
using Comparator = bool (*)(const base::WeakPtr<DesktopCaptureClient>&,
const base::WeakPtr<DesktopCaptureClient>&);
using ClientSet = std::set<base::WeakPtr<DesktopCaptureClient>, Comparator>;
raw_ptr<aura::Window> root_;
raw_ptr<aura::Window> capture_window_ = nullptr;
// The global set of DesktopCaptureClients.
static ClientSet* clients_;
base::ObserverList<aura::client::CaptureClientObserver>::Unchecked observers_;
base::WeakPtrFactory<DesktopCaptureClient> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_CAPTURE_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_capture_client.h | C++ | unknown | 2,843 |
// 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/widget/desktop_aura/desktop_drag_drop_client_ozone.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "ui/aura/client/capture_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/base/data_transfer_policy/data_transfer_policy_controller.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/layout.h"
#include "ui/compositor/layer.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/platform_window/platform_window_delegate.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
using ::ui::mojom::DragOperation;
// The minimum alpha required so we would treat the pixel as visible.
constexpr uint32_t kMinAlpha = 32;
// Returns true if |image| has any visible regions (defined as having a pixel
// with alpha > |kMinAlpha|).
bool IsValidDragImage(const gfx::ImageSkia& image) {
if (image.isNull())
return false;
// Because we need a GL context per window, we do a quick check so that we
// don't make another context if the window would just be displaying a mostly
// transparent image.
const SkBitmap* in_bitmap = image.bitmap();
for (int y = 0; y < in_bitmap->height(); ++y) {
uint32_t* in_row = in_bitmap->getAddr32(0, y);
for (int x = 0; x < in_bitmap->width(); ++x) {
if (SkColorGetA(in_row[x]) > kMinAlpha)
return true;
}
}
return false;
}
std::unique_ptr<views::Widget> CreateDragWidget(
const gfx::Point& root_location,
const gfx::ImageSkia& image,
const gfx::Vector2d& drag_widget_offset) {
auto widget = std::make_unique<views::Widget>();
views::Widget::InitParams params(views::Widget::InitParams::TYPE_DRAG);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.accept_events = false;
gfx::Point location = root_location - drag_widget_offset;
params.bounds = gfx::Rect(location, image.size());
widget->set_focus_on_creation(false);
widget->set_frame_type(views::Widget::FrameType::kForceNative);
widget->Init(std::move(params));
widget->GetNativeWindow()->SetName("DragWindow");
std::unique_ptr<views::ImageView> image_view =
std::make_unique<views::ImageView>();
image_view->SetImage(image);
widget->SetContentsView(std::move(image_view));
widget->Show();
widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false);
widget->StackAtTop();
return widget;
}
// Drops the dragged data if no policy restrictions exist (Data Leak Prevention
// stack uninitialised) or if there are rules allowing the data transfer.
// Otherwise the drag is cancelled.
void DropIfAllowed(const ui::OSExchangeData* drag_data,
aura::client::DragUpdateInfo& drag_info,
base::OnceClosure drop_cb) {
if (ui::DataTransferPolicyController::HasInstance()) {
ui::DataTransferPolicyController::Get()->DropIfAllowed(
drag_data, &drag_info.data_endpoint, std::move(drop_cb));
} else {
std::move(drop_cb).Run();
}
}
// A callback that runs the drop closure, if there is one, to perform the data
// drop. If this callback is destroyed without running, the |drag_cancel|
// closure will run.
void PerformDrop(aura::client::DragDropDelegate::DropCallback drop_cb,
std::unique_ptr<ui::OSExchangeData> data_to_drop,
base::ScopedClosureRunner drag_cancel) {
if (drop_cb) {
auto output_drag_op = ui::mojom::DragOperation::kNone;
std::move(drop_cb).Run(std::move(data_to_drop), output_drag_op,
/*drag_image_layer_owner=*/nullptr);
}
base::IgnoreResult(drag_cancel.Release());
}
} // namespace
DesktopDragDropClientOzone::DragContext::DragContext() = default;
DesktopDragDropClientOzone::DragContext::~DragContext() = default;
DesktopDragDropClientOzone::DesktopDragDropClientOzone(
aura::Window* root_window,
ui::WmDragHandler* drag_handler)
: root_window_(root_window),
drag_handler_(drag_handler) {}
DesktopDragDropClientOzone::~DesktopDragDropClientOzone() {
ResetDragDropTarget(true);
}
DragOperation DesktopDragDropClientOzone::StartDragAndDrop(
std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& root_location,
int allowed_operations,
ui::mojom::DragEventSource source) {
if (!drag_handler_)
return DragOperation::kNone;
DCHECK(!drag_context_);
drag_context_ = std::make_unique<DragContext>();
if (drag_handler_->ShouldReleaseCaptureForDrag(data.get())) {
aura::Window* capture_window =
aura::client::GetCaptureClient(root_window)->GetGlobalCaptureWindow();
if (capture_window) {
capture_window->ReleaseCapture();
}
}
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(root_window);
auto initial_cursor = source_window->GetHost()->last_cursor();
if (cursor_client) {
cursor_client->SetCursor(ui::mojom::CursorType::kGrabbing);
}
if (!ui::OzonePlatform::GetInstance()
->GetPlatformProperties()
.platform_shows_drag_image) {
const auto& provider = data->provider();
gfx::ImageSkia drag_image = provider.GetDragImage();
if (IsValidDragImage(drag_image)) {
drag_context_->size = drag_image.size();
drag_context_->offset = provider.GetDragImageOffset();
drag_context_->widget =
CreateDragWidget(root_location, drag_image, drag_context_->offset);
}
}
// This object is owned by a DesktopNativeWidgetAura that can be destroyed
// during the drag loop, which will also destroy this object. So keep track
// of whether we are still alive after the drag ends.
auto alive = weak_factory_.GetWeakPtr();
const bool drag_succeeded = drag_handler_->StartDrag(
*data.get(), allowed_operations, source, cursor_client->GetCursor(),
!source_window->HasCapture(),
base::BindOnce(&DesktopDragDropClientOzone::OnDragFinished,
weak_factory_.GetWeakPtr()),
GetLocationDelegate());
if (!alive)
return DragOperation::kNone;
if (!drag_succeeded)
drag_operation_ = DragOperation::kNone;
if (cursor_client)
cursor_client->SetCursor(initial_cursor);
drag_context_.reset();
return drag_operation_;
}
#if BUILDFLAG(IS_LINUX)
void DesktopDragDropClientOzone::UpdateDragImage(const gfx::ImageSkia& image,
const gfx::Vector2d& offset) {
DCHECK(drag_handler_);
drag_handler_->UpdateDragImage(image, offset);
}
#endif // BUILDFLAG(LINUX)
void DesktopDragDropClientOzone::DragCancel() {
ResetDragDropTarget(true);
drag_operation_ = DragOperation::kNone;
if (!drag_handler_)
return;
drag_handler_->CancelDrag();
}
bool DesktopDragDropClientOzone::IsDragDropInProgress() {
return drag_context_.get();
}
void DesktopDragDropClientOzone::AddObserver(
aura::client::DragDropClientObserver* observer) {
NOTIMPLEMENTED_LOG_ONCE();
}
void DesktopDragDropClientOzone::RemoveObserver(
aura::client::DragDropClientObserver* observer) {
NOTIMPLEMENTED_LOG_ONCE();
}
void DesktopDragDropClientOzone::OnDragEnter(
const gfx::PointF& point,
std::unique_ptr<ui::OSExchangeData> data,
int operation,
int modifiers) {
last_drag_point_ = point;
last_drop_operation_ = operation;
// If |data| is empty, we defer sending any events to the
// |drag_drop_delegate_|. All necessary events will be sent on dropping.
if (!data)
return;
data_to_drop_ = std::move(data);
UpdateTargetAndCreateDropEvent(point, modifiers);
}
int DesktopDragDropClientOzone::OnDragMotion(const gfx::PointF& point,
int operation,
int modifiers) {
last_drag_point_ = point;
last_drop_operation_ = operation;
// If |data_to_drop_| doesn't have data, return that we accept everything.
if (!data_to_drop_)
return ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE;
// Ask the delegate what operation it would accept for the current data.
int client_operation = ui::DragDropTypes::DRAG_NONE;
std::unique_ptr<ui::DropTargetEvent> event =
UpdateTargetAndCreateDropEvent(point, modifiers);
if (drag_drop_delegate_ && event) {
current_drag_info_ = drag_drop_delegate_->OnDragUpdated(*event);
client_operation = current_drag_info_.drag_operation;
}
return client_operation;
}
void DesktopDragDropClientOzone::OnDragDrop(
std::unique_ptr<ui::OSExchangeData> data,
int modifiers) {
// If we didn't have |data_to_drop_|, then |drag_drop_delegate_| had never
// been updated, and now it needs to receive deferred enter and update events
// before handling the actual drop.
const bool postponed_enter_and_update = !data_to_drop_;
// If we didn't have |data_to_drop_| already since the drag had entered the
// window, take the new data that comes now.
if (!data_to_drop_)
data_to_drop_ = std::move(data);
// crbug.com/1151836: check that we have data.
if (data_to_drop_) {
// This will call the delegate's OnDragEntered if needed.
auto event = UpdateTargetAndCreateDropEvent(last_drag_point_, modifiers);
if (drag_drop_delegate_ && event) {
if (postponed_enter_and_update) {
// TODO(https://crbug.com/1014860): deal with drop refusals.
// The delegate's OnDragUpdated returns an operation that the delegate
// would accept. Normally the accepted operation would be propagated
// properly, and if the delegate didn't accept it, the drop would never
// be called, but in this scenario of postponed updates we send all
// events at once. Now we just drop, but perhaps we could call
// OnDragLeave and quit?
current_drag_info_ = drag_drop_delegate_->OnDragUpdated(*event);
}
auto drop_cb = drag_drop_delegate_->GetDropCallback(*event);
if (drop_cb) {
base::ScopedClosureRunner drag_cancel(
base::BindOnce(&DesktopDragDropClientOzone::DragCancel,
weak_factory_.GetWeakPtr()));
DropIfAllowed(
data_to_drop_.get(), current_drag_info_,
base::BindOnce(&PerformDrop, std::move(drop_cb),
std::move(data_to_drop_), std::move(drag_cancel)));
}
}
}
ResetDragDropTarget(false);
}
void DesktopDragDropClientOzone::OnDragLeave() {
data_to_drop_.reset();
ResetDragDropTarget(true);
}
void DesktopDragDropClientOzone::OnWindowDestroyed(aura::Window* window) {
DCHECK_EQ(window, current_window_);
current_window_->RemoveObserver(this);
current_window_ = nullptr;
drag_drop_delegate_ = nullptr;
current_drag_info_ = aura::client::DragUpdateInfo();
}
ui::WmDragHandler::LocationDelegate*
DesktopDragDropClientOzone::GetLocationDelegate() {
return nullptr;
}
void DesktopDragDropClientOzone::OnDragFinished(DragOperation operation) {
drag_operation_ = operation;
}
std::unique_ptr<ui::DropTargetEvent>
DesktopDragDropClientOzone::UpdateTargetAndCreateDropEvent(
const gfx::PointF& root_location,
int modifiers) {
DCHECK(data_to_drop_);
aura::Window* window =
root_window_->GetEventHandlerForPoint(gfx::ToFlooredPoint(root_location));
if (!window) {
ResetDragDropTarget(true);
return nullptr;
}
auto* new_delegate = aura::client::GetDragDropDelegate(window);
const bool delegate_has_changed = (new_delegate != drag_drop_delegate_);
if (delegate_has_changed) {
ResetDragDropTarget(true);
drag_drop_delegate_ = new_delegate;
current_window_ = window;
current_window_->AddObserver(this);
}
if (!drag_drop_delegate_)
return nullptr;
gfx::PointF target_location(root_location);
aura::Window::ConvertPointToTarget(root_window_, window, &target_location);
auto event = std::make_unique<ui::DropTargetEvent>(
*data_to_drop_, target_location, gfx::PointF(root_location),
last_drop_operation_);
event->set_flags(modifiers);
if (delegate_has_changed)
drag_drop_delegate_->OnDragEntered(*event);
return event;
}
void DesktopDragDropClientOzone::ResetDragDropTarget(bool send_exit) {
if (drag_drop_delegate_) {
if (send_exit)
drag_drop_delegate_->OnDragExited();
drag_drop_delegate_ = nullptr;
}
if (current_window_) {
current_window_->RemoveObserver(this);
current_window_ = nullptr;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone.cc | C++ | unknown | 12,939 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_H_
#include <memory>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/window_observer.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/buildflags.h"
#include "ui/platform_window/wm/wm_drag_handler.h"
#include "ui/platform_window/wm/wm_drop_handler.h"
#include "ui/views/views_export.h"
namespace aura::client {
class DragDropDelegate;
} // namespace aura::client
namespace ui {
class DropTargetEvent;
}
namespace views {
class Widget;
class VIEWS_EXPORT DesktopDragDropClientOzone
: public aura::client::DragDropClient,
public ui::WmDropHandler,
public aura::WindowObserver {
public:
DesktopDragDropClientOzone(aura::Window* root_window,
ui::WmDragHandler* drag_handler);
DesktopDragDropClientOzone(const DesktopDragDropClientOzone&) = delete;
DesktopDragDropClientOzone& operator=(const DesktopDragDropClientOzone&) =
delete;
~DesktopDragDropClientOzone() override;
protected:
friend class DesktopDragDropClientOzoneTest;
// Holds data related to the drag operation started by this client.
struct DragContext {
DragContext();
~DragContext();
// Widget that the user drags around. May be nullptr.
std::unique_ptr<Widget> widget;
// The size of drag image.
gfx::Size size;
// The offset of |drag_widget_| relative to the mouse position.
gfx::Vector2d offset;
#if BUILDFLAG(IS_LINUX)
// The last received drag location. The drag widget is moved asynchronously
// so its position is updated when the UI thread has time for that. When
// the first change to the location happens, a call to UpdateDragWidget()
// is posted, and this location is set. The location can be updated a few
// more times until the posted task is executed, but no more than a single
// call to UpdateDragWidget() is scheduled at any time; this optional is set
// means that the task is scheduled.
// This is used on a platform where chrome manages a drag image (e.g. x11).
absl::optional<gfx::Point> last_screen_location_px;
#endif
};
// aura::client::DragDropClient
ui::mojom::DragOperation StartDragAndDrop(
std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& root_location,
int allowed_operations,
ui::mojom::DragEventSource source) override;
#if BUILDFLAG(IS_LINUX)
void UpdateDragImage(const gfx::ImageSkia& image,
const gfx::Vector2d& offset) override;
#endif
void DragCancel() override;
bool IsDragDropInProgress() override;
void AddObserver(aura::client::DragDropClientObserver* observer) override;
void RemoveObserver(aura::client::DragDropClientObserver* observer) override;
// ui::WmDropHandler
void OnDragEnter(const gfx::PointF& point,
std::unique_ptr<ui::OSExchangeData> data,
int operation,
int modifiers) override;
int OnDragMotion(const gfx::PointF& point,
int operation,
int modifiers) override;
void OnDragDrop(std::unique_ptr<ui::OSExchangeData> data,
int modifiers) override;
void OnDragLeave() override;
// aura::WindowObserver
void OnWindowDestroyed(aura::Window* window) override;
// Returns a WmDragHandler::LocationDelegate passed to `StartDrag`.
virtual ui::WmDragHandler::LocationDelegate* GetLocationDelegate();
void OnDragFinished(ui::mojom::DragOperation operation);
// Returns a DropTargetEvent to be passed to the DragDropDelegate.
// Updates the delegate if needed, which in its turn calls their
// OnDragExited/OnDragEntered, so after getting the event the delegate
// is ready to accept OnDragUpdated or GetDropCallback. Returns nullptr if
// drop is not possible.
std::unique_ptr<ui::DropTargetEvent> UpdateTargetAndCreateDropEvent(
const gfx::PointF& point,
int modifiers);
// Updates |drag_drop_delegate_| along with |window|.
void UpdateDragDropDelegate(aura::Window* window);
// Resets |drag_drop_delegate_|.
// |send_exit| controls whether to call delegate's OnDragExited() before
// resetting.
void ResetDragDropTarget(bool send_exit);
DragContext* drag_context() { return drag_context_.get(); }
aura::Window* root_window() { return root_window_; }
private:
const raw_ptr<aura::Window> root_window_;
const raw_ptr<ui::WmDragHandler> drag_handler_;
aura::client::DragUpdateInfo current_drag_info_;
// Last window under the mouse.
raw_ptr<aura::Window> current_window_ = nullptr;
// The delegate corresponding to the window located at the mouse position.
raw_ptr<aura::client::DragDropDelegate> drag_drop_delegate_ = nullptr;
// The data to be delivered through the drag and drop.
std::unique_ptr<ui::OSExchangeData> data_to_drop_;
// The most recent native coordinates of an incoming drag. Updated while
// the mouse is moved, and used at dropping.
gfx::PointF last_drag_point_;
// The most recent drop operation. Updated while the mouse is moved, and
// used at dropping.
int last_drop_operation_ = 0;
// The selected operation on drop.
ui::mojom::DragOperation drag_operation_ = ui::mojom::DragOperation::kNone;
std::unique_ptr<DragContext> drag_context_;
base::WeakPtrFactory<DesktopDragDropClientOzone> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone.h | C++ | unknown | 6,148 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_linux.h"
#include "base/functional/bind.h"
#include "base/task/single_thread_task_runner.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/base/data_transfer_policy/data_transfer_policy_controller.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/layout.h"
#include "ui/views/widget/widget.h"
namespace views {
DesktopDragDropClientOzoneLinux::DesktopDragDropClientOzoneLinux(
aura::Window* root_window,
ui::WmDragHandler* drag_handler)
: DesktopDragDropClientOzone(root_window, drag_handler) {}
DesktopDragDropClientOzoneLinux::~DesktopDragDropClientOzoneLinux() = default;
ui::WmDragHandler::LocationDelegate*
DesktopDragDropClientOzoneLinux::GetLocationDelegate() {
return this;
}
void DesktopDragDropClientOzoneLinux::OnDragLocationChanged(
const gfx::Point& screen_point_px) {
DCHECK(drag_context());
if (!drag_context()->widget)
return;
const bool dispatch_mouse_event = !drag_context()->last_screen_location_px;
drag_context()->last_screen_location_px = screen_point_px;
if (dispatch_mouse_event) {
// Post a task to dispatch mouse movement event when control returns to the
// message loop. This allows smoother dragging since the events are
// dispatched without waiting for the drag widget updates.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(
&DesktopDragDropClientOzoneLinux::UpdateDragWidgetLocation,
weak_factory_.GetWeakPtr()));
}
}
void DesktopDragDropClientOzoneLinux::OnDragOperationChanged(
ui::mojom::DragOperation operation) {
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(root_window());
if (!cursor_client)
return;
ui::mojom::CursorType cursor_type = ui::mojom::CursorType::kNull;
switch (operation) {
case ui::mojom::DragOperation::kNone:
cursor_type = ui::mojom::CursorType::kDndNone;
break;
case ui::mojom::DragOperation::kMove:
cursor_type = ui::mojom::CursorType::kDndMove;
break;
case ui::mojom::DragOperation::kCopy:
cursor_type = ui::mojom::CursorType::kDndCopy;
break;
case ui::mojom::DragOperation::kLink:
cursor_type = ui::mojom::CursorType::kDndLink;
break;
}
cursor_client->SetCursor(cursor_type);
}
absl::optional<gfx::AcceleratedWidget>
DesktopDragDropClientOzoneLinux::GetDragWidget() {
DCHECK(drag_context());
if (drag_context()->widget)
return drag_context()
->widget->GetNativeWindow()
->GetHost()
->GetAcceleratedWidget();
return absl::nullopt;
}
void DesktopDragDropClientOzoneLinux::UpdateDragWidgetLocation() {
if (!drag_context())
return;
float scale_factor = ui::GetScaleFactorForNativeView(
drag_context()->widget->GetNativeWindow());
gfx::Point scaled_point = gfx::ScaleToRoundedPoint(
*drag_context()->last_screen_location_px, 1.f / scale_factor);
drag_context()->widget->SetBounds(
gfx::Rect(scaled_point - drag_context()->offset, drag_context()->size));
drag_context()->widget->StackAtTop();
drag_context()->last_screen_location_px.reset();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_linux.cc | C++ | unknown | 3,573 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_LINUX_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_LINUX_H_
#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/buildflags.h"
#include "ui/platform_window/wm/wm_drag_handler.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone.h"
namespace views {
class VIEWS_EXPORT DesktopDragDropClientOzoneLinux
: public DesktopDragDropClientOzone,
public ui::WmDragHandler::LocationDelegate {
public:
DesktopDragDropClientOzoneLinux(aura::Window* root_window,
ui::WmDragHandler* drag_handler);
DesktopDragDropClientOzoneLinux(const DesktopDragDropClientOzoneLinux&) =
delete;
DesktopDragDropClientOzoneLinux& operator=(
const DesktopDragDropClientOzoneLinux&) = delete;
~DesktopDragDropClientOzoneLinux() override;
private:
// DesktopdragDropClientOzone::
ui::WmDragHandler::LocationDelegate* GetLocationDelegate() override;
// ui::WmDragHandler::LocationDelegate:
void OnDragLocationChanged(const gfx::Point& screen_point_px) override;
void OnDragOperationChanged(ui::mojom::DragOperation operation) override;
absl::optional<gfx::AcceleratedWidget> GetDragWidget() override;
// Updates |drag_widget_| so it is aligned with the last drag location.
void UpdateDragWidgetLocation();
base::WeakPtrFactory<DesktopDragDropClientOzoneLinux> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_OZONE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_linux.h | C++ | unknown | 1,922 |