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 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/interaction/interaction_test_util_views.h"
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/i18n/rtl.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom-shared.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/gesture_event_details.h"
#include "ui/events/types/event_type.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
#include "ui/views/controls/menu/menu_host.h"
#include "ui/views/controls/menu/menu_host_root_view.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/view_tracker.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/any_widget_observer.h"
#include "ui/views/window/dialog_delegate.h"
#if BUILDFLAG(IS_LINUX) && BUILDFLAG(IS_OZONE) && \
!BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_CHROMEOS_LACROS)
#define HANDLE_WAYLAND_FAILURE 1
#else
#define HANDLE_WAYLAND_FAILURE 0
#endif
#if HANDLE_WAYLAND_FAILURE
#include "ui/ozone/public/ozone_platform.h"
#include "ui/views/widget/widget_observer.h"
#endif
namespace views::test {
namespace {
#if HANDLE_WAYLAND_FAILURE
// On Wayland on Linux, window activation isn't guaranteed to work (based on
// what compositor extensions are installed). So instead, make a best effort to
// wait for the widget to activate, and if it fails, skip the test as it cannot
// possibly pass.
class WidgetActivationWaiterWayland final : public WidgetObserver {
public:
// A more than reasonable amount of time to wait for a window to activate.
static constexpr base::TimeDelta kTimeout = base::Seconds(1);
// Constructs an activation waiter for the given widget.
explicit WidgetActivationWaiterWayland(Widget* widget)
: active_(widget->IsActive()) {
if (!active_) {
widget_observation_.Observe(widget);
}
}
~WidgetActivationWaiterWayland() override = default;
// Waits for the widget to become active or the operation to time out; returns
// true on success. Returns immediately if the widget is already active.
bool Wait() {
if (!active_) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&WidgetActivationWaiterWayland::OnTimeout,
weak_ptr_factory_.GetWeakPtr()),
kTimeout);
run_loop_.Run();
}
return active_;
}
private:
// WidgetObserver:
void OnWidgetDestroyed(Widget* widget) override {
NOTREACHED_NORETURN() << "Widget destroyed before observation.";
}
void OnWidgetActivationChanged(Widget* widget, bool active) override {
if (!active) {
return;
}
active_ = true;
widget_observation_.Reset();
run_loop_.Quit();
}
void OnTimeout() {
widget_observation_.Reset();
run_loop_.Quit();
}
bool active_;
base::RunLoop run_loop_{base::RunLoop::Type::kNestableTasksAllowed};
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
base::WeakPtrFactory<WidgetActivationWaiterWayland> weak_ptr_factory_{this};
};
#endif // HANDLE_WAYLAND_FAILURE
// Waits for the dropdown pop-up and selects the specified item from the list.
class DropdownItemSelector {
public:
// The owning `simulator` will be used to simulate a click on the
// `item_index`-th drop-down menu item using `input_type`.
DropdownItemSelector(InteractionTestUtilSimulatorViews* simulator,
ui::test::InteractionTestUtil::InputType input_type,
size_t item_index)
: simulator_(simulator),
input_type_(input_type),
item_index_(item_index) {
observer_.set_shown_callback(base::BindRepeating(
&DropdownItemSelector::OnWidgetShown, weak_ptr_factory_.GetWeakPtr()));
observer_.set_hidden_callback(base::BindRepeating(
&DropdownItemSelector::OnWidgetHidden, weak_ptr_factory_.GetWeakPtr()));
}
DropdownItemSelector(const DropdownItemSelector&) = delete;
void operator=(const DropdownItemSelector&) = delete;
~DropdownItemSelector() = default;
// Synchronously waits for the drop-down to appear and selects the appropriate
// item.
void SelectItem() {
CHECK(!run_loop_.running());
CHECK(!result_.has_value());
run_loop_.Run();
}
// Returns whether the operation succeeded or failed.
ui::test::ActionResult result() const {
return result_.value_or(ui::test::ActionResult::kFailed);
}
private:
// Responds to a new widget being shown. The assumption is that this widget is
// the combobox dropdown. If it is not, the follow-up call will fail.
void OnWidgetShown(Widget* widget) {
if (widget_ || result_.has_value()) {
return;
}
widget_ = widget;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&DropdownItemSelector::SelectItemImpl,
weak_ptr_factory_.GetWeakPtr()));
}
// Detects when a widget is hidden. Fails the operation if this was the drop-
// down widget and the item has not yet been selected.
void OnWidgetHidden(Widget* widget) {
if (result_.has_value() || widget_ != widget) {
return;
}
LOG(ERROR) << "Widget closed before selection took place.";
SetResult(ui::test::ActionResult::kFailed);
}
// Actually finds and selects the item in the drop-down. If it is not present
// or cannot be selected, fails the operation.
void SelectItemImpl() {
CHECK(widget_);
CHECK(!result_.has_value());
// Because this widget was just shown, it may not be laid out yet.
widget_->LayoutRootViewIfNecessary();
size_t index = item_index_;
if (auto* const menu_item =
FindMenuItem(widget_->GetContentsView(), index)) {
// No longer tracking the widget. This will prevent synchronous widget
// dismissed during SelectMenuItem() below from thinking it failed.
widget_ = nullptr;
// Try to select the item.
const auto result = simulator_->SelectMenuItem(
ElementTrackerViews::GetInstance()->GetElementForView(menu_item,
true),
input_type_);
SetResult(result);
switch (result) {
case ui::test::ActionResult::kFailed:
LOG(ERROR) << "Unable to select dropdown menu item.";
break;
case ui::test::ActionResult::kNotAttempted:
NOTREACHED_NORETURN();
case ui::test::ActionResult::kKnownIncompatible:
LOG(WARNING)
<< "Select dropdown item not available on this platform with "
"input type "
<< input_type_;
break;
case ui::test::ActionResult::kSucceeded:
break;
}
} else {
LOG(ERROR) << "Dropdown menu item not found.";
SetResult(ui::test::ActionResult::kFailed);
}
}
// Sets the result and aborts `run_loop_`. Should only ever be called once.
void SetResult(ui::test::ActionResult result) {
CHECK(!result_.has_value());
result_ = result;
widget_ = nullptr;
weak_ptr_factory_.InvalidateWeakPtrs();
run_loop_.Quit();
}
// Recursively search `from` for the `index`-th MenuItemView.
//
// Searches in-order, depth-first. It is assumed that menu items will appear
// in search order in the same order they appear visually.
static MenuItemView* FindMenuItem(View* from, size_t& index) {
for (auto* child : from->children()) {
auto* const item = AsViewClass<MenuItemView>(child);
if (item) {
if (index == 0U)
return item;
--index;
} else if (auto* result = FindMenuItem(child, index)) {
return result;
}
}
return nullptr;
}
const base::raw_ptr<InteractionTestUtilSimulatorViews> simulator_;
const ui::test::InteractionTestUtil::InputType input_type_;
const size_t item_index_;
base::RunLoop run_loop_{base::RunLoop::Type::kNestableTasksAllowed};
AnyWidgetObserver observer_{views::test::AnyWidgetTestPasskey()}; // IN-TEST
absl::optional<ui::test::ActionResult> result_;
base::raw_ptr<Widget> widget_ = nullptr;
base::WeakPtrFactory<DropdownItemSelector> weak_ptr_factory_{this};
};
gfx::Point GetCenter(views::View* view) {
return view->GetLocalBounds().CenterPoint();
}
bool SendDefaultAction(View* target) {
ui::AXActionData action;
action.action = ax::mojom::Action::kDoDefault;
return target->HandleAccessibleAction(action);
}
// Sends a mouse click to the specified `target`.
// Views are EventHandlers but Widgets are not despite having the same API for
// event handling, so use a templated approach to support both cases.
template <class T>
void SendMouseClick(T* target, const gfx::Point& point) {
ui::MouseEvent mouse_down(ui::ET_MOUSE_PRESSED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
target->OnMouseEvent(&mouse_down);
ui::MouseEvent mouse_up(ui::ET_MOUSE_RELEASED, point, point,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
target->OnMouseEvent(&mouse_up);
}
// Sends a tap gesture to the specified `target`.
// Views are EventHandlers but Widgets are not despite having the same API for
// event handling, so use a templated approach to support both cases.
template <class T>
void SendTapGesture(T* target, const gfx::Point& point) {
ui::GestureEventDetails press_details(ui::ET_GESTURE_TAP);
press_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN);
ui::GestureEvent press_event(point.x(), point.y(), ui::EF_NONE,
ui::EventTimeForNow(), press_details);
target->OnGestureEvent(&press_event);
ui::GestureEventDetails release_details(ui::ET_GESTURE_END);
release_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN);
ui::GestureEvent release_event(point.x(), point.y(), ui::EF_NONE,
ui::EventTimeForNow(), release_details);
target->OnGestureEvent(&release_event);
}
// Sends a key press to the specified `target`. Returns true if the view is
// still valid after processing the keypress.
bool SendKeyPress(View* view, ui::KeyboardCode code, int flags = ui::EF_NONE) {
ViewTracker tracker(view);
view->OnKeyPressed(
ui::KeyEvent(ui::ET_KEY_PRESSED, code, flags, ui::EventTimeForNow()));
// Verify that the button is not destroyed after the key-down before trying
// to send the key-up.
if (!tracker.view())
return false;
tracker.view()->OnKeyReleased(
ui::KeyEvent(ui::ET_KEY_RELEASED, code, flags, ui::EventTimeForNow()));
return tracker.view();
}
} // namespace
InteractionTestUtilSimulatorViews::InteractionTestUtilSimulatorViews() =
default;
InteractionTestUtilSimulatorViews::~InteractionTestUtilSimulatorViews() =
default;
ui::test::ActionResult InteractionTestUtilSimulatorViews::PressButton(
ui::TrackedElement* element,
InputType input_type) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const button =
Button::AsButton(element->AsA<TrackedElementViews>()->view());
if (!button)
return ui::test::ActionResult::kNotAttempted;
PressButton(button, input_type);
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::SelectMenuItem(
ui::TrackedElement* element,
InputType input_type) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const menu_item =
AsViewClass<MenuItemView>(element->AsA<TrackedElementViews>()->view());
if (!menu_item)
return ui::test::ActionResult::kNotAttempted;
#if BUILDFLAG(IS_MAC)
// Keyboard input isn't reliable on Mac for submenus, so unless the test
// specifically calls for keyboard input, prefer mouse.
if (input_type == ui::test::InteractionTestUtil::InputType::kDontCare)
input_type = ui::test::InteractionTestUtil::InputType::kMouse;
#endif // BUILDFLAG(IS_MAC)
auto* const host = menu_item->GetWidget()->GetRootView();
gfx::Point point = GetCenter(menu_item);
View::ConvertPointToTarget(menu_item, host, &point);
switch (input_type) {
case ui::test::InteractionTestUtil::InputType::kMouse:
SendMouseClick(host->GetWidget(), point);
break;
case ui::test::InteractionTestUtil::InputType::kTouch:
SendTapGesture(host->GetWidget(), point);
break;
case ui::test::InteractionTestUtil::InputType::kKeyboard:
case ui::test::InteractionTestUtil::InputType::kDontCare: {
#if BUILDFLAG(IS_MAC)
constexpr ui::KeyboardCode kSelectMenuKeyboardCode = ui::VKEY_SPACE;
#else
constexpr ui::KeyboardCode kSelectMenuKeyboardCode = ui::VKEY_RETURN;
#endif
MenuController* const controller = menu_item->GetMenuController();
controller->SelectItemAndOpenSubmenu(menu_item);
ui::KeyEvent key_event(ui::ET_KEY_PRESSED, kSelectMenuKeyboardCode,
ui::EF_NONE, ui::EventTimeForNow());
controller->OnWillDispatchKeyEvent(&key_event);
break;
}
}
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::DoDefaultAction(
ui::TrackedElement* element,
InputType input_type) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
if (!DoDefaultAction(element->AsA<TrackedElementViews>()->view(),
input_type)) {
LOG(ERROR) << "Failed to send default action to " << *element;
return ui::test::ActionResult::kFailed;
}
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::SelectTab(
ui::TrackedElement* tab_collection,
size_t index,
InputType input_type) {
// Currently, only TabbedPane is supported, but other types of tab
// collections (e.g. browsers and tabstrips) may be supported by a different
// kind of simulator specific to browser code, so if this is not a supported
// View type, just return false instead of sending an error.
if (!tab_collection->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const pane = views::AsViewClass<TabbedPane>(
tab_collection->AsA<TrackedElementViews>()->view());
if (!pane)
return ui::test::ActionResult::kNotAttempted;
// Unlike with the element type, an out-of-bounds tab is always an error.
auto* const tab = pane->GetTabAt(index);
if (!tab) {
LOG(ERROR) << "Tab index " << index << " out of range, there are "
<< pane->GetTabCount() << " tabs.";
return ui::test::ActionResult::kFailed;
}
switch (input_type) {
case ui::test::InteractionTestUtil::InputType::kDontCare:
if (!SendDefaultAction(tab)) {
LOG(ERROR) << "Failed to send default action to tab.";
return ui::test::ActionResult::kFailed;
}
break;
case ui::test::InteractionTestUtil::InputType::kMouse:
SendMouseClick(tab, GetCenter(tab));
break;
case ui::test::InteractionTestUtil::InputType::kTouch:
SendTapGesture(tab, GetCenter(tab));
break;
case ui::test::InteractionTestUtil::InputType::kKeyboard: {
// Keyboard navigation is done by sending arrow keys to the currently-
// selected tab. Scan through the tabs by using the right arrow until the
// correct tab is selected; limit the number of times this is tried to
// avoid in infinite loop if something goes wrong.
const auto current_index = pane->GetSelectedTabIndex();
if (current_index != index) {
const auto code = ((current_index > index) ^ base::i18n::IsRTL())
? ui::VKEY_LEFT
: ui::VKEY_RIGHT;
const int count =
std::abs(static_cast<int>(index) - static_cast<int>(current_index));
LOG_IF(WARNING, count > 1)
<< "SelectTab via keyboard from " << current_index << " to "
<< index << " will pass through intermediate tabs.";
for (int i = 0; i < count; ++i) {
auto* const current_tab = pane->GetTabAt(pane->GetSelectedTabIndex());
SendKeyPress(current_tab, code);
}
if (index != pane->GetSelectedTabIndex()) {
LOG(ERROR) << "Unable to cycle through tabs to reach index " << index;
return ui::test::ActionResult::kFailed;
}
}
break;
}
}
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::SelectDropdownItem(
ui::TrackedElement* dropdown,
size_t index,
InputType input_type) {
if (!dropdown->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const view = dropdown->AsA<TrackedElementViews>()->view();
auto* const combobox = views::AsViewClass<Combobox>(view);
auto* const editable_combobox = views::AsViewClass<EditableCombobox>(view);
if (!combobox && !editable_combobox)
return ui::test::ActionResult::kNotAttempted;
auto* const model =
combobox ? combobox->GetModel() : editable_combobox->GetComboboxModel();
if (index >= model->GetItemCount()) {
LOG(ERROR) << "Item index " << index << " is out of range, there are "
<< model->GetItemCount() << " items.";
return ui::test::ActionResult::kFailed;
}
// InputType::kDontCare is implemented in a way that is safe across all
// platforms and most test environments; it does not rely on popping up the
// dropdown and selecting individual items.
if (input_type == InputType::kDontCare) {
if (combobox) {
combobox->MenuSelectionAt(index);
} else {
editable_combobox->SetText(model->GetItemAt(index));
}
return ui::test::ActionResult::kSucceeded;
}
// For specific input types, the dropdown will be popped out. Because of
// asynchronous and event-handling issues, this is not yet supported on Mac.
#if BUILDFLAG(IS_MAC)
LOG(WARNING) << "SelectDropdownItem(): "
"only InputType::kDontCare is supported on Mac.";
return ui::test::ActionResult::kKnownIncompatible;
#else
// This is required in case we want to repeatedly test a combobox; otherwise
// it will refuse to open the second time.
if (combobox)
combobox->closed_time_ = base::TimeTicks();
// The highest-fidelity input simulation involves actually opening the
// drop-down and selecting an item from the list.
DropdownItemSelector selector(this, input_type, index);
// Try to get the arrow. If it's present, the combobox will be opened by
// activating the button. Note that while Combobox has the ability to hide its
// arrow, the button is still present and visible, just transparent.
auto* const arrow = combobox ? combobox->arrow_button_.get()
: editable_combobox->arrow_.get();
if (arrow) {
PressButton(arrow, input_type);
} else {
if (!editable_combobox) {
LOG(ERROR) << "Only EditableCombobox should have the option to "
"completely remove its arrow.";
return ui::test::ActionResult::kFailed;
}
// Editable comboboxes without visible arrows exist, but are weird.
switch (input_type) {
case InputType::kDontCare:
case InputType::kKeyboard:
// Have to resort to keyboard input; DoDefaultAction() doesn't work.
SendKeyPress(editable_combobox->textfield_, ui::VKEY_DOWN);
break;
default:
LOG(WARNING) << "Mouse and touch input are not supported for "
"comboboxes without visible arrows.";
return ui::test::ActionResult::kNotAttempted;
}
}
selector.SelectItem();
return selector.result();
#endif
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::EnterText(
ui::TrackedElement* element,
std::u16string text,
TextEntryMode mode) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const view = element->AsA<TrackedElementViews>()->view();
// Currently, Textfields (and derived types like Textareas) are supported, as
// well as EditableCombobox.
Textfield* textfield = AsViewClass<Textfield>(view);
if (!textfield && IsViewClass<EditableCombobox>(view))
textfield = AsViewClass<EditableCombobox>(view)->textfield_;
if (!textfield) {
return ui::test::ActionResult::kNotAttempted;
}
if (textfield->GetReadOnly()) {
LOG(ERROR) << "Cannot set text on read-only textfield.";
return ui::test::ActionResult::kFailed;
}
// Textfield does not expose all of the power of RenderText so some care has
// to be taken in positioning the input caret using the methods available to
// this class.
switch (mode) {
case TextEntryMode::kAppend: {
// Determine the start and end of the selectable range, and position the
// caret immediately after the end of the range. This approach does not
// make any assumptions about the indexing mode of the text,
// multi-codepoint characters, etc.
textfield->SelectAll(false);
auto range = textfield->GetSelectedRange();
range.set_start(range.end());
textfield->SetSelectedRange(range);
break;
}
case TextEntryMode::kInsertOrReplace:
// No action needed; keep selection and cursor as they are.
break;
case TextEntryMode::kReplaceAll:
textfield->SelectAll(false);
break;
}
// This is an IME method that is the closest thing to inserting text from
// the user rather than setting it programmatically.
textfield->InsertText(
text,
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::ActivateSurface(
ui::TrackedElement* element) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const widget = element->AsA<TrackedElementViews>()->view()->GetWidget();
#if HANDLE_WAYLAND_FAILURE
if (ui::OzonePlatform::GetPlatformNameForTest() == "wayland") {
WidgetActivationWaiterWayland waiter(widget);
widget->Activate();
if (!waiter.Wait()) {
LOG(WARNING)
<< "Unable to activate widget due to lack of Wayland support for "
"widget activation; test is not meaningful on this platform.";
return ui::test::ActionResult::kKnownIncompatible;
}
return ui::test::ActionResult::kSucceeded;
}
#endif // HANDLE_WAYLAND_FAILURE
views::test::WidgetActivationWaiter waiter(widget, true);
widget->Activate();
waiter.Wait();
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::SendAccelerator(
ui::TrackedElement* element,
ui::Accelerator accelerator) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
element->AsA<TrackedElementViews>()
->view()
->GetFocusManager()
->ProcessAccelerator(accelerator);
return ui::test::ActionResult::kSucceeded;
}
ui::test::ActionResult InteractionTestUtilSimulatorViews::Confirm(
ui::TrackedElement* element) {
if (!element->IsA<TrackedElementViews>())
return ui::test::ActionResult::kNotAttempted;
auto* const view = element->AsA<TrackedElementViews>()->view();
// Currently, only dialogs can be confirmed. Fetch the delegate and call
// Accept().
DialogDelegate* delegate = nullptr;
if (auto* const dialog = AsViewClass<DialogDelegateView>(view)) {
delegate = dialog->AsDialogDelegate();
} else if (auto* const bubble = AsViewClass<BubbleDialogDelegateView>(view)) {
delegate = bubble->AsDialogDelegate();
}
if (!delegate)
return ui::test::ActionResult::kNotAttempted;
if (!delegate->GetOkButton()) {
LOG(ERROR) << "Confirm(): cannot confirm dialog that has no OK button.";
return ui::test::ActionResult::kFailed;
}
delegate->AcceptDialog();
return ui::test::ActionResult::kSucceeded;
}
bool InteractionTestUtilSimulatorViews::DoDefaultAction(View* view,
InputType input_type) {
switch (input_type) {
case ui::test::InteractionTestUtil::InputType::kDontCare:
return SendDefaultAction(view);
case ui::test::InteractionTestUtil::InputType::kMouse:
SendMouseClick(view, GetCenter(view));
return true;
case ui::test::InteractionTestUtil::InputType::kTouch:
SendTapGesture(view, GetCenter(view));
return true;
case ui::test::InteractionTestUtil::InputType::kKeyboard:
SendKeyPress(view, ui::VKEY_SPACE);
return true;
}
}
// static
void InteractionTestUtilSimulatorViews::PressButton(Button* button,
InputType input_type) {
switch (input_type) {
case ui::test::InteractionTestUtil::InputType::kMouse:
SendMouseClick(button, GetCenter(button));
break;
case ui::test::InteractionTestUtil::InputType::kTouch:
SendTapGesture(button, GetCenter(button));
break;
case ui::test::InteractionTestUtil::InputType::kKeyboard:
case ui::test::InteractionTestUtil::InputType::kDontCare:
SendKeyPress(button, ui::VKEY_SPACE);
break;
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interaction_test_util_views.cc | C++ | unknown | 26,551 |
// 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_INTERACTION_INTERACTION_TEST_UTIL_VIEWS_H_
#define UI_VIEWS_INTERACTION_INTERACTION_TEST_UTIL_VIEWS_H_
#include <string>
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_test_util.h"
namespace ui {
class TrackedElement;
}
namespace views {
class Button;
class View;
}
namespace views::test {
// Views implementation of InteractionTestUtil::Simulator.
// Add one to your InteractionTestUtil instance to get Views support.
class InteractionTestUtilSimulatorViews
: public ui::test::InteractionTestUtil::Simulator {
public:
InteractionTestUtilSimulatorViews();
~InteractionTestUtilSimulatorViews() override;
// ui::test::InteractionTestUtil::Simulator:
ui::test::ActionResult PressButton(ui::TrackedElement* element,
InputType input_type) override;
ui::test::ActionResult SelectMenuItem(ui::TrackedElement* element,
InputType input_type) override;
ui::test::ActionResult DoDefaultAction(ui::TrackedElement* element,
InputType input_type) override;
ui::test::ActionResult SelectTab(ui::TrackedElement* tab_collection,
size_t index,
InputType input_type) override;
ui::test::ActionResult SelectDropdownItem(ui::TrackedElement* dropdown,
size_t index,
InputType input_type) override;
ui::test::ActionResult EnterText(ui::TrackedElement* element,
std::u16string text,
TextEntryMode mode) override;
ui::test::ActionResult ActivateSurface(ui::TrackedElement* element) override;
ui::test::ActionResult SendAccelerator(ui::TrackedElement* element,
ui::Accelerator accelerator) override;
ui::test::ActionResult Confirm(ui::TrackedElement* element) override;
// Convenience method for tests that need to simulate a button press and have
// direct access to the button.
static void PressButton(Button* button,
InputType input_type = InputType::kDontCare);
// As above, but for non-button Views.
static bool DoDefaultAction(View* view,
InputType input_type = InputType::kDontCare);
};
} // namespace views::test
#endif // UI_VIEWS_INTERACTION_INTERACTION_TEST_UTIL_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interaction_test_util_views.h | C++ | unknown | 2,656 |
// 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/interaction/interaction_test_util_views.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/test/bind.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom-shared.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/expect_call_in_scope.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/simple_combobox_model.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/range/range.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/flex_layout_types.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_MAC)
#include "ui/base/interaction/interaction_test_util_mac.h"
#endif
namespace views::test {
namespace {
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kMenuItemIdentifier);
const char16_t kMenuItem1[] = u"Menu item";
const char16_t kMenuItem2[] = u"Menu item 2";
const char16_t kTab1Title[] = u"Tab1";
const char16_t kTab2Title[] = u"Tab2";
const char16_t kTab3Title[] = u"Tab3";
const char16_t kComboBoxItem1[] = u"Item1";
const char16_t kComboBoxItem2[] = u"Item2";
const char16_t kComboBoxItem3[] = u"Item3";
constexpr int kMenuID1 = 1;
constexpr int kMenuID2 = 2;
class DefaultActionTestView : public View {
public:
DefaultActionTestView() = default;
~DefaultActionTestView() override = default;
bool HandleAccessibleAction(const ui::AXActionData& action_data) override {
EXPECT_EQ(ax::mojom::Action::kDoDefault, action_data.action);
EXPECT_FALSE(activated_);
activated_ = true;
return true;
}
bool activated() const { return activated_; }
private:
bool activated_ = false;
};
class AcceleratorView : public View {
public:
explicit AcceleratorView(ui::Accelerator accelerator)
: accelerator_(accelerator) {
AddAccelerator(accelerator);
}
bool AcceleratorPressed(const ui::Accelerator& accelerator) override {
EXPECT_EQ(accelerator_, accelerator);
EXPECT_FALSE(pressed_);
pressed_ = true;
return true;
}
bool CanHandleAccelerators() const override { return true; }
bool pressed() const { return pressed_; }
private:
const ui::Accelerator accelerator_;
bool pressed_ = false;
};
} // namespace
class InteractionTestUtilViewsTest
: public ViewsTestBase,
public testing::WithParamInterface<
ui::test::InteractionTestUtil::InputType> {
public:
InteractionTestUtilViewsTest() = default;
~InteractionTestUtilViewsTest() override = default;
std::unique_ptr<Widget> CreateWidget() {
auto widget = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 650, 650);
widget->Init(std::move(params));
auto* contents = widget->SetContentsView(std::make_unique<View>());
auto* layout = contents->SetLayoutManager(std::make_unique<FlexLayout>());
layout->SetOrientation(LayoutOrientation::kHorizontal);
layout->SetDefault(kFlexBehaviorKey,
FlexSpecification(MinimumFlexSizeRule::kPreferred,
MaximumFlexSizeRule::kUnbounded));
WidgetVisibleWaiter visible_waiter(widget.get());
widget->Show();
visible_waiter.Wait();
return widget;
}
static View* ElementToView(ui::TrackedElement* element) {
return element ? element->AsA<TrackedElementViews>()->view() : nullptr;
}
void CreateMenuModel() {
menu_model_ = std::make_unique<ui::SimpleMenuModel>(nullptr);
menu_model_->AddItem(kMenuID1, kMenuItem1);
menu_model_->AddItem(kMenuID2, kMenuItem2);
menu_model_->SetElementIdentifierAt(1, kMenuItemIdentifier);
}
void ShowMenu() {
CreateMenuModel();
menu_runner_ =
std::make_unique<MenuRunner>(menu_model_.get(), MenuRunner::NO_FLAGS);
menu_runner_->RunMenuAt(
widget_.get(), nullptr, gfx::Rect(gfx::Point(), gfx::Size(200, 200)),
MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_MOUSE);
menu_item_ = AsViewClass<MenuItemView>(ElementToView(
ui::ElementTracker::GetElementTracker()->GetFirstMatchingElement(
kMenuItemIdentifier,
ElementTrackerViews::GetContextForView(contents_))));
Widget* const menu_widget = menu_item_->GetWidget();
test::WidgetVisibleWaiter visible_waiter(menu_widget);
visible_waiter.Wait();
EXPECT_TRUE(menu_item_->GetVisible());
EXPECT_TRUE(menu_item_->GetWidget()->IsVisible());
}
void CloseMenu() {
menu_runner_.reset();
menu_model_.reset();
menu_item_ = nullptr;
}
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = CreateWidget();
contents_ = widget_->GetContentsView();
test_util_ = std::make_unique<ui::test::InteractionTestUtil>();
test_util_->AddSimulator(
std::make_unique<InteractionTestUtilSimulatorViews>());
#if BUILDFLAG(IS_MAC)
test_util_->AddSimulator(
std::make_unique<ui::test::InteractionTestUtilSimulatorMac>());
#endif
}
void TearDown() override {
test_util_.reset();
if (menu_runner_)
CloseMenu();
widget_.reset();
contents_ = nullptr;
ViewsTestBase::TearDown();
}
std::unique_ptr<ui::ComboboxModel> CreateComboboxModel() {
return std::make_unique<ui::SimpleComboboxModel>(
std::vector<ui::SimpleComboboxModel::Item>{
ui::SimpleComboboxModel::Item(kComboBoxItem1),
ui::SimpleComboboxModel::Item(kComboBoxItem2),
ui::SimpleComboboxModel::Item(kComboBoxItem3)});
}
protected:
std::unique_ptr<ui::test::InteractionTestUtil> test_util_;
std::unique_ptr<Widget> widget_;
raw_ptr<View> contents_ = nullptr;
std::unique_ptr<ui::SimpleMenuModel> menu_model_;
std::unique_ptr<MenuRunner> menu_runner_;
raw_ptr<MenuItemView> menu_item_ = nullptr;
};
TEST_P(InteractionTestUtilViewsTest, PressButton) {
UNCALLED_MOCK_CALLBACK(Button::PressedCallback::Callback, pressed);
// Add a spacer view to make sure we're actually trying to send events in the
// appropriate coordinate space.
contents_->AddChildView(
std::make_unique<LabelButton>(Button::PressedCallback(), u"Spacer"));
auto* const button = contents_->AddChildView(std::make_unique<LabelButton>(
Button::PressedCallback(pressed.Get()), u"Button"));
widget_->LayoutRootViewIfNecessary();
EXPECT_CALL_IN_SCOPE(pressed, Run,
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->PressButton(
views::ElementTrackerViews::GetInstance()
->GetElementForView(button, true),
GetParam())));
}
TEST_P(InteractionTestUtilViewsTest, SelectMenuItem) {
ShowMenu();
UNCALLED_MOCK_CALLBACK(ui::ElementTracker::Callback, pressed);
auto subscription =
ui::ElementTracker::GetElementTracker()->AddElementActivatedCallback(
kMenuItemIdentifier,
ElementTrackerViews::GetContextForWidget(widget_.get()),
pressed.Get());
EXPECT_CALL_IN_SCOPE(pressed, Run,
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectMenuItem(
views::ElementTrackerViews::GetInstance()
->GetElementForView(menu_item_),
GetParam())));
}
TEST_P(InteractionTestUtilViewsTest, DoDefault) {
if (GetParam() == ui::test::InteractionTestUtil::InputType::kDontCare) {
// Unfortunately, buttons don't respond to AX events the same way, so use a
// custom view for this one case.
auto* const view =
contents_->AddChildView(std::make_unique<DefaultActionTestView>());
widget_->LayoutRootViewIfNecessary();
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->DoDefaultAction(
views::ElementTrackerViews::GetInstance()->GetElementForView(
view, true)));
EXPECT_TRUE(view->activated());
} else {
// A button can be used for this because we are simulating a usual event
// type, which buttons respond to.
UNCALLED_MOCK_CALLBACK(Button::PressedCallback::Callback, pressed);
// Add a spacer view to make sure we're actually trying to send events in
// the appropriate coordinate space.
contents_->AddChildView(
std::make_unique<LabelButton>(Button::PressedCallback(), u"Spacer"));
auto* const button = contents_->AddChildView(std::make_unique<LabelButton>(
Button::PressedCallback(pressed.Get()), u"Button"));
widget_->LayoutRootViewIfNecessary();
EXPECT_CALL_IN_SCOPE(pressed, Run,
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->DoDefaultAction(
views::ElementTrackerViews::GetInstance()
->GetElementForView(button, true),
GetParam())));
}
}
TEST_P(InteractionTestUtilViewsTest, SelectTab) {
auto* const pane = contents_->AddChildView(std::make_unique<TabbedPane>());
pane->AddTab(kTab1Title, std::make_unique<LabelButton>(
Button::PressedCallback(), u"Button"));
pane->AddTab(kTab2Title, std::make_unique<LabelButton>(
Button::PressedCallback(), u"Button"));
pane->AddTab(kTab3Title, std::make_unique<LabelButton>(
Button::PressedCallback(), u"Button"));
auto* const pane_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(pane, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectTab(pane_el, 2, GetParam()));
EXPECT_EQ(2U, pane->GetSelectedTabIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectTab(pane_el, 0, GetParam()));
EXPECT_EQ(0U, pane->GetSelectedTabIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectTab(pane_el, 1, GetParam()));
EXPECT_EQ(1U, pane->GetSelectedTabIndex());
}
TEST_P(InteractionTestUtilViewsTest, SelectDropdownItem_Combobox) {
#if BUILDFLAG(IS_MAC)
// Only kDontCare is supported on Mac.
if (GetParam() != ui::test::InteractionTestUtil::InputType::kDontCare)
GTEST_SKIP();
#endif
auto* const box = contents_->AddChildView(
std::make_unique<Combobox>(CreateComboboxModel()));
box->SetAccessibleName(u"Combobox");
widget_->LayoutRootViewIfNecessary();
auto* const box_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(box, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 2, GetParam()));
EXPECT_EQ(2U, box->GetSelectedIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 0, GetParam()));
EXPECT_EQ(0U, box->GetSelectedIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 1, GetParam()));
EXPECT_EQ(1U, box->GetSelectedIndex());
}
TEST_P(InteractionTestUtilViewsTest, SelectDropdownItem_EditableCombobox) {
#if BUILDFLAG(IS_MAC)
// Only kDontCare is supported on Mac.
if (GetParam() != ui::test::InteractionTestUtil::InputType::kDontCare)
GTEST_SKIP();
#endif
auto* const box = contents_->AddChildView(
std::make_unique<EditableCombobox>(CreateComboboxModel()));
box->SetAccessibleName(u"Editable Combobox");
widget_->LayoutRootViewIfNecessary();
auto* const box_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(box, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 2, GetParam()));
EXPECT_EQ(kComboBoxItem3, box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 0, GetParam()));
EXPECT_EQ(kComboBoxItem1, box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 1, GetParam()));
EXPECT_EQ(kComboBoxItem2, box->GetText());
}
TEST_P(InteractionTestUtilViewsTest, SelectDropdownItem_Combobox_NoArrow) {
#if BUILDFLAG(IS_MAC)
// Only kDontCare is supported on Mac.
if (GetParam() != ui::test::InteractionTestUtil::InputType::kDontCare)
GTEST_SKIP();
#endif
auto* const box = contents_->AddChildView(
std::make_unique<Combobox>(CreateComboboxModel()));
box->SetShouldShowArrow(false);
box->SetAccessibleName(u"Combobox");
widget_->LayoutRootViewIfNecessary();
auto* const box_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(box, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 2, GetParam()));
EXPECT_EQ(2U, box->GetSelectedIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 0, GetParam()));
EXPECT_EQ(0U, box->GetSelectedIndex());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 1, GetParam()));
EXPECT_EQ(1U, box->GetSelectedIndex());
}
TEST_P(InteractionTestUtilViewsTest,
SelectDropdownItem_EditableCombobox_NoArrow) {
#if BUILDFLAG(IS_MAC)
// Only kDontCare is supported on Mac.
if (GetParam() != ui::test::InteractionTestUtil::InputType::kDontCare)
GTEST_SKIP();
#endif
// These cases are not supported for editable combobox without an arrow
// button; editable comboboxes without arrows trigger on specific text input.
if (GetParam() == ui::test::InteractionTestUtil::InputType::kMouse ||
GetParam() == ui::test::InteractionTestUtil::InputType::kTouch) {
GTEST_SKIP();
}
// Pass the default values for every parameter except for `display_arrow`.
auto* const box = contents_->AddChildView(std::make_unique<EditableCombobox>(
CreateComboboxModel(), false, true, EditableCombobox::kDefaultTextContext,
EditableCombobox::kDefaultTextStyle, /* display_arrow =*/false));
box->SetAccessibleName(u"Editable Combobox");
auto* const box_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(box, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 2, GetParam()));
EXPECT_EQ(kComboBoxItem3, box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 0, GetParam()));
EXPECT_EQ(kComboBoxItem1, box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SelectDropdownItem(box_el, 1, GetParam()));
EXPECT_EQ(kComboBoxItem2, box->GetText());
}
TEST_F(InteractionTestUtilViewsTest, EnterText_Textfield) {
auto* const edit = contents_->AddChildView(std::make_unique<Textfield>());
edit->SetDefaultWidthInChars(20);
widget_->LayoutRootViewIfNecessary();
auto* const edit_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(edit, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(edit_el, u"abcd"));
EXPECT_EQ(u"abcd", edit->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
edit_el, u"efgh",
ui::test::InteractionTestUtil::TextEntryMode::kReplaceAll));
EXPECT_EQ(u"efgh", edit->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
edit_el, u"abcd",
ui::test::InteractionTestUtil::TextEntryMode::kAppend));
EXPECT_EQ(u"efghabcd", edit->GetText());
edit->SetSelectedRange(gfx::Range(2, 6));
EXPECT_EQ(
ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
edit_el, u"1234",
ui::test::InteractionTestUtil::TextEntryMode::kInsertOrReplace));
EXPECT_EQ(u"ef1234cd", edit->GetText());
}
TEST_F(InteractionTestUtilViewsTest, EnterText_EditableCombobox) {
auto* const box = contents_->AddChildView(
std::make_unique<EditableCombobox>(CreateComboboxModel()));
box->SetAccessibleName(u"Editable Combobox");
widget_->LayoutRootViewIfNecessary();
auto* const box_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(box, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(box_el, u"abcd"));
EXPECT_EQ(u"abcd", box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
box_el, u"efgh",
ui::test::InteractionTestUtil::TextEntryMode::kReplaceAll));
EXPECT_EQ(u"efgh", box->GetText());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
box_el, u"abcd",
ui::test::InteractionTestUtil::TextEntryMode::kAppend));
EXPECT_EQ(u"efghabcd", box->GetText());
box->SelectRange(gfx::Range(2, 6));
EXPECT_EQ(
ui::test::ActionResult::kSucceeded,
test_util_->EnterText(
box_el, u"1234",
ui::test::InteractionTestUtil::TextEntryMode::kInsertOrReplace));
EXPECT_EQ(u"ef1234cd", box->GetText());
}
TEST_F(InteractionTestUtilViewsTest, ActivateSurface) {
// Create a bubble that will close on deactivation.
auto dialog_ptr = std::make_unique<BubbleDialogDelegateView>(
contents_, BubbleBorder::Arrow::TOP_LEFT);
dialog_ptr->set_close_on_deactivate(true);
auto* widget = BubbleDialogDelegateView::CreateBubble(std::move(dialog_ptr));
WidgetVisibleWaiter shown_waiter(widget);
widget->Show();
shown_waiter.Wait();
// Activating the primary widget should close the bubble again.
WidgetDestroyedWaiter closed_waiter(widget);
auto* const view_el =
ElementTrackerViews::GetInstance()->GetElementForView(contents_, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->ActivateSurface(view_el));
closed_waiter.Wait();
}
TEST_F(InteractionTestUtilViewsTest, SendAccelerator) {
ui::Accelerator accel(ui::VKEY_F5, ui::EF_SHIFT_DOWN);
ui::Accelerator accel2(ui::VKEY_F6, ui::EF_NONE);
auto* const view =
contents_->AddChildView(std::make_unique<AcceleratorView>(accel));
auto* const view_el =
ElementTrackerViews::GetInstance()->GetElementForView(view, true);
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SendAccelerator(view_el, accel2));
EXPECT_FALSE(view->pressed());
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->SendAccelerator(view_el, accel));
EXPECT_TRUE(view->pressed());
}
TEST_F(InteractionTestUtilViewsTest, Confirm) {
UNCALLED_MOCK_CALLBACK(base::OnceClosure, accept);
auto dialog_ptr = std::make_unique<BubbleDialogDelegateView>(
contents_, BubbleBorder::Arrow::TOP_LEFT);
auto* dialog = dialog_ptr.get();
dialog->SetAcceptCallback(accept.Get());
auto* widget = BubbleDialogDelegateView::CreateBubble(std::move(dialog_ptr));
WidgetVisibleWaiter shown_waiter(widget);
widget->Show();
shown_waiter.Wait();
auto* const dialog_el =
views::ElementTrackerViews::GetInstance()->GetElementForView(dialog,
true);
EXPECT_CALL_IN_SCOPE(accept, Run, {
EXPECT_EQ(ui::test::ActionResult::kSucceeded,
test_util_->Confirm(dialog_el));
WidgetDestroyedWaiter closed_waiter(widget);
closed_waiter.Wait();
});
}
INSTANTIATE_TEST_SUITE_P(
,
InteractionTestUtilViewsTest,
::testing::Values(ui::test::InteractionTestUtil::InputType::kDontCare,
ui::test::InteractionTestUtil::InputType::kMouse,
ui::test::InteractionTestUtil::InputType::kKeyboard,
ui::test::InteractionTestUtil::InputType::kTouch),
[](testing::TestParamInfo<ui::test::InteractionTestUtil::InputType>
input_type) -> std::string {
switch (input_type.param) {
case ui::test::InteractionTestUtil::InputType::kDontCare:
return "DontCare";
case ui::test::InteractionTestUtil::InputType::kMouse:
return "Mouse";
case ui::test::InteractionTestUtil::InputType::kKeyboard:
return "Keyboard";
case ui::test::InteractionTestUtil::InputType::kTouch:
return "Touch";
}
});
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interaction_test_util_views_unittest.cc | C++ | unknown | 21,638 |
// 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/interaction/interactive_views_test.h"
#include <functional>
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_sequence.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/test/ui_controls.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/interaction/interaction_test_util_views.h"
#include "ui/views/view_tracker.h"
#if BUILDFLAG(IS_MAC)
#include "ui/base/interaction/interaction_test_util_mac.h"
#endif
namespace views::test {
using ui::test::internal::SpecifyElement;
namespace {
auto CreateTestUtil() {
auto test_util = std::make_unique<ui::test::InteractionTestUtil>();
test_util->AddSimulator(
std::make_unique<views::test::InteractionTestUtilSimulatorViews>());
#if BUILDFLAG(IS_MAC)
test_util->AddSimulator(
std::make_unique<ui::test::InteractionTestUtilSimulatorMac>());
#endif
return test_util;
}
} // namespace
using ui::test::internal::kInteractiveTestPivotElementId;
InteractiveViewsTestApi::InteractiveViewsTestApi()
: InteractiveViewsTestApi(
std::make_unique<internal::InteractiveViewsTestPrivate>(
CreateTestUtil())) {}
InteractiveViewsTestApi::InteractiveViewsTestApi(
std::unique_ptr<internal::InteractiveViewsTestPrivate> private_test_impl)
: InteractiveTestApi(std::move(private_test_impl)) {}
InteractiveViewsTestApi::~InteractiveViewsTestApi() = default;
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::NameView(
base::StringPiece name,
AbsoluteViewSpecifier spec) {
return NameViewRelative(kInteractiveTestPivotElementId, name,
GetFindViewCallback(std::move(spec)));
}
// static
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::NameChildView(
ElementSpecifier parent,
base::StringPiece name,
ChildViewSpecifier spec) {
return std::move(
NameViewRelative(parent, name, GetFindViewCallback(std::move(spec)))
.SetDescription(
base::StringPrintf("NameChildView( \"%s\" )", name.data())));
}
// static
ui::InteractionSequence::StepBuilder
InteractiveViewsTestApi::NameDescendantView(ElementSpecifier parent,
base::StringPiece name,
ViewMatcher matcher) {
return std::move(
NameViewRelative(
parent, name,
base::BindOnce(
[](ViewMatcher matcher, View* ancestor) -> View* {
auto* const result =
FindMatchingView(ancestor, matcher, /* recursive =*/true);
if (!result) {
LOG(ERROR)
<< "NameDescendantView(): No descendant matches matcher.";
}
return result;
},
matcher))
.SetDescription(
base::StringPrintf("NameDescendantView( \"%s\" )", name.data())));
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::ScrollIntoView(
ElementSpecifier view) {
return std::move(WithView(view, [](View* v) {
v->ScrollViewToVisible();
}).SetDescription("ScrollIntoView()"));
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::MoveMouseTo(
ElementSpecifier reference,
RelativePositionSpecifier position) {
StepBuilder step;
step.SetDescription("MoveMouseTo()");
SpecifyElement(step, reference);
step.SetStartCallback(base::BindOnce(
[](InteractiveViewsTestApi* test, RelativePositionCallback pos_callback,
ui::InteractionSequence* seq, ui::TrackedElement* el) {
test->test_impl().mouse_error_message_.clear();
if (!test->mouse_util().PerformGestures(
test->test_impl().GetWindowHintFor(el),
InteractionTestUtilMouse::MoveTo(
std::move(pos_callback).Run(el)))) {
seq->FailForTesting();
}
},
base::Unretained(this), GetPositionCallback(std::move(position))));
return step;
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::MoveMouseTo(
AbsolutePositionSpecifier position) {
return MoveMouseTo(kInteractiveTestPivotElementId,
GetPositionCallback(std::move(position)));
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::ClickMouse(
ui_controls::MouseButton button,
bool release) {
StepBuilder step;
step.SetDescription("ClickMouse()");
step.SetElementID(kInteractiveTestPivotElementId);
step.SetStartCallback(base::BindOnce(
[](InteractiveViewsTestApi* test, ui_controls::MouseButton button,
bool release, ui::InteractionSequence* seq, ui::TrackedElement* el) {
test->test_impl().mouse_error_message_.clear();
if (!test->mouse_util().PerformGestures(
test->test_impl().GetWindowHintFor(el),
release ? InteractionTestUtilMouse::Click(button)
: InteractionTestUtilMouse::MouseGestures{
InteractionTestUtilMouse::MouseDown(button)})) {
seq->FailForTesting();
}
},
base::Unretained(this), button, release));
step.SetMustRemainVisible(false);
return step;
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::DragMouseTo(
ElementSpecifier reference,
RelativePositionSpecifier position,
bool release) {
StepBuilder step;
step.SetDescription("DragMouseTo()");
SpecifyElement(step, reference);
step.SetStartCallback(base::BindOnce(
[](InteractiveViewsTestApi* test, RelativePositionCallback pos_callback,
bool release, ui::InteractionSequence* seq, ui::TrackedElement* el) {
test->test_impl().mouse_error_message_.clear();
const gfx::Point target = std::move(pos_callback).Run(el);
if (!test->mouse_util().PerformGestures(
test->test_impl().GetWindowHintFor(el),
release ? InteractionTestUtilMouse::DragAndRelease(target)
: InteractionTestUtilMouse::DragAndHold(target))) {
seq->FailForTesting();
}
},
base::Unretained(this), GetPositionCallback(std::move(position)),
release));
return step;
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::DragMouseTo(
AbsolutePositionSpecifier position,
bool release) {
return DragMouseTo(kInteractiveTestPivotElementId,
GetPositionCallback(std::move(position)), release);
}
InteractiveViewsTestApi::StepBuilder InteractiveViewsTestApi::ReleaseMouse(
ui_controls::MouseButton button) {
StepBuilder step;
step.SetDescription("ReleaseMouse()");
step.SetElementID(kInteractiveTestPivotElementId);
step.SetStartCallback(base::BindOnce(
[](InteractiveViewsTestApi* test, ui_controls::MouseButton button,
ui::InteractionSequence* seq, ui::TrackedElement* el) {
test->test_impl().mouse_error_message_.clear();
if (!test->mouse_util().PerformGestures(
test->test_impl().GetWindowHintFor(el),
InteractionTestUtilMouse::MouseUp(button))) {
return seq->FailForTesting();
}
},
base::Unretained(this), button));
step.SetMustRemainVisible(false);
return step;
}
// static
InteractiveViewsTestApi::FindViewCallback
InteractiveViewsTestApi::GetFindViewCallback(AbsoluteViewSpecifier spec) {
if (View** view = absl::get_if<View*>(&spec)) {
CHECK(*view) << "NameView(View*): view must be set.";
return base::BindOnce(
[](const std::unique_ptr<ViewTracker>& ref, View*) {
LOG_IF(ERROR, !ref->view()) << "NameView(View*): view ceased to be "
"valid before step was executed.";
return ref->view();
},
std::make_unique<ViewTracker>(*view));
}
if (std::reference_wrapper<View*>* view =
absl::get_if<std::reference_wrapper<View*>>(&spec)) {
return base::BindOnce(
[](std::reference_wrapper<View*> view, View*) {
LOG_IF(ERROR, !view.get())
<< "NameView(ref(View*)): view pointer is null.";
return view.get();
},
*view);
}
return base::RectifyCallback<FindViewCallback>(
std::move(absl::get<base::OnceCallback<View*()>>(spec)));
}
// static
InteractiveViewsTestApi::FindViewCallback
InteractiveViewsTestApi::GetFindViewCallback(ChildViewSpecifier spec) {
if (size_t* index = absl::get_if<size_t>(&spec)) {
return base::BindOnce(
[](size_t index, View* parent) -> View* {
if (index >= parent->children().size()) {
LOG(ERROR) << "NameChildView(int): Child index out of bounds; got "
<< index << " but only " << parent->children().size()
<< " children.";
return nullptr;
}
return parent->children()[index];
},
*index);
}
return base::BindOnce(
[](ViewMatcher matcher, View* parent) -> View* {
auto* const result =
FindMatchingView(parent, matcher, /*recursive =*/false);
LOG_IF(ERROR, !result)
<< "NameChildView(ViewMatcher): No child matches matcher.";
return result;
},
absl::get<ViewMatcher>(spec));
}
// static
View* InteractiveViewsTestApi::FindMatchingView(const View* from,
ViewMatcher& matcher,
bool recursive) {
for (auto* const child : from->children()) {
if (matcher.Run(child))
return child;
if (recursive) {
auto* const result = FindMatchingView(child, matcher, true);
if (result)
return result;
}
}
return nullptr;
}
void InteractiveViewsTestApi::SetContextWidget(Widget* widget) {
context_widget_ = widget;
if (widget) {
CHECK(!test_impl().mouse_util_)
<< "Changing the context widget during a test is not supported.";
test_impl().mouse_util_ =
std::make_unique<InteractionTestUtilMouse>(widget);
} else {
test_impl().mouse_util_.reset();
}
}
// static
InteractiveViewsTestApi::RelativePositionCallback
InteractiveViewsTestApi::GetPositionCallback(AbsolutePositionSpecifier spec) {
if (auto* point = absl::get_if<gfx::Point>(&spec)) {
return base::BindOnce([](gfx::Point p, ui::TrackedElement*) { return p; },
*point);
}
if (auto** point = absl::get_if<gfx::Point*>(&spec)) {
return base::BindOnce([](gfx::Point* p, ui::TrackedElement*) { return *p; },
base::Unretained(*point));
}
CHECK(absl::holds_alternative<AbsolutePositionCallback>(spec));
return base::RectifyCallback<RelativePositionCallback>(
std::move(absl::get<AbsolutePositionCallback>(spec)));
}
// static
InteractiveViewsTestApi::RelativePositionCallback
InteractiveViewsTestApi::GetPositionCallback(RelativePositionSpecifier spec) {
if (auto* cb = absl::get_if<RelativePositionCallback>(&spec)) {
return std::move(*cb);
}
CHECK(absl::holds_alternative<CenterPoint>(spec));
return base::BindOnce([](ui::TrackedElement* el) {
CHECK(el->IsA<views::TrackedElementViews>());
return el->AsA<views::TrackedElementViews>()
->view()
->GetBoundsInScreen()
.CenterPoint();
});
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interactive_views_test.cc | C++ | unknown | 11,686 |
// 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_INTERACTION_INTERACTIVE_VIEWS_TEST_H_
#define UI_VIEWS_INTERACTION_INTERACTIVE_VIEWS_TEST_H_
#include <functional>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_piece_forward.h"
#include "base/strings/stringprintf.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/interaction/interactive_test.h"
#include "ui/base/interaction/interactive_test_internal.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/interaction/interaction_test_util_mouse.h"
#include "ui/views/interaction/interactive_views_test_internal.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/view_utils.h"
namespace views::test {
// Provides interactive test functionality for Views.
//
// Interactive tests use InteractionSequence, ElementTracker, and
// InteractionTestUtil to provide a common library of concise test methods. This
// convenience API is nicknamed "Kombucha" (see
// //chrome/test/interaction/README.md for more information).
//
// This class is not a test fixture; it is a mixin that can be added to existing
// test classes using `InteractiveViewsTestT<T>` - or just use
// `InteractiveViewsTest`, which *is* a test fixture (preferred; see below).
//
// To use Kombucha for in-process browser tests, instead see:
// //chrome/test/interaction/interactive_browser_test.h
class InteractiveViewsTestApi : public ui::test::InteractiveTestApi {
public:
InteractiveViewsTestApi();
~InteractiveViewsTestApi() override;
// Returns an object that can be used to inject mouse inputs. Generally,
// prefer to use methods like MoveMouseTo, MouseClick, and DragMouseTo.
InteractionTestUtilMouse& mouse_util() { return test_impl().mouse_util(); }
// Shorthand to convert a tracked element into a View. The element should be
// a views::TrackedElementViews and of type `T`.
template <typename T = View>
static T* AsView(ui::TrackedElement* el);
template <typename T = View>
static const T* AsView(const ui::TrackedElement* el);
// Runs a test InteractionSequence from a series of Steps or StepBuilders with
// RunSynchronouslyForTesting(). Hooks both the completed and aborted
// callbacks to ensure completion, and prints an error on failure. The context
// will be pulled from `context_widget()`.
template <typename... Args>
bool RunTestSequence(Args&&... steps);
// Naming views:
//
// The following methods name a view (to be referred to later in the test
// sequence by name) based on some kind of rule or relationship. The View need
// not have an ElementIdentifier assigned ahead of time, so this is useful for
// finding random or dynamically-created views.
//
// For example:
//
// RunTestSequence(
// ...
// NameView(kThirdTabName,
// base::BindLambdaForTesting([&](){
// return browser_view->tabstrip()->tab_at(3);
// }))
// WithElement(kThirdTabName, ...)
// ...
// );
//
// How the view is named will depend on which version of the method you use;
// the
// Determines if a view matches some predicate.
using ViewMatcher = base::RepeatingCallback<bool(const View*)>;
// Specifies a View not relative to any particular other View.
using AbsoluteViewSpecifier = absl::variant<
// Specify a view that is known at the time the sequence is created. The
// View must persist until the step executes.
View*,
// Specify a view pointer that will be valid by the time the step
// executes. Use `std::ref()` to wrap the pointer that will receive the
// value.
std::reference_wrapper<View*>,
// Find and return a view based on an arbitrary rule.
base::OnceCallback<View*()>>;
// Specifies a view relative to its parent.
using ChildViewSpecifier = absl::variant<
// The index of the child in the parent view. An out of bounds index will
// generate an error.
size_t,
// Specifies a filter that is applied to the children; the first child
// view to satisfy the filter (i.e. return true) is named.
ViewMatcher>;
// Methods that name views.
// Names a view relative to another view `relative_to` based on an arbitrary
// rule. The resulting view does not need to be a descendant (or even an
// ancestor) of `relative_to`.
//
// Your `find_callback` should take a pointer to a View or a derived type and
// return a pointer to a View or derived type.
template <typename C,
typename V = internal::ViewArgType<0, C>,
typename R = std::remove_cv_t<
std::remove_pointer_t<ui::test::internal::ReturnTypeOf<C>>>,
typename = ui::test::internal::RequireSignature<C, R*(V*)>>
[[nodiscard]] static StepBuilder NameViewRelative(
ElementSpecifier relative_to,
base::StringPiece name,
C&& find_callback);
[[nodiscard]] static StepBuilder NameView(base::StringPiece name,
AbsoluteViewSpecifier spec);
[[nodiscard]] static StepBuilder NameChildView(ElementSpecifier parent,
base::StringPiece name,
ChildViewSpecifier spec);
[[nodiscard]] static StepBuilder NameDescendantView(ElementSpecifier ancestor,
base::StringPiece name,
ViewMatcher matcher);
// Names the `index` (0-indexed) child view of `parent` that is of type `V`.
template <typename V>
[[nodiscard]] static StepBuilder NameChildViewByType(ElementSpecifier parent,
base::StringPiece name,
size_t index = 0);
// Names the `index` (0-indexed) descendant view of `parent` in depth-first
// traversal order that is of type `V`.
template <typename V>
[[nodiscard]] static StepBuilder NameDescendantViewByType(
ElementSpecifier ancestor,
base::StringPiece name,
size_t index = 0);
// As WithElement(), but `view` should resolve to a TrackedElementViews
// wrapping a view of type `V`.
template <typename F,
typename V = internal::ViewArgType<0, F>,
typename = ui::test::internal::RequireSignature<F, void(V*)>>
[[nodiscard]] static StepBuilder WithView(ElementSpecifier view,
F&& function);
// As CheckElement(), but `view` should resolve to a TrackedElementViews
// wrapping a view of type `V`.
template <typename F,
typename V = internal::ViewArgType<0, F>,
typename = ui::test::internal::RequireSignature<
F,
bool(V*)>> // NOLINT(readability/casting)
[[nodiscard]] static StepBuilder CheckView(ElementSpecifier view, F&& check);
// As CheckView(), but checks that the result of calling `function` on `view`
// matches `matcher`. If not, the mismatch is printed and the test fails.
//
// `matcher` should resolve or convert to type `Matcher<R>`.
template <typename F,
typename M,
typename R = ui::test::internal::ReturnTypeOf<F>,
typename V = internal::ViewArgType<0, F>,
typename = ui::test::internal::RequireSignature<F, R(V*)>>
[[nodiscard]] static StepBuilder CheckView(ElementSpecifier view,
F&& function,
M&& matcher);
// As CheckView() but checks that `matcher` matches the value returned by
// calling `property` on `view`. On failure, logs the matcher error and fails
// the test.
//
// `matcher` must resolve or convert to type `Matcher<R>`.
template <typename V, typename R, typename M>
[[nodiscard]] static StepBuilder CheckViewProperty(ElementSpecifier view,
R (V::*property)() const,
M&& matcher);
// Scrolls `view` into the visible viewport if it is currently scrolled
// outside its container. The view must be otherwise present and visible.
// Has no effect if the view is not in a scroll container.
[[nodiscard]] static StepBuilder ScrollIntoView(ElementSpecifier view);
// Indicates that the center point of the target element should be used for a
// mouse move.
struct CenterPoint {};
// Function that returns a destination for a move or drag.
using AbsolutePositionCallback = base::OnceCallback<gfx::Point()>;
// Specifies an absolute position for a mouse move or drag that does not need
// a reference element.
using AbsolutePositionSpecifier = absl::variant<
// Use this specific position. This value is stored when the sequence is
// created; use gfx::Point* if you want to capture a point during sequence
// execution.
gfx::Point,
// As above, but the position is read from the memory address on execution
// instead of copied when the test sequence is constructed. Use this when
// you want to calculate and cache a point during test execution for later
// use. The pointer must remain valid through the end of the test.
gfx::Point*,
// Use the return value of the supplied callback
AbsolutePositionCallback>;
// Specifies how the `reference_element` should be used (or not) to generate a
// target point for a mouse move.
using RelativePositionCallback =
base::OnceCallback<gfx::Point(ui::TrackedElement* reference_element)>;
// Specifies how the target position of a mouse operation (in screen
// coordinates) will be determined.
using RelativePositionSpecifier = absl::variant<
// Default to the centerpoint of the reference element, which should be a
// views::View.
CenterPoint,
// Use the return value of the supplied callback.
RelativePositionCallback>;
// Move the mouse to the specified `position` in screen coordinates. The
// `reference` element will be used based on how `position` is specified.
[[nodiscard]] StepBuilder MoveMouseTo(AbsolutePositionSpecifier position);
[[nodiscard]] StepBuilder MoveMouseTo(
ElementSpecifier reference,
RelativePositionSpecifier position = CenterPoint());
// Clicks mouse button `button` at the current cursor position.
[[nodiscard]] StepBuilder ClickMouse(
ui_controls::MouseButton button = ui_controls::LEFT,
bool release = true);
// Depresses the left mouse button at the current cursor position and drags to
// the target `position`. The `reference` element will be used based on how
// `position` is specified.
[[nodiscard]] StepBuilder DragMouseTo(AbsolutePositionSpecifier position,
bool release = true);
[[nodiscard]] StepBuilder DragMouseTo(
ElementSpecifier reference,
RelativePositionSpecifier position = CenterPoint(),
bool release = true);
// Releases the specified mouse button. Use when you previously called
// ClickMouse() or DragMouseTo() with `release` = false.
[[nodiscard]] StepBuilder ReleaseMouse(
ui_controls::MouseButton button = ui_controls::LEFT);
// As IfElement(), but `condition` takes a single argument that is a const
// View pointer. If `element` is not a view of type V, then the test will
// fail.
template <typename C,
typename T,
typename U = MultiStep,
typename V = internal::ViewArgType<0, C>,
typename = ui::test::internal::RequireSignature<
C,
bool(const V*)>> // NOLINT(readability/casting)
[[nodiscard]] static StepBuilder IfView(ElementSpecifier element,
C&& condition,
T&& then_steps,
U&& else_steps = MultiStep());
// As IfElementMatches(), but `function` takes a single argument that is a
// const View pointer. If `element` is not a view of type V, then the test
// will fail.
template <typename F,
typename M,
typename T,
typename U = MultiStep,
typename R = ui::test::internal::ReturnTypeOf<F>,
typename V = internal::ViewArgType<0, F>,
typename = ui::test::internal::RequireSignature<F, R(const V*)>>
[[nodiscard]] static StepBuilder IfViewMatches(ElementSpecifier element,
F&& function,
M&& matcher,
T&& then_steps,
U&& else_steps = MultiStep());
// Executes `then_steps` if `property` of the view `element` (which must be of
// the correct View type) matches `matcher`, otherwise executes `else_steps`.
//
// Note that bare literal strings cannot be passed as `matcher` for properties
// with string values, you will need to either explicitly pass a
// std::[u16]string or explicitly construct a testing::Eq matcher.
template <typename R,
typename M,
typename V,
typename T,
typename U = MultiStep>
[[nodiscard]] static StepBuilder IfViewPropertyMatches(
ElementSpecifier element,
R (V::*property)() const,
M&& matcher,
T&& then_steps,
U&& else_steps = MultiStep());
// Sets the context widget. Must be called before RunTestSequence() or any of
// the mouse functions.
void SetContextWidget(Widget* context_widget);
Widget* context_widget() { return context_widget_; }
protected:
explicit InteractiveViewsTestApi(
std::unique_ptr<internal::InteractiveViewsTestPrivate> private_test_impl);
private:
using FindViewCallback = base::OnceCallback<View*(View*)>;
static FindViewCallback GetFindViewCallback(AbsoluteViewSpecifier spec);
static FindViewCallback GetFindViewCallback(ChildViewSpecifier spec);
// Recursively finds an element that matches `matcher` starting with (but
// not including) `from`. If `recursive` is true, searches all descendants,
// otherwise searches children.
static views::View* FindMatchingView(const views::View* from,
ViewMatcher& matcher,
bool recursive);
// Converts a *PositionSpecifier to an appropriate *PositionCallback.
static RelativePositionCallback GetPositionCallback(
AbsolutePositionSpecifier spec);
static RelativePositionCallback GetPositionCallback(
RelativePositionSpecifier spec);
internal::InteractiveViewsTestPrivate& test_impl() {
return static_cast<internal::InteractiveViewsTestPrivate&>(
InteractiveTestApi::private_test_impl());
}
// Creates the follow-up step for a mouse action.
StepBuilder CreateMouseFollowUpStep(const base::StringPiece& description);
base::raw_ptr<Widget, DanglingUntriaged> context_widget_ = nullptr;
};
// Template that adds InteractiveViewsTestApi to any test fixture. Prefer to use
// InteractiveViewsTest unless you specifically need to inherit from another
// test class.
//
// You must call SetContextWidget() before using RunTestSequence() or any of the
// mouse actions.
//
// See //chrome/test/interaction/README.md for usage.
template <typename T>
class InteractiveViewsTestT : public T, public InteractiveViewsTestApi {
public:
template <typename... Args>
explicit InteractiveViewsTestT(Args&&... args)
: T(std::forward<Args>(args)...) {}
~InteractiveViewsTestT() override = default;
protected:
void SetUp() override {
T::SetUp();
private_test_impl().DoTestSetUp();
}
void TearDown() override {
private_test_impl().DoTestTearDown();
T::TearDown();
}
};
// Convenience test fixture for Views tests that supports
// InteractiveViewsTestApi.
//
// You must call SetContextWidget() before using RunTestSequence() or any of the
// mouse actions.
//
// See //chrome/test/interaction/README.md for usage.
using InteractiveViewsTest = InteractiveViewsTestT<ViewsTestBase>;
// Template definitions:
// static
template <class T>
T* InteractiveViewsTestApi::AsView(ui::TrackedElement* el) {
auto* const views_el = el->AsA<TrackedElementViews>();
CHECK(views_el);
T* const view = AsViewClass<T>(views_el->view());
CHECK(view);
return view;
}
// static
template <class T>
const T* InteractiveViewsTestApi::AsView(const ui::TrackedElement* el) {
const auto* const views_el = el->AsA<TrackedElementViews>();
CHECK(views_el);
const T* const view = AsViewClass<T>(views_el->view());
CHECK(view);
return view;
}
template <typename... Args>
bool InteractiveViewsTestApi::RunTestSequence(Args&&... steps) {
return RunTestSequenceInContext(
ElementTrackerViews::GetContextForWidget(context_widget()),
std::forward<Args>(steps)...);
}
// static
template <typename C, typename V, typename R, typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::NameViewRelative(
ElementSpecifier relative_to,
base::StringPiece name,
C&& find_callback) {
StepBuilder builder;
builder.SetDescription(
base::StringPrintf("NameViewRelative( \"%s\" )", name.data()));
ui::test::internal::SpecifyElement(builder, relative_to);
builder.SetMustBeVisibleAtStart(true);
builder.SetStartCallback(base::BindOnce(
[](base::OnceCallback<R*(V*)> find_callback, std::string name,
ui::InteractionSequence* seq, ui::TrackedElement* el) {
V* relative_to = nullptr;
if (el->identifier() !=
ui::test::internal::kInteractiveTestPivotElementId) {
if (!el->IsA<TrackedElementViews>()) {
LOG(ERROR) << "NameView(): Target element is not a View.";
seq->FailForTesting();
return;
}
View* const view = el->AsA<TrackedElementViews>()->view();
if (!IsViewClass<V>(view)) {
LOG(ERROR) << "NameView(): Target View is of type "
<< view->GetClassName() << " but expected "
<< V::MetaData()->type_name();
seq->FailForTesting();
return;
}
relative_to = AsViewClass<V>(view);
}
View* const result = std::move(find_callback).Run(relative_to);
if (!result) {
LOG(ERROR) << "NameView(): No View found.";
seq->FailForTesting();
return;
}
auto* const target_element =
ElementTrackerViews::GetInstance()->GetElementForView(
result, /* assign_temporary_id =*/true);
if (!target_element) {
LOG(ERROR)
<< "NameView(): attempting to name View that is not visible.";
seq->FailForTesting();
return;
}
seq->NameElement(target_element, name);
},
ui::test::internal::MaybeBind(std::forward<C>(find_callback)),
std::string(name)));
return builder;
}
// static
template <typename F, typename V, typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::WithView(
ElementSpecifier view,
F&& function) {
StepBuilder builder;
builder.SetDescription("WithView()");
ui::test::internal::SpecifyElement(builder, view);
builder.SetMustBeVisibleAtStart(true);
builder.SetStartCallback(base::BindOnce(
[](base::OnceCallback<void(V*)> function, ui::InteractionSequence* seq,
ui::TrackedElement* el) { std::move(function).Run(AsView<V>(el)); },
ui::test::internal::MaybeBind(std::forward<F>(function))));
return builder;
}
// static
template <typename C, typename T, typename U, typename V, typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::IfView(
ElementSpecifier element,
C&& condition,
T&& then_steps,
U&& else_steps) {
return std::move(
IfElement(element,
base::BindOnce(
[](base::OnceCallback<bool(const V*)> condition,
const ui::InteractionSequence* seq,
const ui::TrackedElement* el) {
const V* const view = el ? AsView<V>(el) : nullptr;
return std::move(condition).Run(view);
},
ui::test::internal::MaybeBind(std::forward<C>(condition))),
std::forward<T>(then_steps), std::forward<U>(else_steps))
.SetDescription("IfView()"));
}
// static
template <typename F,
typename M,
typename T,
typename U,
typename R,
typename V,
typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::IfViewMatches(
ElementSpecifier element,
F&& function,
M&& matcher,
T&& then_steps,
U&& else_steps) {
return std::move(
IfElementMatches(
element,
base::BindOnce(
[](base::OnceCallback<R(const V*)> condition,
const ui::InteractionSequence* seq,
const ui::TrackedElement* el) {
const V* const view = el ? AsView<V>(el) : nullptr;
return std::move(condition).Run(view);
},
ui::test::internal::MaybeBind(std::forward<F>(function))),
testing::Matcher<R>(std::forward<M>(matcher)),
std::forward<T>(then_steps), std::forward<U>(else_steps))
.SetDescription("IfViewMatches()"));
}
// static
template <typename R, typename M, typename V, typename T, typename U>
ui::InteractionSequence::StepBuilder
InteractiveViewsTestApi::IfViewPropertyMatches(ElementSpecifier element,
R (V::*property)() const,
M&& matcher,
T&& then_steps,
U&& else_steps) {
using Return = std::remove_cvref_t<R>;
base::OnceCallback<Return(const V*)> function = base::BindOnce(
[](R (V::*property)() const, const V* view) -> Return {
return (view->*property)();
},
std::move(property));
return std::move(
IfViewMatches(element, std::move(function), std::forward<M>(matcher),
std::forward<T>(then_steps), std::forward<U>(else_steps))
.SetDescription("IfViewPropertyMatches()"));
}
// static
template <typename V>
ui::InteractionSequence::StepBuilder
InteractiveViewsTestApi::NameChildViewByType(ElementSpecifier parent,
base::StringPiece name,
size_t index) {
return std::move(
NameChildView(parent, name,
base::BindRepeating(
[](size_t& index, const View* view) {
if (IsViewClass<V>(view)) {
if (index == 0) {
return true;
}
--index;
}
return false;
},
base::OwnedRef(index)))
.SetDescription(base::StringPrintf(
"NameChildViewByType<%s>( \"%s\" %zu )",
V::MetaData()->type_name().c_str(), name.data(), index)));
}
// static
template <typename V>
ui::InteractionSequence::StepBuilder
InteractiveViewsTestApi::NameDescendantViewByType(ElementSpecifier ancestor,
base::StringPiece name,
size_t index) {
return std::move(
NameDescendantView(ancestor, name,
base::BindRepeating(
[](size_t& index, const View* view) {
if (IsViewClass<V>(view)) {
if (index == 0) {
return true;
}
--index;
}
return false;
},
base::OwnedRef(index)))
.SetDescription(base::StringPrintf(
"NameDescendantViewByType<%s>( \"%s\" %zu )",
V::MetaData()->type_name().c_str(), name.data(), index)));
}
// static
template <typename F, typename, typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::CheckView(
ElementSpecifier view,
F&& check) {
return CheckView(view, std::forward<F>(check), true);
}
// static
template <typename F, typename M, typename R, typename V, typename>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::CheckView(
ElementSpecifier view,
F&& function,
M&& matcher) {
StepBuilder builder;
builder.SetDescription("CheckView()");
ui::test::internal::SpecifyElement(builder, view);
builder.SetStartCallback(base::BindOnce(
[](base::OnceCallback<R(V*)> function, testing::Matcher<R> matcher,
ui::InteractionSequence* seq, ui::TrackedElement* el) {
if (!ui::test::internal::MatchAndExplain(
"CheckView()", matcher,
std::move(function).Run(AsView<V>(el)))) {
seq->FailForTesting();
}
},
ui::test::internal::MaybeBind(std::forward<F>(function)),
testing::Matcher<R>(std::forward<M>(matcher))));
return builder;
}
// static
template <typename V, typename R, typename M>
ui::InteractionSequence::StepBuilder InteractiveViewsTestApi::CheckViewProperty(
ElementSpecifier view,
R (V::*property)() const,
M&& matcher) {
StepBuilder builder;
builder.SetDescription("CheckViewProperty()");
ui::test::internal::SpecifyElement(builder, view);
builder.SetStartCallback(base::BindOnce(
[](R (V::*property)() const, testing::Matcher<R> matcher,
ui::InteractionSequence* seq, ui::TrackedElement* el) {
if (!ui::test::internal::MatchAndExplain(
"CheckViewProperty()", matcher, (AsView<V>(el)->*property)())) {
seq->FailForTesting();
}
},
property, testing::Matcher<R>(std::forward<M>(matcher))));
return builder;
}
} // namespace views::test
#endif // UI_VIEWS_INTERACTION_INTERACTIVE_VIEWS_TEST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interactive_views_test.h | C++ | unknown | 26,957 |
// 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/interaction/interactive_views_test_internal.h"
#include <memory>
#include <utility>
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/native_window_tracker.h"
#include "ui/views/widget/widget.h"
namespace views::test::internal {
// Caches the last-known native window associated with a context.
// Useful for executing ClickMouse() and ReleaseMouse() commands, as no target
// element is provided for those commands. A NativeWindowTracker is used to
// prevent using a cached value after the native window has been destroyed.
class InteractiveViewsTestPrivate::WindowHintCacheEntry {
public:
WindowHintCacheEntry() = default;
~WindowHintCacheEntry() = default;
WindowHintCacheEntry(WindowHintCacheEntry&& other) = default;
WindowHintCacheEntry& operator=(WindowHintCacheEntry&& other) = default;
bool IsValid() const {
return window_ && tracker_ && !tracker_->WasNativeWindowDestroyed();
}
gfx::NativeWindow GetWindow() const {
return IsValid() ? window_ : gfx::NativeWindow();
}
void SetWindow(gfx::NativeWindow window) {
if (window_ == window)
return;
window_ = window;
tracker_ = window ? views::NativeWindowTracker::Create(window) : nullptr;
}
private:
gfx::NativeWindow window_ = gfx::NativeWindow();
std::unique_ptr<NativeWindowTracker> tracker_;
};
InteractiveViewsTestPrivate::InteractiveViewsTestPrivate(
std::unique_ptr<ui::test::InteractionTestUtil> test_util)
: InteractiveTestPrivate(std::move(test_util)) {}
InteractiveViewsTestPrivate::~InteractiveViewsTestPrivate() = default;
void InteractiveViewsTestPrivate::OnSequenceComplete() {
mouse_util_->CancelAllGestures();
InteractiveTestPrivate::OnSequenceComplete();
}
void InteractiveViewsTestPrivate::OnSequenceAborted(
const ui::InteractionSequence::AbortedData& data) {
mouse_util_->CancelAllGestures();
InteractiveTestPrivate::OnSequenceAborted(data);
}
gfx::NativeWindow InteractiveViewsTestPrivate::GetWindowHintFor(
ui::TrackedElement* el) {
// See if the native window can be extracted directly from the element.
gfx::NativeWindow window = GetNativeWindowFromElement(el);
// If not, see if the window can be extracted from the context (perhaps via
// the cache).
if (!window)
window = GetNativeWindowFromContext(el->context());
// If a window was found, then a cache entry may need to be inserted/updated.
if (window) {
// This is just a find if the entry already exists.
auto result =
window_hint_cache_.try_emplace(el->context(), WindowHintCacheEntry());
// This is a no-op if this is already the cached window.
result.first->second.SetWindow(window);
}
return window;
}
gfx::NativeWindow InteractiveViewsTestPrivate::GetNativeWindowFromElement(
ui::TrackedElement* el) const {
gfx::NativeWindow window = gfx::NativeWindow();
if (el->IsA<TrackedElementViews>()) {
// Most widgets have an associated native window.
Widget* const widget = el->AsA<TrackedElementViews>()->view()->GetWidget();
window = widget->GetNativeWindow();
// Most of those that don't are sub-widgets that are hard-parented to
// another widget.
if (!window && widget->parent())
window = widget->parent()->GetNativeWindow();
// At worst case, fall back to the primary window.
if (!window)
window = widget->GetPrimaryWindowWidget()->GetNativeWindow();
}
return window;
}
gfx::NativeWindow InteractiveViewsTestPrivate::GetNativeWindowFromContext(
ui::ElementContext context) const {
// Used the cached value, if one exists.
const auto it = window_hint_cache_.find(context);
return it != window_hint_cache_.end() ? it->second.GetWindow()
: gfx::NativeWindow();
}
} // namespace views::test::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interactive_views_test_internal.cc | C++ | unknown | 4,227 |
// 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_INTERACTION_INTERACTIVE_VIEWS_TEST_INTERNAL_H_
#define UI_VIEWS_INTERACTION_INTERACTIVE_VIEWS_TEST_INTERNAL_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_sequence.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/interaction/interactive_test_internal.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/interaction/interaction_test_util_mouse.h"
namespace views {
class NativeWindowTracker;
}
namespace views::test {
class InteractiveViewsTestApi;
namespace internal {
// Provides functionality required by InteractiveViewsTestApi but which needs to
// be hidden from tests inheriting from the API class.
class InteractiveViewsTestPrivate
: public ui::test::internal::InteractiveTestPrivate {
public:
explicit InteractiveViewsTestPrivate(
std::unique_ptr<ui::test::InteractionTestUtil> test_util);
~InteractiveViewsTestPrivate() override;
// base::test::internal::InteractiveTestPrivate:
void OnSequenceComplete() override;
void OnSequenceAborted(
const ui::InteractionSequence::AbortedData& data) override;
InteractionTestUtilMouse& mouse_util() { return *mouse_util_; }
gfx::NativeWindow GetWindowHintFor(ui::TrackedElement* el);
protected:
// Retrieves the native window from an element. Used by GetWindowHintFor().
virtual gfx::NativeWindow GetNativeWindowFromElement(
ui::TrackedElement* el) const;
// Retrieves the native window from a context. Used by GetWindowHintFor().
virtual gfx::NativeWindow GetNativeWindowFromContext(
ui::ElementContext context) const;
private:
friend class views::test::InteractiveViewsTestApi;
class WindowHintCacheEntry;
// Provides mouse input simulation.
std::unique_ptr<InteractionTestUtilMouse> mouse_util_;
// Tracks failures when a mouse operation fails.
std::string mouse_error_message_;
// Safely tracks the most recent native window targeted in each context.
// For actions like ClickMouse() or ReleaseMouse(), a pivot element is used
// so only the context is known; a NativeWindowTracker must be used to verify
// that the cached information is still valid.
std::map<ui::ElementContext, WindowHintCacheEntry> window_hint_cache_;
};
template <size_t N, typename F>
using ViewArgType = std::remove_cv_t<
std::remove_pointer_t<ui::test::internal::NthArgumentOf<N, F>>>;
} // namespace internal
} // namespace views::test
#endif // UI_VIEWS_INTERACTION_INTERACTIVE_VIEWS_TEST_INTERNAL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interactive_views_test_internal.h | C++ | unknown | 2,800 |
// 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/interaction/interactive_views_test.h"
#include <functional>
#include <memory>
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/expect_call_in_scope.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/flex_layout_view.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_utils.h"
namespace views::test {
namespace {
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kContentsId);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kButtonsId);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kButton1Id);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kTabbedPaneId);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kScrollChild1Id);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kScrollChild2Id);
constexpr char16_t kButton1Caption[] = u"Button 1";
constexpr char16_t kButton2Caption[] = u"Button 2";
constexpr char16_t kTab1Title[] = u"Tab 1";
constexpr char16_t kTab2Title[] = u"Tab 2";
constexpr char16_t kTab3Title[] = u"Tab 3";
constexpr char16_t kTab1Contents[] = u"Tab 1 Contents";
constexpr char16_t kTab2Contents[] = u"Tab 2 Contents";
constexpr char16_t kTab3Contents[] = u"Tab 3 Contents";
constexpr char kViewName[] = "Named View";
constexpr char kViewName2[] = "Second Named View";
} // namespace
class InteractiveViewsTestTest : public InteractiveViewsTest {
public:
InteractiveViewsTestTest() = default;
~InteractiveViewsTestTest() override = default;
void SetUp() override {
InteractiveViewsTest::SetUp();
// Set up the Views hierarchy to use for the tests.
auto contents =
Builder<FlexLayoutView>()
.CopyAddressTo(&contents_)
.SetProperty(kElementIdentifierKey, kContentsId)
.SetOrientation(LayoutOrientation::kVertical)
.AddChildren(
Builder<TabbedPane>()
.CopyAddressTo(&tabs_)
.SetProperty(kElementIdentifierKey, kTabbedPaneId)
.AddTab(kTab1Title, std::make_unique<Label>(kTab1Contents))
.AddTab(kTab2Title, std::make_unique<Label>(kTab2Contents))
.AddTab(kTab3Title, std::make_unique<Label>(kTab3Contents)),
Builder<FlexLayoutView>()
.CopyAddressTo(&buttons_)
.SetProperty(kElementIdentifierKey, kButtonsId)
.SetOrientation(LayoutOrientation::kHorizontal)
.AddChildren(
Builder<LabelButton>()
.CopyAddressTo(&button1_)
.SetProperty(kElementIdentifierKey, kButton1Id)
.SetText(kButton1Caption)
.SetCallback(button1_callback_.Get()),
Builder<LabelButton>()
.CopyAddressTo(&button2_)
.SetText(kButton2Caption)
.SetCallback(button2_callback_.Get())),
Builder<ScrollView>()
.CopyAddressTo(&scroll_)
.SetPreferredSize(gfx::Size(100, 90))
.SetVerticalScrollBarMode(
ScrollView::ScrollBarMode::kEnabled)
.SetContents(
Builder<FlexLayoutView>()
.SetOrientation(LayoutOrientation::kVertical)
.SetSize(gfx::Size(100, 200))
.AddChildren(
Builder<View>()
.SetProperty(kElementIdentifierKey,
kScrollChild1Id)
.SetPreferredSize(gfx::Size(100, 100)),
Builder<View>()
.SetProperty(kElementIdentifierKey,
kScrollChild2Id)
.SetPreferredSize(gfx::Size(100, 100)))));
// Create and show the test widget.
widget_ = CreateTestWidget();
widget_->SetContentsView(std::move(contents).Build());
WidgetVisibleWaiter waiter(widget_.get());
widget_->Show();
waiter.Wait();
widget_->LayoutRootViewIfNecessary();
// This is required before RunTestSequence() can be called.
SetContextWidget(widget_.get());
}
void TearDown() override {
SetContextWidget(nullptr);
widget_.reset();
contents_ = nullptr;
tabs_ = nullptr;
buttons_ = nullptr;
button1_ = nullptr;
button2_ = nullptr;
scroll_ = nullptr;
InteractiveViewsTest::TearDown();
}
protected:
using ButtonCallbackMock = testing::StrictMock<
base::MockCallback<Button::PressedCallback::Callback>>;
std::unique_ptr<Widget> widget_;
base::raw_ptr<FlexLayoutView> contents_;
base::raw_ptr<TabbedPane> tabs_;
base::raw_ptr<FlexLayoutView> buttons_;
base::raw_ptr<LabelButton> button1_;
base::raw_ptr<LabelButton> button2_;
base::raw_ptr<ScrollView> scroll_;
ButtonCallbackMock button1_callback_;
ButtonCallbackMock button2_callback_;
};
TEST_F(InteractiveViewsTestTest, WithView) {
RunTestSequence(WithView(kButton1Id, base::BindOnce([](LabelButton* button) {
EXPECT_TRUE(button->GetVisible());
})),
// Check version with arbitrary return value and matcher.
WithView(kTabbedPaneId, base::BindOnce([](TabbedPane* tabs) {
EXPECT_EQ(3U, tabs->GetTabCount());
})));
}
TEST_F(InteractiveViewsTestTest, CheckView) {
RunTestSequence(
// Check version with no matcher and only boolean return value.
CheckView(kButton1Id, base::BindOnce([](LabelButton* button) {
return button->GetVisible();
})),
// Check version with arbitrary return value and matcher.
CheckView(kTabbedPaneId, base::BindOnce([](TabbedPane* tabs) {
return tabs->GetTabCount();
}),
testing::Gt(2U)));
}
TEST_F(InteractiveViewsTestTest, CheckViewFails) {
UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted);
private_test_impl().set_aborted_callback_for_testing(aborted.Get());
EXPECT_CALL_IN_SCOPE(
aborted, Run,
RunTestSequence(
// Check version with no matcher and only boolean return value.
CheckView(kButton1Id, base::BindOnce([](LabelButton* button) {
return !button->GetVisible();
}))));
}
TEST_F(InteractiveViewsTestTest, CheckViewProperty) {
RunTestSequence(
CheckViewProperty(kButton1Id, &LabelButton::GetText,
// Implicit creation of an equality matcher.
kButton1Caption),
CheckViewProperty(kTabbedPaneId, &TabbedPane::GetSelectedTabIndex,
// Explicit creation of an inequality matcher.
testing::Ne(1U)));
}
TEST_F(InteractiveViewsTestTest, CheckViewPropertyFails) {
UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted);
private_test_impl().set_aborted_callback_for_testing(aborted.Get());
EXPECT_CALL_IN_SCOPE(
aborted, Run,
RunTestSequence(CheckViewProperty(
kTabbedPaneId, &TabbedPane::GetSelectedTabIndex, testing::Eq(1U))));
}
TEST_F(InteractiveViewsTestTest, NameViewAbsoluteValue) {
RunTestSequence(
NameView(kViewName, button2_.get()),
WithElement(kViewName,
base::BindLambdaForTesting([&](ui::TrackedElement* el) {
EXPECT_EQ(button2_.get(), AsView<LabelButton>(el));
})));
}
TEST_F(InteractiveViewsTestTest, NameViewAbsoluteDeferred) {
View* view = nullptr;
RunTestSequence(
Do(base::BindLambdaForTesting([&]() { view = button2_.get(); })),
NameView(kViewName, std::ref(view)),
WithElement(kViewName,
base::BindLambdaForTesting([&](ui::TrackedElement* el) {
EXPECT_EQ(view, AsView(el));
})));
}
TEST_F(InteractiveViewsTestTest, NameViewAbsoluteCallback) {
RunTestSequence(
NameView(kViewName, base::BindLambdaForTesting(
[&]() -> View* { return button2_.get(); })),
WithElement(kViewName,
base::BindLambdaForTesting([&](ui::TrackedElement* el) {
EXPECT_EQ(button2_.get(), AsView<LabelButton>(el));
})));
}
TEST_F(InteractiveViewsTestTest, NameChildViewByIndex) {
RunTestSequence(
NameChildView(kButtonsId, kViewName, 1U),
WithElement(kViewName,
base::BindLambdaForTesting([&](ui::TrackedElement* el) {
auto* const button = AsView<LabelButton>(el);
EXPECT_EQ(button2_.get(), button);
EXPECT_EQ(1U, button->parent()->GetIndexOf(button));
})));
}
TEST_F(InteractiveViewsTestTest, NameChildViewByFilter) {
EXPECT_CALL_IN_SCOPE(
button2_callback_, Run,
RunTestSequence(
NameChildView(
kButtonsId, kViewName, base::BindRepeating([](const View* view) {
const auto* const button = AsViewClass<LabelButton>(view);
return button && button->GetText() == kButton2Caption;
})),
PressButton(kViewName, InputType::kKeyboard)));
}
TEST_F(InteractiveViewsTestTest, NameDescendantView) {
EXPECT_CALL_IN_SCOPE(
button1_callback_, Run,
RunTestSequence(NameDescendantView(
kContentsId, kViewName,
base::BindRepeating([&](const View* view) {
return view->GetProperty(kElementIdentifierKey) ==
kButton1Id;
})),
PressButton(kViewName, InputType::kMouse)));
}
TEST_F(InteractiveViewsTestTest, NameViewRelative) {
RunTestSequence(
SelectTab(kTabbedPaneId, 1U, InputType::kTouch),
NameViewRelative(kTabbedPaneId, kViewName,
base::BindRepeating([&](TabbedPane* tabs) {
return tabs->GetTabAt(1U)->contents();
})),
WithElement(kViewName,
base::BindLambdaForTesting([&](ui::TrackedElement* el) {
EXPECT_EQ(kTab2Contents, AsView<Label>(el)->GetText());
})));
}
TEST_F(InteractiveViewsTestTest, NameChildViewFails) {
UNCALLED_MOCK_CALLBACK(ui::InteractionSequence::AbortedCallback, aborted);
private_test_impl().set_aborted_callback_for_testing(aborted.Get());
EXPECT_CALL_IN_SCOPE(
aborted, Run,
RunTestSequence(
NameChildView(
kButtonsId, kViewName, base::BindRepeating([](const View* view) {
const auto* const button = AsViewClass<LabelButton>(view);
return button && button->GetText() ==
u"This is not a valid button caption.";
})),
PressButton(kViewName, InputType::kKeyboard)));
}
TEST_F(InteractiveViewsTestTest, NameChildViewByTypeAndIndex) {
EXPECT_CALLS_IN_SCOPE_2(
button1_callback_, Run, button2_callback_, Run,
RunTestSequence(
NameChildViewByType<views::LabelButton>(kButtonsId, kViewName),
NameChildViewByType<views::LabelButton>(kButtonsId, kViewName2, 1),
PressButton(kViewName), PressButton(kViewName2)));
}
TEST_F(InteractiveViewsTestTest, NameDescendantViewByTypeAndIndex) {
RunTestSequence(
NameDescendantViewByType<views::TabbedPaneTab>(kContentsId, kViewName),
NameDescendantViewByType<views::TabbedPaneTab>(kContentsId, kViewName2,
2),
CheckViewProperty(kViewName, &views::TabbedPaneTab::GetTitleText,
kTab1Title),
CheckViewProperty(kViewName2, &views::TabbedPaneTab::GetTitleText,
kTab3Title));
}
TEST_F(InteractiveViewsTestTest, IfViewTrue) {
UNCALLED_MOCK_CALLBACK(base::OnceCallback<bool(const LabelButton*)>,
condition);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(condition, Run(button1_.get())).WillOnce(testing::Return(true));
EXPECT_CALL(step1, Run);
RunTestSequence(
IfView(kButton1Id, condition.Get(), Do(step1.Get()), Do(step2.Get())));
}
TEST_F(InteractiveViewsTestTest, IfViewFalse) {
UNCALLED_MOCK_CALLBACK(base::OnceCallback<bool(const LabelButton*)>,
condition);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(condition, Run(button1_.get())).WillOnce(testing::Return(false));
EXPECT_CALL(step2, Run);
RunTestSequence(
IfView(kButton1Id, condition.Get(), Do(step1.Get()), Do(step2.Get())));
}
TEST_F(InteractiveViewsTestTest, IfViewMatchesTrue) {
UNCALLED_MOCK_CALLBACK(base::OnceCallback<int(const LabelButton*)>,
condition);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(condition, Run(button1_.get())).WillOnce(testing::Return(1));
EXPECT_CALL(step1, Run);
RunTestSequence(IfViewMatches(kButton1Id, condition.Get(), 1, Do(step1.Get()),
Do(step2.Get())));
}
TEST_F(InteractiveViewsTestTest, IfViewMatchesFalse) {
UNCALLED_MOCK_CALLBACK(base::OnceCallback<int(const LabelButton*)>,
condition);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(condition, Run(button1_.get())).WillOnce(testing::Return(2));
EXPECT_CALL(step2, Run);
RunTestSequence(IfViewMatches(kButton1Id, condition.Get(), 1, Do(step1.Get()),
Do(step2.Get())));
}
TEST_F(InteractiveViewsTestTest, IfViewPropertyMatchesTrue) {
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(step1, Run);
RunTestSequence(IfViewPropertyMatches(kButton1Id, &LabelButton::GetText,
std::u16string(kButton1Caption),
Do(step1.Get()), Do(step2.Get())));
}
TEST_F(InteractiveViewsTestTest, IfViewPropertyMatchesFalse) {
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step1);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, step2);
EXPECT_CALL(step2, Run);
RunTestSequence(IfViewPropertyMatches(kButton1Id, &LabelButton::GetText,
testing::Ne(kButton1Caption),
Do(step1.Get()), Do(step2.Get())));
}
// Test that elements named in the main test sequence are available in
// subsequences.
TEST_F(InteractiveViewsTestTest, InParallelNamedView) {
auto is_view = []() {
return base::BindOnce([](View* actual) { return actual; });
};
RunTestSequence(
// Name two views. Each will be referenced in a subsequence.
NameView(kViewName, button1_.get()), NameView(kViewName2, button2_.get()),
// Run subsequences, each of which references a different named view from
// the outer sequence. Both should succeed.
InParallel(CheckView(kViewName, is_view(), button1_),
CheckView(kViewName2, is_view(), button2_)));
}
// Test that various automatic binding methods work with verbs and conditions.
TEST_F(InteractiveViewsTestTest, BindingMethods) {
UNCALLED_MOCK_CALLBACK(base::OnceClosure, correct);
UNCALLED_MOCK_CALLBACK(base::OnceClosure, incorrect);
auto get_second_tab = [](TabbedPane* tabs) { return tabs->GetTabAt(1U); };
EXPECT_CALL(correct, Run).Times(2);
RunTestSequence(
SelectTab(kTabbedPaneId, 1U),
NameViewRelative(kTabbedPaneId, kViewName, get_second_tab),
WithView(kViewName, [](TabbedPaneTab* tab) { EXPECT_NE(nullptr, tab); }),
IfView(
kViewName, [](const TabbedPaneTab* tab) { return tab != nullptr; },
Do(correct.Get()), Do(incorrect.Get())),
IfViewMatches(
kViewName,
[this](const TabbedPaneTab* tab) { return tabs_->GetIndexOf(tab); },
0U, Do(incorrect.Get()), Do(correct.Get())));
}
TEST_F(InteractiveViewsTestTest, ScrollIntoView) {
const auto visible = [this](View* view) {
const gfx::Rect bounds = view->GetBoundsInScreen();
const gfx::Rect scroll_bounds = scroll_->GetBoundsInScreen();
return bounds.Intersects(scroll_bounds);
};
RunTestSequence(CheckView(kScrollChild1Id, visible, true),
CheckView(kScrollChild2Id, visible, false),
ScrollIntoView(kScrollChild2Id),
CheckView(kScrollChild2Id, visible, true),
ScrollIntoView(kScrollChild1Id),
CheckView(kScrollChild1Id, visible, true));
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/interaction/interactive_views_test_unittest.cc | C++ | unknown | 17,560 |
// 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/masked_targeter_delegate.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/views/view.h"
namespace views {
bool MaskedTargeterDelegate::DoesIntersectRect(const View* target,
const gfx::Rect& rect) const {
// Early return if |rect| does not even intersect the rectangular bounds
// of |target|.
if (!ViewTargeterDelegate::DoesIntersectRect(target, rect))
return false;
// Early return if |mask| is not a valid hit test mask.
SkPath mask;
if (!GetHitTestMask(&mask))
return false;
// Return whether or not |rect| intersects the custom hit test mask
// of |target|.
SkRegion clip_region;
clip_region.setRect({0, 0, target->width(), target->height()});
SkRegion mask_region;
return mask_region.setPath(mask, clip_region) &&
mask_region.intersects(RectToSkIRect(rect));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/masked_targeter_delegate.cc | C++ | unknown | 1,160 |
// 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_MASKED_TARGETER_DELEGATE_H_
#define UI_VIEWS_MASKED_TARGETER_DELEGATE_H_
#include "ui/base/ui_base_types.h"
#include "ui/views/view_targeter_delegate.h"
#include "ui/views/views_export.h"
class SkPath;
namespace gfx {
class Rect;
}
namespace views {
class View;
// Defines the default behaviour for hit-testing a rectangular region against
// the bounds of a View having a custom-shaped hit test mask. Views define
// such a mask by extending this class.
class VIEWS_EXPORT MaskedTargeterDelegate : public ViewTargeterDelegate {
public:
MaskedTargeterDelegate() = default;
MaskedTargeterDelegate(const MaskedTargeterDelegate&) = delete;
MaskedTargeterDelegate& operator=(const MaskedTargeterDelegate&) = delete;
~MaskedTargeterDelegate() override = default;
// Sets the hit-test mask for the view which implements this interface,
// in that view's local coordinate space. Returns whether a valid mask
// has been set in |mask|.
virtual bool GetHitTestMask(SkPath* mask) const = 0;
// ViewTargeterDelegate:
bool DoesIntersectRect(const View* target,
const gfx::Rect& rect) const override;
};
} // namespace views
#endif // UI_VIEWS_MASKED_TARGETER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/masked_targeter_delegate.h | C++ | unknown | 1,379 |
// 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/metadata/type_conversion.h"
#include <string>
#include "components/url_formatter/url_fixer.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/separator.h"
std::u16string ui::metadata::TypeConverter<GURL>::ToString(
const GURL& source_value) {
return base::ASCIIToUTF16(source_value.possibly_invalid_spec());
}
absl::optional<GURL> ui::metadata::TypeConverter<GURL>::FromString(
const std::u16string& source_value) {
const GURL url =
url_formatter::FixupURL(base::UTF16ToUTF8(source_value), std::string());
return url.is_valid() ? absl::make_optional(url) : absl::nullopt;
}
ui::metadata::ValidStrings
ui::metadata::TypeConverter<GURL>::GetValidStrings() {
return {};
}
DEFINE_ENUM_CONVERTERS(
views::ScrollView::ScrollBarMode,
{views::ScrollView::ScrollBarMode::kDisabled, u"kDisabled"},
{views::ScrollView::ScrollBarMode::kHiddenButEnabled, u"kHiddenButEnabled"},
{views::ScrollView::ScrollBarMode::kEnabled, u"kEnabled"})
DEFINE_ENUM_CONVERTERS(
views::BubbleFrameView::PreferredArrowAdjustment,
{views::BubbleFrameView::PreferredArrowAdjustment::kMirror, u"kMirror"},
{views::BubbleFrameView::PreferredArrowAdjustment::kOffset, u"kOffset"})
DEFINE_ENUM_CONVERTERS(
views::BubbleBorder::Arrow,
{views::BubbleBorder::Arrow::TOP_LEFT, u"TOP_LEFT"},
{views::BubbleBorder::Arrow::TOP_RIGHT, u"TOP_RIGHT"},
{views::BubbleBorder::Arrow::BOTTOM_LEFT, u"BOTTOM_LEFT"},
{views::BubbleBorder::Arrow::BOTTOM_RIGHT, u"BOTTOM_RIGHT"},
{views::BubbleBorder::Arrow::LEFT_TOP, u"LEFT_TOP"},
{views::BubbleBorder::Arrow::RIGHT_TOP, u"RIGHT_TOP"},
{views::BubbleBorder::Arrow::LEFT_BOTTOM, u"LEFT_BOTTOM"},
{views::BubbleBorder::Arrow::RIGHT_BOTTOM, u"RIGHT_BOTTOM"},
{views::BubbleBorder::Arrow::TOP_CENTER, u"TOP_CENTER"},
{views::BubbleBorder::Arrow::BOTTOM_CENTER, u"BOTTOM_CENTER"},
{views::BubbleBorder::Arrow::LEFT_CENTER, u"LEFT_CENTER"},
{views::BubbleBorder::Arrow::RIGHT_CENTER, u"RIGHT_CENTER"},
{views::BubbleBorder::Arrow::NONE, u"NONE"},
{views::BubbleBorder::Arrow::FLOAT, u"FLOAT"})
DEFINE_ENUM_CONVERTERS(
ui::TextInputType,
{ui::TextInputType::TEXT_INPUT_TYPE_NONE, u"TEXT_INPUT_TYPE_NONE"},
{ui::TextInputType::TEXT_INPUT_TYPE_TEXT, u"TEXT_INPUT_TYPE_TEXT"},
{ui::TextInputType::TEXT_INPUT_TYPE_PASSWORD, u"TEXT_INPUT_TYPE_PASSWORD"},
{ui::TextInputType::TEXT_INPUT_TYPE_SEARCH, u"TEXT_INPUT_TYPE_SEARCH"},
{ui::TextInputType::TEXT_INPUT_TYPE_EMAIL, u"EXT_INPUT_TYPE_EMAIL"},
{ui::TextInputType::TEXT_INPUT_TYPE_NUMBER, u"TEXT_INPUT_TYPE_NUMBER"},
{ui::TextInputType::TEXT_INPUT_TYPE_TELEPHONE,
u"TEXT_INPUT_TYPE_TELEPHONE"},
{ui::TextInputType::TEXT_INPUT_TYPE_URL, u"TEXT_INPUT_TYPE_URL"},
{ui::TextInputType::TEXT_INPUT_TYPE_DATE, u"TEXT_INPUT_TYPE_DATE"},
{ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME,
u"TEXT_INPUT_TYPE_DATE_TIME"},
{ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME_LOCAL,
u"TEXT_INPUT_TYPE_DATE_TIME_LOCAL"},
{ui::TextInputType::TEXT_INPUT_TYPE_MONTH, u"TEXT_INPUT_TYPE_MONTH"},
{ui::TextInputType::TEXT_INPUT_TYPE_TIME, u"TEXT_INPUT_TYPE_TIME"},
{ui::TextInputType::TEXT_INPUT_TYPE_WEEK, u"TEXT_INPUT_TYPE_WEEK"},
{ui::TextInputType::TEXT_INPUT_TYPE_TEXT_AREA,
u"TEXT_INPUT_TYPE_TEXT_AREA"},
{ui::TextInputType::TEXT_INPUT_TYPE_CONTENT_EDITABLE,
u"TEXT_INPUT_TYPE_CONTENT_EDITABLE"},
{ui::TextInputType::TEXT_INPUT_TYPE_DATE_TIME_FIELD,
u"TEXT_INPUT_TYPE_DATE_TIME_FIELD"},
{ui::TextInputType::TEXT_INPUT_TYPE_NULL, u"TEXT_INPUT_TYPE_NULL"})
DEFINE_ENUM_CONVERTERS(views::Separator::Orientation,
{views::Separator::Orientation::kHorizontal,
u"kHorizontal"},
{views::Separator::Orientation::kVertical, u"kVertical"})
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/type_conversion.cc | C++ | unknown | 4,195 |
// 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_METADATA_TYPE_CONVERSION_H_
#define UI_VIEWS_METADATA_TYPE_CONVERSION_H_
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/metadata/base_type_conversion.h"
#include "ui/views/views_export.h"
#include "url/gurl.h"
template <>
struct VIEWS_EXPORT ui::metadata::TypeConverter<GURL>
: BaseTypeConverter<true> {
static std::u16string ToString(const GURL& source_value);
static absl::optional<GURL> FromString(const std::u16string& source_value);
static ui::metadata::ValidStrings GetValidStrings();
};
#endif // UI_VIEWS_METADATA_TYPE_CONVERSION_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/type_conversion.h | C++ | unknown | 743 |
// 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/metadata/type_conversion.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/focus_ring.h"
using ViewsTypeConversionTest = PlatformTest;
TEST_F(ViewsTypeConversionTest, CheckIsSerializable) {
// Test types with no explicit or aliased converters.
EXPECT_FALSE(ui::metadata::TypeConverter<
views::Button::PressedCallback>::IsSerializable());
EXPECT_FALSE(
ui::metadata::TypeConverter<views::FocusRing*>::IsSerializable());
// Test absl::optional type.
EXPECT_FALSE(ui::metadata::TypeConverter<
absl::optional<views::FocusRing*>>::IsSerializable());
}
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/type_conversion_unittest.cc | C++ | unknown | 868 |
// 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_METADATA_VIEW_FACTORY_H_
#define UI_VIEWS_METADATA_VIEW_FACTORY_H_
#include <functional>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/class_property.h"
#include "ui/base/metadata/base_type_conversion.h"
#include "ui/views/metadata/view_factory_internal.h"
#include "ui/views/views_export.h"
namespace views {
template <typename Builder>
class BaseViewBuilderT : public internal::ViewBuilderCore {
public:
using ViewClass_ = typename internal::ViewClassTrait<Builder>::ViewClass_;
using AfterBuildCallback = base::OnceCallback<void(ViewClass_*)>;
using ConfigureCallback = base::OnceCallback<void(ViewClass_*)>;
BaseViewBuilderT() { view_ = std::make_unique<ViewClass_>(); }
explicit BaseViewBuilderT(std::unique_ptr<ViewClass_> view) {
view_ = std::move(view);
}
explicit BaseViewBuilderT(ViewClass_* root_view) : root_view_(root_view) {}
BaseViewBuilderT(BaseViewBuilderT&&) = default;
BaseViewBuilderT& operator=(BaseViewBuilderT&&) = default;
~BaseViewBuilderT() override = default;
Builder& AfterBuild(AfterBuildCallback after_build_callback) & {
// Allow multiple after build callbacks by chaining them.
if (after_build_callback_) {
after_build_callback_ = base::BindOnce(
[](AfterBuildCallback previous_callback,
AfterBuildCallback current_callback, ViewClass_* root_view) {
std::move(previous_callback).Run(root_view);
std::move(current_callback).Run(root_view);
},
std::move(after_build_callback_), std::move(after_build_callback));
} else {
after_build_callback_ = std::move(after_build_callback);
}
return *static_cast<Builder*>(this);
}
Builder&& AfterBuild(AfterBuildCallback after_build_callback) && {
return std::move(this->AfterBuild(std::move(after_build_callback)));
}
template <typename ViewPtr>
Builder& CopyAddressTo(ViewPtr* view_address) & {
*view_address = view_ ? view_.get() : root_view_.get();
return *static_cast<Builder*>(this);
}
template <typename ViewPtr>
Builder&& CopyAddressTo(ViewPtr* view_address) && {
return std::move(this->CopyAddressTo(view_address));
}
Builder& CustomConfigure(ConfigureCallback configure_callback) & {
// Allow multiple configure callbacks by chaining them.
if (configure_callback_) {
configure_callback_ = base::BindOnce(
[](ConfigureCallback current_callback,
ConfigureCallback previous_callback, ViewClass_* root_view) {
std::move(current_callback).Run(root_view);
std::move(previous_callback).Run(root_view);
},
std::move(configure_callback), std::move(configure_callback_));
} else {
configure_callback_ = std::move(configure_callback);
}
return *static_cast<Builder*>(this);
}
Builder&& CustomConfigure(ConfigureCallback configure_callback) && {
return std::move(this->CustomConfigure(std::move(configure_callback)));
}
template <typename Child>
Builder& AddChild(Child&& child) & {
children_.emplace_back(std::make_pair(child.Release(), absl::nullopt));
return *static_cast<Builder*>(this);
}
template <typename Child>
Builder&& AddChild(Child&& child) && {
return std::move(this->AddChild(std::move(child)));
}
template <typename Child>
Builder& AddChildAt(Child&& child, size_t index) & {
children_.emplace_back(std::make_pair(child.Release(), index));
return *static_cast<Builder*>(this);
}
template <typename Child>
Builder&& AddChildAt(Child&& child, size_t index) && {
return std::move(this->AddChildAt(std::move(child), index));
}
template <typename Child, typename... Types>
Builder& AddChildren(Child&& child, Types&&... args) & {
return AddChildrenImpl(&child, &args...);
}
template <typename Child, typename... Types>
Builder&& AddChildren(Child&& child, Types&&... args) && {
return std::move(this->AddChildrenImpl(&child, &args...));
}
[[nodiscard]] std::unique_ptr<ViewClass_> Build() && {
DCHECK(!root_view_) << "Root view specified. Use BuildChildren() instead.";
DCHECK(view_);
SetProperties(view_.get());
DoCustomConfigure(view_.get());
CreateChildren(view_.get());
DoAfterBuild(view_.get());
return std::move(view_);
}
void BuildChildren() && {
DCHECK(!view_) << "Default constructor called. Use Build() instead.";
DCHECK(root_view_);
SetProperties(root_view_);
DoCustomConfigure(root_view_);
CreateChildren(root_view_);
DoAfterBuild(root_view_);
}
template <typename T>
Builder& SetProperty(const ui::ClassProperty<T>* property,
ui::metadata::ArgType<T> value) & {
auto setter =
std::make_unique<internal::ClassPropertyValueSetter<ViewClass_, T>>(
property, value);
internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
return *static_cast<Builder*>(this);
}
template <typename T>
Builder&& SetProperty(const ui::ClassProperty<T>* property,
ui::metadata::ArgType<T> value) && {
return std::move(this->SetProperty(property, value));
}
template <typename T>
Builder& SetProperty(const ui::ClassProperty<T*>* property,
ui::metadata::ArgType<T> value) & {
auto setter =
std::make_unique<internal::ClassPropertyMoveSetter<ViewClass_, T>>(
property, value);
internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
return *static_cast<Builder*>(this);
}
template <typename T>
Builder&& SetProperty(const ui::ClassProperty<T*>* property,
ui::metadata::ArgType<T> value) && {
return std::move(this->SetProperty(property, value));
}
template <typename T>
Builder& SetProperty(const ui::ClassProperty<T*>* property, T&& value) & {
auto setter =
std::make_unique<internal::ClassPropertyMoveSetter<ViewClass_, T>>(
property, std::move(value));
internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
return *static_cast<Builder*>(this);
}
template <typename T>
Builder&& SetProperty(const ui::ClassProperty<T*>* property, T&& value) && {
return std::move(this->SetProperty(property, value));
}
template <typename T>
Builder& SetProperty(const ui::ClassProperty<T*>* property,
std::unique_ptr<T> value) & {
auto setter =
std::make_unique<internal::ClassPropertyUniquePtrSetter<ViewClass_, T>>(
property, std::move(value));
internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
return *static_cast<Builder*>(this);
}
template <typename T>
Builder&& SetProperty(const ui::ClassProperty<T*>* property,
std::unique_ptr<T> value) && {
return std::move(this->SetProperty(property, std::move(value)));
}
protected:
// Internal implementation which iterates over all the parameters without
// resorting to recursion which can lead to more code generation.
template <typename... Args>
Builder& AddChildrenImpl(Args*... args) & {
std::vector<internal::ViewBuilderCore*> children = {args...};
for (auto* child : children)
children_.emplace_back(std::make_pair(child->Release(), absl::nullopt));
return *static_cast<Builder*>(this);
}
void DoAfterBuild(ViewClass_* view) {
if (after_build_callback_) {
std::move(after_build_callback_).Run(view);
}
}
void DoCustomConfigure(ViewClass_* view) {
if (configure_callback_)
std::move(configure_callback_).Run(view);
}
std::unique_ptr<View> DoBuild() override { return std::move(*this).Build(); }
// Optional callback invoked right after calling `CreateChildren()`. This
// allows additional configuration of the view not easily covered by the
// builder after all addresses have been copied, properties have been set,
// and children have themselves been built and added.
AfterBuildCallback after_build_callback_;
// Optional callback invoked right before calling CreateChildren. This allows
// any additional configuration of the view not easily covered by the builder.
ConfigureCallback configure_callback_;
// Owned and meaningful during the Builder building process. Its
// ownership will be transferred out upon Build() call.
std::unique_ptr<ViewClass_> view_;
// Unowned root view. Used for creating a builder with an existing root
// instance.
raw_ptr<ViewClass_> root_view_ = nullptr;
};
} // namespace views
// Example of builder class generated by the following macros.
//
// template <typename Builder, typename ViewClass>
// class ViewBuilderT : public BaseViewBuilderT<Builder, ViewClass> {
// public:
// ViewBuilderT() = default;
// ViewBuilderT(const ViewBuilderT&&) = default;
// ViewBuilderT& operator=(const ViewBuilderT&&) = default;
// ~ViewBuilderT() override = default;
//
// Builder& SetEnabled(bool value) {
// auto setter = std::make_unique<
// PropertySetter<ViewClass, bool, decltype(&ViewClass::SetEnabled),
// &ViewClass::SetEnabled>>(value);
// ViewBuilderCore::AddPropertySetter(std::move(setter));
// return *static_cast<Builder*>(this);
// }
//
// Builder& SetVisible(bool value) {
// auto setter = std::make_unique<
// PropertySetter<ViewClass, bool, &ViewClass::SetVisible>>(value);
// ViewBuilderCore::AddPropertySetter(std::move(setter));
// return *static_cast<Builder*>(this);
// }
// };
//
// class VIEWS_EXPORT ViewBuilderTest
// : public ViewBuilderT<ViewBuilderTest, View> {};
//
// template <typename Builder, typename ViewClass>
// class LabelButtonBuilderT : public ViewBuilderT<Builder, ViewClass> {
// public:
// LabelButtonBuilderT() = default;
// LabelButtonBuilderT(LabelButtonBuilderT&&) = default;
// LabelButtonBuilderT& operator=(LabelButtonBuilderT&&) = default;
// ~LabelButtonBuilderT() override = default;
//
// Builder& SetIsDefault(bool value) {
// auto setter = std::make_unique<
// PropertySetter<ViewClass, bool, decltype(&ViewClass::SetIsDefault),
// &ViewClass::SetIsDefault>>(value);
// ViewBuilderCore::AddPropertySetter(std::move(setter));
// return *static_cast<Builder*>(this);
// }
// };
//
// class VIEWS_EXPORT LabelButtonBuilder
// : public LabelButtonBuilderT<LabelButtonBuilder, LabelButton> {};
// The maximum number of overloaded params is 10. This should be overkill since
// a function with 10 params is well into the "suspect" territory anyway.
// TODO(kylixrd@): Evaluate whether a max of 5 may be more reasonable.
#define NUM_ARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NUM_ARGS(...) NUM_ARGS_IMPL(__VA_ARGS__, _10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define BUILD_MACRO_NAME_IMPL(a, b) a##b
#define BUILD_MACRO_NAME(a, b) BUILD_MACRO_NAME_IMPL(a, b)
// This will expand the list of types into a parameter declaration list.
// eg: DECL_PARAMS(int, char, float, double) will expand to:
// int param4, char param3, float param2, double param1
#define DECL_PARAM1(type) type param1
#define DECL_PARAM2(type, ...) type param2, DECL_PARAM1(__VA_ARGS__)
#define DECL_PARAM3(type, ...) type param3, DECL_PARAM2(__VA_ARGS__)
#define DECL_PARAM4(type, ...) type param4, DECL_PARAM3(__VA_ARGS__)
#define DECL_PARAM5(type, ...) type param5, DECL_PARAM4(__VA_ARGS__)
#define DECL_PARAM6(type, ...) type param6, DECL_PARAM5(__VA_ARGS__)
#define DECL_PARAM7(type, ...) type param7, DECL_PARAM6(__VA_ARGS__)
#define DECL_PARAM8(type, ...) type param8, DECL_PARAM7(__VA_ARGS__)
#define DECL_PARAM9(type, ...) type param9, DECL_PARAM8(__VA_ARGS__)
#define DECL_PARAM10(type, ...) type param10, DECL_PARAM9(__VA_ARGS__)
#define DECL_PARAMS(...) \
BUILD_MACRO_NAME(DECL_PARAM, NUM_ARGS(__VA_ARGS__))(__VA_ARGS__)
// This will expand into list of parameters suitable for calling a function
// using the same param names from the above expansion.
// eg: PASS_PARAMS(int, char, float, double)
// param4, param3, param2, param1
#define PASS_PARAM1(type) param1
#define PASS_PARAM2(type, ...) param2, PASS_PARAM1(__VA_ARGS__)
#define PASS_PARAM3(type, ...) param3, PASS_PARAM2(__VA_ARGS__)
#define PASS_PARAM4(type, ...) param4, PASS_PARAM3(__VA_ARGS__)
#define PASS_PARAM5(type, ...) param5, PASS_PARAM4(__VA_ARGS__)
#define PASS_PARAM6(type, ...) param6, PASS_PARAM5(__VA_ARGS__)
#define PASS_PARAM7(type, ...) param7, PASS_PARAM6(__VA_ARGS__)
#define PASS_PARAM8(type, ...) param8, PASS_PARAM7(__VA_ARGS__)
#define PASS_PARAM9(type, ...) param9, PASS_PARAM8(__VA_ARGS__)
#define PASS_PARAM10(type, ...) param10, PASS_PARAM9(__VA_ARGS__)
#define PASS_PARAMS(...) \
BUILD_MACRO_NAME(PASS_PARAM, NUM_ARGS(__VA_ARGS__))(__VA_ARGS__)
// BEGIN_VIEW_BUILDER, END_VIEW_BUILDER and VIEW_BUILDER_XXXX macros should
// be placed into the same namespace as the 'view_class' parameter.
#define BEGIN_VIEW_BUILDER(export, view_class, ancestor) \
template <typename BuilderT> \
class export view_class##BuilderT : public ancestor##BuilderT<BuilderT> { \
private: \
using ViewClass_ = view_class; \
\
public: \
view_class##BuilderT() = default; \
explicit view_class##BuilderT( \
typename ::views::internal::ViewClassTrait<BuilderT>::ViewClass_* \
root_view) \
: ancestor##BuilderT<BuilderT>(root_view) {} \
explicit view_class##BuilderT( \
std::unique_ptr< \
typename ::views::internal::ViewClassTrait<BuilderT>::ViewClass_> \
view) \
: ancestor##BuilderT<BuilderT>(std::move(view)) {} \
view_class##BuilderT(view_class##BuilderT&&) = default; \
view_class##BuilderT& operator=(view_class##BuilderT&&) = default; \
~view_class##BuilderT() override = default;
#define VIEW_BUILDER_PROPERTY2(property_type, property_name) \
BuilderT& Set##property_name( \
::ui::metadata::ArgType<property_type> value)& { \
auto setter = std::make_unique<::views::internal::PropertySetter< \
ViewClass_, property_type, decltype(&ViewClass_::Set##property_name), \
&ViewClass_::Set##property_name>>(std::move(value)); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter)); \
return *static_cast<BuilderT*>(this); \
} \
BuilderT&& Set##property_name( \
::ui::metadata::ArgType<property_type> value)&& { \
return std::move(this->Set##property_name(std::move(value))); \
}
#define VIEW_BUILDER_PROPERTY3(property_type, property_name, field_type) \
BuilderT& Set##property_name( \
::ui::metadata::ArgType<property_type> value)& { \
auto setter = std::make_unique<::views::internal::PropertySetter< \
ViewClass_, property_type, decltype(&ViewClass_::Set##property_name), \
&ViewClass_::Set##property_name, field_type>>(std::move(value)); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter)); \
return *static_cast<BuilderT*>(this); \
} \
BuilderT&& Set##property_name( \
::ui::metadata::ArgType<property_type> value)&& { \
return std::move(this->Set##property_name(std::move(value))); \
}
#define GET_VB_MACRO(_1, _2, _3, macro_name, ...) macro_name
#define VIEW_BUILDER_PROPERTY(...) \
GET_VB_MACRO(__VA_ARGS__, VIEW_BUILDER_PROPERTY3, VIEW_BUILDER_PROPERTY2) \
(__VA_ARGS__)
// Sometimes the method being called is on the ancestor to ViewClass_. This
// macro will ensure the overload casts function correctly by specifying the
// ancestor class on which the method is declared. In most cases the following
// macro will be used.
// NOTE: See the Builder declaration for DialogDelegateView in dialog_delegate.h
// for an example.
#define VIEW_BUILDER_OVERLOAD_METHOD_CLASS(class_name, method_name, ...) \
BuilderT& method_name(DECL_PARAMS(__VA_ARGS__))& { \
auto caller = std::make_unique<::views::internal::ClassMethodCaller< \
ViewClass_, \
decltype((static_cast<void (class_name::*)(__VA_ARGS__)>( \
&ViewClass_::method_name))), \
&class_name::method_name, __VA_ARGS__>>(PASS_PARAMS(__VA_ARGS__)); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(caller)); \
return *static_cast<BuilderT*>(this); \
} \
BuilderT&& method_name(DECL_PARAMS(__VA_ARGS__))&& { \
return std::move(this->method_name(PASS_PARAMS(__VA_ARGS__))); \
}
// Unless the above scenario is in play, please favor the use of this macro for
// declaring overloaded builder methods.
#define VIEW_BUILDER_OVERLOAD_METHOD(method_name, ...) \
VIEW_BUILDER_OVERLOAD_METHOD_CLASS(ViewClass_, method_name, __VA_ARGS__)
#define VIEW_BUILDER_METHOD(method_name, ...) \
template <typename... Args> \
BuilderT& method_name(Args&&... args)& { \
auto caller = std::make_unique<::views::internal::ClassMethodCaller< \
ViewClass_, decltype(&ViewClass_::method_name), \
&ViewClass_::method_name, __VA_ARGS__>>(std::forward<Args>(args)...); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(caller)); \
return *static_cast<BuilderT*>(this); \
} \
template <typename... Args> \
BuilderT&& method_name(Args&&... args)&& { \
return std::move(this->method_name(std::forward<Args>(args)...)); \
}
// Enables exposing a template or ambiguously-named method by providing an alias
// that will be used on the Builder.
//
// Examples:
//
// VIEW_BUILDER_METHOD_ALIAS(
// AddTab, AddTab<View>, StringPiece, unique_ptr<View>)
//
// VIEW_BUILDER_METHOD_ALIAS(UnambiguousName, AmbiguousName, int)
//
#define VIEW_BUILDER_METHOD_ALIAS(builder_method, view_method, ...) \
template <typename... Args> \
BuilderT& builder_method(Args&&... args)& { \
auto caller = std::make_unique<::views::internal::ClassMethodCaller< \
ViewClass_, decltype(&ViewClass_::view_method), \
&ViewClass_::view_method, __VA_ARGS__>>(std::forward<Args>(args)...); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(caller)); \
return *static_cast<BuilderT*>(this); \
} \
template <typename... Args> \
BuilderT&& builder_method(Args&&... args)&& { \
return std::move(this->builder_method(std::forward<Args>(args)...)); \
}
#define VIEW_BUILDER_VIEW_TYPE_PROPERTY(property_type, property_name) \
template <typename _View> \
BuilderT& Set##property_name(_View&& view)& { \
auto setter = std::make_unique<::views::internal::ViewBuilderSetter< \
ViewClass_, property_type, \
decltype(&ViewClass_::Set##property_name<property_type>), \
&ViewClass_::Set##property_name<property_type>>>(view.Release()); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter)); \
return *static_cast<BuilderT*>(this); \
} \
template <typename _View> \
BuilderT&& Set##property_name(_View&& view)&& { \
return std::move(this->Set##property_name(std::move(view))); \
}
#define VIEW_BUILDER_VIEW_PROPERTY(property_type, property_name) \
template <typename _View> \
BuilderT& Set##property_name(_View&& view)& { \
auto setter = std::make_unique<::views::internal::ViewBuilderSetter< \
ViewClass_, property_type, decltype(&ViewClass_::Set##property_name), \
&ViewClass_::Set##property_name>>(view.Release()); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter)); \
return *static_cast<BuilderT*>(this); \
} \
template <typename _View> \
BuilderT&& Set##property_name(_View&& view)&& { \
return std::move(this->Set##property_name(std::move(view))); \
}
#define VIEW_BUILDER_PROPERTY_DEFAULT(property_type, property_name, default) \
BuilderT& Set##property_name(::ui::metadata::ArgType<property_type> value = \
default)& { \
auto setter = std::make_unique<::views::internal::PropertySetter< \
ViewClass_, property_type, decltype(&ViewClass_::Set##property_name), \
&ViewClass_::Set##property_name>>(std::move(value)); \
::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter)); \
return *static_cast<BuilderT*>(this); \
} \
BuilderT&& Set##property_name(::ui::metadata::ArgType<property_type> value = \
default)&& { \
return std::move(this->Set##property_name(value)); \
}
// Turn off clang-format due to it messing up the following macro. Places the
// semi-colon on a separate line.
// clang-format off
#define END_VIEW_BUILDER };
// Unlike the above macros, DEFINE_VIEW_BUILDER must be placed in the global
// namespace. Unless 'view_class' is already in the 'views' namespace, it should
// be fully qualified with the namespace in which it lives.
#define DEFINE_VIEW_BUILDER(export, view_class) \
namespace views { \
template <> \
class export Builder<view_class> \
: public view_class##BuilderT<Builder<view_class>> { \
private: \
using ViewClass_ = view_class; \
public: \
Builder() = default; \
explicit Builder(ViewClass_* root_view) \
: view_class##BuilderT<Builder<ViewClass_>>(root_view) {} \
explicit Builder(std::unique_ptr<ViewClass_> view) \
: view_class##BuilderT<Builder<ViewClass_>>(std::move(view)) {} \
Builder(Builder&&) = default; \
Builder<ViewClass_>& operator=(Builder<ViewClass_>&&) = default; \
~Builder() = default; \
[[nodiscard]] std::unique_ptr<internal::ViewBuilderCore> Release() \
override { \
return std::make_unique<Builder<view_class>>(std::move(*this)); \
} \
}; \
} // namespace views
// clang-format on
#endif // UI_VIEWS_METADATA_VIEW_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/view_factory.h | C++ | unknown | 25,766 |
// 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/metadata/view_factory_internal.h"
#include "ui/views/view.h"
namespace views::internal {
ViewBuilderCore::ViewBuilderCore() = default;
ViewBuilderCore::ViewBuilderCore(ViewBuilderCore&&) = default;
ViewBuilderCore::~ViewBuilderCore() = default;
ViewBuilderCore& ViewBuilderCore::operator=(ViewBuilderCore&&) = default;
std::unique_ptr<View> ViewBuilderCore::Build() && {
return DoBuild();
}
void ViewBuilderCore::AddPropertySetter(
std::unique_ptr<PropertySetterBase> setter) {
property_list_.push_back(std::move(setter));
}
void ViewBuilderCore::CreateChildren(View* parent) {
for (auto& builder : children_) {
if (builder.second)
parent->AddChildViewAt(builder.first->DoBuild(), builder.second.value());
else
parent->AddChildView(builder.first->DoBuild());
}
}
void ViewBuilderCore::SetProperties(View* view) {
for (auto& property : property_list_)
property->SetProperty(view);
}
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/view_factory_internal.cc | C++ | unknown | 1,126 |
// 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_METADATA_VIEW_FACTORY_INTERNAL_H_
#define UI_VIEWS_METADATA_VIEW_FACTORY_INTERNAL_H_
#include <functional>
#include <map>
#include <memory>
#include <tuple>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/class_property.h"
#include "ui/base/metadata/base_type_conversion.h"
#include "ui/views/views_export.h"
namespace views {
class View;
template <typename T>
class Builder {};
namespace internal {
template <typename T>
class ViewClassTrait {};
template <typename T>
class ViewClassTrait<Builder<T>> {
public:
using ViewClass_ = T;
};
class PropertySetterBase {
public:
PropertySetterBase() = default;
PropertySetterBase(const PropertySetterBase&) = delete;
PropertySetterBase& operator=(const PropertySetterBase&) = delete;
virtual ~PropertySetterBase() = default;
virtual void SetProperty(View* obj) = 0;
};
template <typename TClass,
typename TValue,
typename TSig,
TSig Set,
typename FType = typename std::remove_reference<TValue>::type>
class PropertySetter : public PropertySetterBase {
public:
explicit PropertySetter(ui::metadata::ArgType<TValue> value)
: value_(std::move(value)) {}
PropertySetter(const PropertySetter&) = delete;
PropertySetter& operator=(const PropertySetter&) = delete;
~PropertySetter() override = default;
void SetProperty(View* obj) override {
(static_cast<TClass*>(obj)->*Set)(std::move(value_));
}
private:
FType value_;
};
template <typename TClass, typename TValue>
class ClassPropertyValueSetter : public PropertySetterBase {
public:
ClassPropertyValueSetter(const ui::ClassProperty<TValue>* property,
TValue value)
: property_(property), value_(value) {}
ClassPropertyValueSetter(const ClassPropertyValueSetter&) = delete;
ClassPropertyValueSetter& operator=(const ClassPropertyValueSetter&) = delete;
~ClassPropertyValueSetter() override = default;
void SetProperty(View* obj) override {
static_cast<TClass*>(obj)->SetProperty(property_, value_);
}
private:
// This field is not a raw_ptr<> because of compiler error when passed to
// templated param T*.
RAW_PTR_EXCLUSION const ui::ClassProperty<TValue>* property_;
TValue value_;
};
template <typename TClass, typename TValue>
class ClassPropertyMoveSetter : public PropertySetterBase {
public:
ClassPropertyMoveSetter(const ui::ClassProperty<TValue*>* property,
const TValue& value)
: property_(property), value_(value) {}
ClassPropertyMoveSetter(const ui::ClassProperty<TValue*>* property,
TValue&& value)
: property_(property), value_(std::move(value)) {}
ClassPropertyMoveSetter(const ClassPropertyMoveSetter&) = delete;
ClassPropertyMoveSetter& operator=(const ClassPropertyMoveSetter&) = delete;
~ClassPropertyMoveSetter() override = default;
void SetProperty(View* obj) override {
static_cast<TClass*>(obj)->SetProperty(property_.get(), std::move(value_));
}
private:
raw_ptr<const ui::ClassProperty<TValue*>> property_;
TValue value_;
};
template <typename TClass, typename TValue>
class ClassPropertyUniquePtrSetter : public PropertySetterBase {
public:
ClassPropertyUniquePtrSetter(const ui::ClassProperty<TValue*>* property,
std::unique_ptr<TValue> value)
: property_(property), value_(std::move(value)) {}
ClassPropertyUniquePtrSetter(const ClassPropertyUniquePtrSetter&) = delete;
ClassPropertyUniquePtrSetter& operator=(const ClassPropertyUniquePtrSetter&) =
delete;
~ClassPropertyUniquePtrSetter() override = default;
void SetProperty(View* obj) override {
static_cast<TClass*>(obj)->SetProperty(property_, std::move(value_));
}
private:
raw_ptr<const ui::ClassProperty<TValue*>> property_;
std::unique_ptr<TValue> value_;
};
template <typename TClass, typename TSig, TSig Set, typename... Args>
class ClassMethodCaller : public PropertySetterBase {
public:
explicit ClassMethodCaller(Args... args)
: args_(std::make_tuple<Args...>(std::move(args)...)) {}
ClassMethodCaller(const ClassMethodCaller&) = delete;
ClassMethodCaller& operator=(const ClassMethodCaller&) = delete;
~ClassMethodCaller() override = default;
void SetProperty(View* obj) override {
std::apply(Set, std::tuple_cat(std::make_tuple(static_cast<TClass*>(obj)),
std::move(args_)));
}
private:
using Parameters = std::tuple<typename std::remove_reference<Args>::type...>;
Parameters args_;
};
class VIEWS_EXPORT ViewBuilderCore {
public:
ViewBuilderCore();
ViewBuilderCore(ViewBuilderCore&&);
ViewBuilderCore& operator=(ViewBuilderCore&&);
virtual ~ViewBuilderCore();
[[nodiscard]] std::unique_ptr<View> Build() &&;
[[nodiscard]] virtual std::unique_ptr<ViewBuilderCore> Release() = 0;
protected:
// Vector of child view builders. If the optional index is included it will be
// passed to View::AddChildViewAt().
using ChildList = std::vector<
std::pair<std::unique_ptr<ViewBuilderCore>, absl::optional<size_t>>>;
using PropertyList = std::vector<std::unique_ptr<PropertySetterBase>>;
void AddPropertySetter(std::unique_ptr<PropertySetterBase> setter);
void CreateChildren(View* parent);
virtual std::unique_ptr<View> DoBuild() = 0;
void SetProperties(View* view);
ChildList children_;
PropertyList property_list_;
};
template <typename TClass, typename TValue, typename TSig, TSig Set>
class ViewBuilderSetter : public PropertySetterBase {
public:
explicit ViewBuilderSetter(std::unique_ptr<ViewBuilderCore> builder)
: builder_(std::move(builder)) {}
ViewBuilderSetter(const ViewBuilderSetter&) = delete;
ViewBuilderSetter& operator=(const ViewBuilderSetter&) = delete;
~ViewBuilderSetter() override = default;
void SetProperty(View* obj) override {
(static_cast<TClass*>(obj)->*Set)(std::move(*builder_).Build());
}
private:
std::unique_ptr<ViewBuilderCore> builder_;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_METADATA_VIEW_FACTORY_INTERNAL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/view_factory_internal.h | C++ | unknown | 6,362 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/metadata/view_factory.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/mock_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
using ViewFactoryTest = views::test::WidgetTest;
namespace internal {
class TestView : public views::View {
public:
METADATA_HEADER(TestView);
TestView() = default;
TestView(const TestView&) = delete;
TestView& operator=(const TestView&) = delete;
~TestView() override = default;
// Define a method with an arbitrary number of parameters (>1).
// Most PODs and enums should work. Stick to parameters passed by-value
// if possible.
// TODO(kylixrd): Figure out support for ref and const-ref parameters
// if ever needed
void ArbitraryMethod(int int_param,
float float_param,
views::PropertyEffects property_effects) {
int_param_ = int_param;
float_param_ = float_param;
property_effects_ = property_effects;
}
int get_int_param() const { return int_param_; }
float get_float_param() const { return float_param_; }
views::PropertyEffects get_property_effects() const {
return property_effects_;
}
private:
int int_param_ = 0;
float float_param_ = 0.0;
views::PropertyEffects property_effects_ = views::kPropertyEffectsNone;
};
BEGIN_VIEW_BUILDER(, TestView, views::View)
VIEW_BUILDER_METHOD(ArbitraryMethod, int, float, views::PropertyEffects)
END_VIEW_BUILDER
BEGIN_METADATA(TestView, views::View)
END_METADATA
} // namespace internal
DEFINE_VIEW_BUILDER(, ::internal::TestView)
TEST_F(ViewFactoryTest, TestViewBuilder) {
views::View* parent = nullptr;
views::LabelButton* button = nullptr;
views::LabelButton* scroll_button = nullptr;
views::ScrollView* scroll_view = nullptr;
views::View* view_with_layout_manager = nullptr;
auto layout_manager = std::make_unique<views::FillLayout>();
auto* layout_manager_ptr = layout_manager.get();
auto view =
views::Builder<views::View>()
.CopyAddressTo(&parent)
.SetEnabled(false)
.SetVisible(true)
.SetBackground(views::CreateSolidBackground(SK_ColorWHITE))
.SetBorder(views::CreateEmptyBorder(0))
.AddChildren(views::Builder<views::View>()
.SetEnabled(false)
.SetVisible(true)
.SetProperty(views::kMarginsKey, gfx::Insets(5)),
views::Builder<views::View>()
.SetGroup(5)
.SetID(1)
.SetFocusBehavior(views::View::FocusBehavior::NEVER),
views::Builder<views::LabelButton>()
.CopyAddressTo(&button)
.SetIsDefault(true)
.SetEnabled(true)
.SetText(u"Test"),
views::Builder<views::ScrollView>()
.CopyAddressTo(&scroll_view)
.SetContents(views::Builder<views::LabelButton>()
.CopyAddressTo(&scroll_button)
.SetText(u"ScrollTest"))
.SetHeader(views::Builder<views::View>().SetID(2)),
views::Builder<views::LabelButton>()
.CopyAddressTo(&view_with_layout_manager)
.SetLayoutManager(std::move(layout_manager)))
.Build();
ASSERT_TRUE(view.get());
EXPECT_NE(parent, nullptr);
EXPECT_NE(button, nullptr);
EXPECT_TRUE(view->GetVisible());
EXPECT_FALSE(view->GetEnabled());
ASSERT_GT(view->children().size(), size_t{2});
EXPECT_EQ(view->children()[1]->GetFocusBehavior(),
views::View::FocusBehavior::NEVER);
EXPECT_EQ(view->children()[2], button);
EXPECT_EQ(button->GetText(), u"Test");
EXPECT_NE(scroll_view, nullptr);
EXPECT_NE(scroll_button, nullptr);
EXPECT_EQ(scroll_button->GetText(), u"ScrollTest");
EXPECT_EQ(scroll_button, scroll_view->contents());
EXPECT_NE(view_with_layout_manager, nullptr);
EXPECT_TRUE(views::IsViewClass<views::LabelButton>(view_with_layout_manager));
EXPECT_EQ(view_with_layout_manager->GetLayoutManager(), layout_manager_ptr);
}
TEST_F(ViewFactoryTest, TestViewBuilderOwnerships) {
views::View* parent = nullptr;
views::LabelButton* button = nullptr;
views::LabelButton* scroll_button = nullptr;
views::ScrollView* scroll_view = nullptr;
auto view_builder = views::Builder<views::View>();
view_builder.CopyAddressTo(&parent)
.SetEnabled(false)
.SetVisible(true)
.SetBackground(views::CreateSolidBackground(SK_ColorWHITE))
.SetBorder(views::CreateEmptyBorder(0));
view_builder.AddChild(views::Builder<views::View>()
.SetEnabled(false)
.SetVisible(true)
.SetProperty(views::kMarginsKey, gfx::Insets(5)));
view_builder.AddChild(
views::Builder<views::View>().SetGroup(5).SetID(1).SetFocusBehavior(
views::View::FocusBehavior::NEVER));
view_builder.AddChild(views::Builder<views::LabelButton>()
.CopyAddressTo(&button)
.SetIsDefault(true)
.SetEnabled(true)
.SetText(u"Test"));
view_builder.AddChild(views::Builder<views::ScrollView>()
.CopyAddressTo(&scroll_view)
.SetContents(views::Builder<views::LabelButton>()
.CopyAddressTo(&scroll_button)
.SetText(u"ScrollTest"))
.SetHeader(views::Builder<views::View>().SetID(2)));
auto view = std::move(view_builder).Build();
ASSERT_TRUE(view.get());
EXPECT_NE(parent, nullptr);
EXPECT_NE(button, nullptr);
EXPECT_TRUE(view->GetVisible());
EXPECT_FALSE(view->GetEnabled());
ASSERT_GT(view->children().size(), size_t{2});
EXPECT_EQ(view->children()[1]->GetFocusBehavior(),
views::View::FocusBehavior::NEVER);
EXPECT_EQ(view->children()[2], button);
EXPECT_EQ(button->GetText(), u"Test");
EXPECT_NE(scroll_view, nullptr);
EXPECT_NE(scroll_button, nullptr);
EXPECT_EQ(scroll_button->GetText(), u"ScrollTest");
EXPECT_EQ(scroll_button, scroll_view->contents());
}
TEST_F(ViewFactoryTest, TestViewBuilderArbitraryMethod) {
auto view = views::Builder<internal::TestView>()
.SetEnabled(false)
.ArbitraryMethod(10, 5.5, views::kPropertyEffectsLayout)
.Build();
EXPECT_FALSE(view->GetEnabled());
EXPECT_EQ(view->get_int_param(), 10);
EXPECT_EQ(view->get_float_param(), 5.5);
EXPECT_EQ(view->get_property_effects(), views::kPropertyEffectsLayout);
}
TEST_F(ViewFactoryTest, TestViewBuilderCustomConfigure) {
views::UniqueWidgetPtr widget =
base::WrapUnique(CreateTopLevelPlatformWidget());
auto* view = widget->GetContentsView()->AddChildView(
views::Builder<internal::TestView>()
.CustomConfigure(base::BindOnce([](internal::TestView* view) {
view->SetEnabled(false);
view->GetViewAccessibility().OverridePosInSet(5, 10);
}))
.Build());
EXPECT_FALSE(view->GetEnabled());
ui::AXNodeData node_data;
view->GetViewAccessibility().GetAccessibleNodeData(&node_data);
EXPECT_EQ(node_data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet), 5);
EXPECT_EQ(node_data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize), 10);
}
TEST_F(ViewFactoryTest, TestViewBuilderAddChildAtIndex) {
views::View* parent = nullptr;
views::LabelButton* ok_button = nullptr;
views::LabelButton* cancel_button = nullptr;
std::unique_ptr<views::View> view =
views::Builder<views::View>()
.CopyAddressTo(&parent)
.AddChild(views::Builder<views::LabelButton>()
.CopyAddressTo(&cancel_button)
.SetIsDefault(false)
.SetEnabled(true)
.SetText(u"Cancel"))
.AddChildAt(views::Builder<views::LabelButton>()
.CopyAddressTo(&ok_button)
.SetIsDefault(false)
.SetEnabled(true)
.SetText(u"OK"),
0)
.Build();
EXPECT_NE(parent, nullptr);
EXPECT_NE(ok_button, nullptr);
EXPECT_NE(cancel_button, nullptr);
EXPECT_EQ(view.get(), parent);
EXPECT_TRUE(view->GetVisible());
// Make sure the OK button is inserted into the child list at index 0.
EXPECT_EQ(ok_button, view->children()[0]);
EXPECT_EQ(cancel_button, view->children()[1]);
}
TEST_F(ViewFactoryTest, TestOrderOfOperations) {
using ViewCallback = base::OnceCallback<void(views::View*)>;
views::View* view = nullptr;
base::MockCallback<ViewCallback> custom_configure_callback;
base::MockCallback<ViewCallback> after_build_callback;
EXPECT_CALL(custom_configure_callback, Run).Times(0);
EXPECT_CALL(after_build_callback, Run).Times(0);
views::Builder<views::View> builder;
builder.CopyAddressTo(&view)
.SetID(1)
.AddChild(views::Builder<views::View>())
.CustomConfigure(custom_configure_callback.Get())
.CustomConfigure(custom_configure_callback.Get())
.AfterBuild(after_build_callback.Get())
.AfterBuild(after_build_callback.Get());
// Addresses should be copied *before* build but properties shouldn't be set,
// children shouldn't be added, and callbacks shouldn't be run until *after*.
ASSERT_NE(view, nullptr);
EXPECT_EQ(view->GetID(), 0);
EXPECT_EQ(view->children().size(), 0u);
testing::Mock::VerifyAndClearExpectations(&custom_configure_callback);
testing::Mock::VerifyAndClearExpectations(&after_build_callback);
{
testing::InSequence sequence;
// Expect that two custom configure callbacks will be run *before* any
// after build callbacks. The order of the custom configure callbacks is
// not guaranteed by the builder.
EXPECT_CALL(custom_configure_callback, Run(testing::Pointer(view)))
.Times(2)
.WillRepeatedly(testing::Invoke([](views::View* view) {
// Properties should be set *before* but children shouldn't be added
// until *after* custom callbacks are run.
EXPECT_EQ(view->GetID(), 1);
EXPECT_EQ(view->children().size(), 0u);
}));
// Expect that two after build callbacks will be run *after* any custom
// configure callbacks. The order of the after build callbacks is not
// guaranteed by the builder.
EXPECT_CALL(after_build_callback, Run(testing::Pointer(view)))
.Times(2)
.WillRepeatedly(testing::Invoke([](views::View* view) {
// Children should be added *before* after build callbacks are run.
EXPECT_EQ(view->children().size(), 1u);
}));
}
// Build the view and verify order of operations.
std::ignore = std::move(builder).Build();
}
| Zhao-PengFei35/chromium_src_4 | ui/views/metadata/view_factory_unittest.cc | C++ | unknown | 12,040 |
// 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/metrics.h"
namespace views {
const int kDefaultMenuShowDelay = 400;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/metrics.cc | C++ | unknown | 256 |
// 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_METRICS_H_
#define UI_VIEWS_METRICS_H_
#include "ui/views/views_export.h"
namespace views {
// NOTE: All times in this file are/should be expressed in milliseconds.
// The default value for how long to wait before showing a menu button on hover.
// This value is used if the OS doesn't supply one.
extern const int kDefaultMenuShowDelay;
// Returns the amount of time between double clicks.
VIEWS_EXPORT int GetDoubleClickInterval();
// Returns the amount of time to wait from hovering over a menu button until
// showing the menu.
VIEWS_EXPORT int GetMenuShowDelay();
} // namespace views
#endif // UI_VIEWS_METRICS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/metrics.h | C++ | unknown | 791 |
// 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 "build/build_config.h"
#include "ui/views/metrics.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif
namespace views {
int GetDoubleClickInterval() {
#if BUILDFLAG(IS_WIN)
return static_cast<int>(::GetDoubleClickTime());
#else
// TODO(jennyz): This value may need to be adjusted on different platforms.
const int kDefaultDoubleClickIntervalMs = 500;
return kDefaultDoubleClickIntervalMs;
#endif
}
int GetMenuShowDelay() {
#if BUILDFLAG(IS_WIN)
static int delay = []() {
DWORD show_delay;
return SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &show_delay, 0)
? static_cast<int>(show_delay)
: kDefaultMenuShowDelay;
}();
return delay;
#else
return 0;
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/metrics_aura.cc | C++ | unknown | 893 |
// 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/metrics.h"
namespace {
// Default double click interval in milliseconds.
// Same as what gtk uses.
const int kDefaultDoubleClickInterval = 500;
} // namespace
namespace views {
int GetDoubleClickInterval() {
return kDefaultDoubleClickInterval;
}
int GetMenuShowDelay() {
return 0;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/metrics_mac.cc | C++ | unknown | 480 |
// 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_MOUSE_CONSTANTS_H_
#define UI_VIEWS_MOUSE_CONSTANTS_H_
#include "base/time/time.h"
namespace views {
// The amount of time, in milliseconds, between clicks until they're
// considered intentionally different.
constexpr auto kMinimumTimeBetweenButtonClicks = base::Milliseconds(100);
} // namespace views
#endif // UI_VIEWS_MOUSE_CONSTANTS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/mouse_constants.h | C++ | unknown | 510 |
// 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/mouse_watcher.h"
#include <utility>
#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/task/single_thread_task_runner.h"
#include "ui/events/event.h"
#include "ui/events/event_observer.h"
#include "ui/events/event_utils.h"
#include "ui/events/platform_event.h"
#include "ui/events/types/event_type.h"
#include "ui/views/event_monitor.h"
namespace views {
// Amount of time between when the mouse moves outside the Host's zone and when
// the listener is notified.
constexpr auto kNotifyListenerTime = base::Milliseconds(300);
class MouseWatcher::Observer : public ui::EventObserver {
public:
Observer(MouseWatcher* mouse_watcher, gfx::NativeWindow window)
: mouse_watcher_(mouse_watcher) {
event_monitor_ = EventMonitor::CreateApplicationMonitor(
this, window,
{ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_MOVED, ui::ET_MOUSE_EXITED,
ui::ET_MOUSE_DRAGGED});
}
Observer(const Observer&) = delete;
Observer& operator=(const Observer&) = delete;
// ui::EventObserver:
void OnEvent(const ui::Event& event) override {
using EventType = MouseWatcherHost::EventType;
switch (event.type()) {
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
HandleMouseEvent(EventType::kMove);
break;
case ui::ET_MOUSE_EXITED:
HandleMouseEvent(EventType::kExit);
break;
case ui::ET_MOUSE_PRESSED:
HandleMouseEvent(EventType::kPress);
break;
default:
NOTREACHED_NORETURN();
}
}
private:
MouseWatcherHost* host() const { return mouse_watcher_->host_.get(); }
// Called when a mouse event we're interested is seen.
void HandleMouseEvent(MouseWatcherHost::EventType event_type) {
using EventType = MouseWatcherHost::EventType;
// It's safe to use GetLastMouseLocation() here as this function is invoked
// during event dispatching.
if (!host()->Contains(event_monitor_->GetLastMouseLocation(), event_type)) {
if (event_type == EventType::kPress) {
NotifyListener();
} else if (!notify_listener_factory_.HasWeakPtrs()) {
// Mouse moved outside the host's zone, start a timer to notify the
// listener.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&Observer::NotifyListener,
notify_listener_factory_.GetWeakPtr()),
event_type == EventType::kMove
? kNotifyListenerTime
: mouse_watcher_->notify_on_exit_time_);
}
} else {
// Mouse moved quickly out of the host and then into it again, so cancel
// the timer.
notify_listener_factory_.InvalidateWeakPtrs();
}
}
void NotifyListener() {
mouse_watcher_->NotifyListener();
// WARNING: we've been deleted.
}
private:
raw_ptr<MouseWatcher> mouse_watcher_;
std::unique_ptr<views::EventMonitor> event_monitor_;
// A factory that is used to construct a delayed callback to the listener.
base::WeakPtrFactory<Observer> notify_listener_factory_{this};
};
MouseWatcherListener::~MouseWatcherListener() = default;
MouseWatcherHost::~MouseWatcherHost() = default;
MouseWatcher::MouseWatcher(std::unique_ptr<MouseWatcherHost> host,
MouseWatcherListener* listener)
: host_(std::move(host)),
listener_(listener),
notify_on_exit_time_(kNotifyListenerTime) {}
MouseWatcher::~MouseWatcher() = default;
void MouseWatcher::Start(gfx::NativeWindow window) {
if (!is_observing())
observer_ = std::make_unique<Observer>(this, window);
}
void MouseWatcher::Stop() {
observer_.reset();
}
void MouseWatcher::NotifyListener() {
observer_.reset();
listener_->MouseMovedOutOfHost();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/mouse_watcher.cc | C++ | unknown | 4,065 |
// 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_MOUSE_WATCHER_H_
#define UI_VIEWS_MOUSE_WATCHER_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
namespace gfx {
class Point;
}
namespace views {
// MouseWatcherListener is notified when the mouse moves outside the host.
class VIEWS_EXPORT MouseWatcherListener {
public:
virtual void MouseMovedOutOfHost() = 0;
protected:
virtual ~MouseWatcherListener();
};
// The MouseWatcherHost determines what region is to be monitored.
class VIEWS_EXPORT MouseWatcherHost {
public:
// The type of mouse event.
enum class EventType { kMove, kExit, kPress };
virtual ~MouseWatcherHost();
// Return false when the mouse has moved outside the monitored region.
virtual bool Contains(const gfx::Point& screen_point, EventType type) = 0;
};
// MouseWatcher is used to watch mouse movement and notify its listener when the
// mouse moves outside the bounds of a MouseWatcherHost.
class VIEWS_EXPORT MouseWatcher {
public:
// Creates a new MouseWatcher. The |listener| will be notified when the |host|
// determines that the mouse has moved outside its monitored region.
// |host| will be owned by the watcher and deleted upon completion, while the
// listener must remain alive for the lifetime of this object.
MouseWatcher(std::unique_ptr<MouseWatcherHost> host,
MouseWatcherListener* listener);
MouseWatcher(const MouseWatcher&) = delete;
MouseWatcher& operator=(const MouseWatcher&) = delete;
~MouseWatcher();
// Sets the amount to delay before notifying the listener when the mouse exits
// the host by way of going to another window.
void set_notify_on_exit_time(base::TimeDelta time) {
notify_on_exit_time_ = time;
}
// Starts watching mouse movements. When the mouse moves outside the bounds of
// the host the listener is notified. |Start| may be invoked any number of
// times. If the mouse moves outside the bounds of the host the listener is
// notified and watcher stops watching events. |window| must be a window in
// the hierarchy related to the host. |window| is used to setup initial state,
// and may be deleted before MouseWatcher.
void Start(gfx::NativeWindow window);
// Stops watching mouse events.
void Stop();
private:
class Observer;
// Are we currently observing events?
bool is_observing() const { return observer_.get() != nullptr; }
// Notifies the listener and stops watching events.
void NotifyListener();
// Host we're listening for events over.
std::unique_ptr<MouseWatcherHost> host_;
// Our listener.
raw_ptr<MouseWatcherListener> listener_;
// Does the actual work of listening for mouse events.
std::unique_ptr<Observer> observer_;
// See description above setter.
base::TimeDelta notify_on_exit_time_;
};
} // namespace views
#endif // UI_VIEWS_MOUSE_WATCHER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/mouse_watcher.h | C++ | unknown | 3,119 |
// 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/mouse_watcher_view_host.h"
#include "ui/display/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
MouseWatcherViewHost::MouseWatcherViewHost(const View* view,
const gfx::Insets& hot_zone_insets)
: view_(view), hot_zone_insets_(hot_zone_insets) {}
MouseWatcherViewHost::~MouseWatcherViewHost() = default;
bool MouseWatcherViewHost::Contains(const gfx::Point& screen_point,
EventType type) {
bool in_view = IsCursorInViewZone(screen_point);
if (!in_view || (type == EventType::kExit && !IsMouseOverWindow()))
return false;
return true;
}
// Returns whether or not the cursor is currently in the view's "zone" which
// is defined as a slightly larger region than the view.
bool MouseWatcherViewHost::IsCursorInViewZone(const gfx::Point& screen_point) {
gfx::Rect bounds = view_->GetLocalBounds();
gfx::Point view_topleft(bounds.origin());
View::ConvertPointToScreen(view_, &view_topleft);
bounds.set_origin(view_topleft);
bounds.SetRect(view_topleft.x() - hot_zone_insets_.left(),
view_topleft.y() - hot_zone_insets_.top(),
bounds.width() + hot_zone_insets_.width(),
bounds.height() + hot_zone_insets_.height());
return bounds.Contains(screen_point.x(), screen_point.y());
}
// Returns true if the mouse is over the view's window.
bool MouseWatcherViewHost::IsMouseOverWindow() {
const Widget* const widget = view_->GetWidget();
if (!widget)
return false;
return display::Screen::GetScreen()->IsWindowUnderCursor(
widget->GetNativeWindow());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/mouse_watcher_view_host.cc | C++ | unknown | 1,849 |
// 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_MOUSE_WATCHER_VIEW_HOST_H_
#define UI_VIEWS_MOUSE_WATCHER_VIEW_HOST_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/mouse_watcher.h"
namespace views {
class View;
class VIEWS_EXPORT MouseWatcherViewHost : public MouseWatcherHost {
public:
// Creates a new MouseWatcherViewHost. `hot_zone_insets` is added to the
// bounds of the view to determine the active zone. For example, if
// `hot_zone_insets.bottom()` is 10, then the listener is not notified if
// the y coordinate is between the origin of the view and height of the view
// plus 10.
MouseWatcherViewHost(const View* view, const gfx::Insets& hot_zone_insets);
MouseWatcherViewHost(const MouseWatcherViewHost&) = delete;
MouseWatcherViewHost& operator=(const MouseWatcherViewHost&) = delete;
~MouseWatcherViewHost() override;
// MouseWatcherHost.
bool Contains(const gfx::Point& screen_point, EventType type) override;
private:
bool IsCursorInViewZone(const gfx::Point& screen_point);
bool IsMouseOverWindow();
// View we're listening for events over.
const raw_ptr<const View> view_;
// Insets added to the bounds of the view.
const gfx::Insets hot_zone_insets_;
};
} // namespace views
#endif // UI_VIEWS_MOUSE_WATCHER_VIEW_HOST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/mouse_watcher_view_host.h | C++ | unknown | 1,409 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_NATIVE_THEME_DELEGATE_H_
#define UI_VIEWS_NATIVE_THEME_DELEGATE_H_
#include "ui/gfx/geometry/rect.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/views_export.h"
namespace views {
// A delagate that supports animating transtions between different native
// theme states. This delegate can be used to control a native theme Border
// or Painter object.
//
// If animation is ongoing, the native theme border or painter will
// composite the foreground state over the backgroud state using an alpha
// between 0 and 255 based on the current value of the animation.
class VIEWS_EXPORT NativeThemeDelegate {
public:
virtual ~NativeThemeDelegate() = default;
// Get the native theme part that should be drawn.
virtual ui::NativeTheme::Part GetThemePart() const = 0;
// Get the rectangle that should be painted.
virtual gfx::Rect GetThemePaintRect() const = 0;
// Get the state of the part, along with any extra data needed for drawing.
virtual ui::NativeTheme::State GetThemeState(
ui::NativeTheme::ExtraParams* params) const = 0;
// If the native theme drawign should be animated, return the Animation object
// that controlls it. If no animation is ongoing, NULL may be returned.
virtual const gfx::Animation* GetThemeAnimation() const = 0;
// If animation is onging, this returns the background native theme state.
virtual ui::NativeTheme::State GetBackgroundThemeState(
ui::NativeTheme::ExtraParams* params) const = 0;
// If animation is onging, this returns the foreground native theme state.
// This state will be composited over the background using an alpha value
// based on the current value of the animation.
virtual ui::NativeTheme::State GetForegroundThemeState(
ui::NativeTheme::ExtraParams* params) const = 0;
};
} // namespace views
#endif // UI_VIEWS_NATIVE_THEME_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/native_theme_delegate.h | C++ | unknown | 2,031 |
// 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_NATIVE_WINDOW_TRACKER_H_
#define UI_VIEWS_NATIVE_WINDOW_TRACKER_H_
#include <memory>
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
namespace views {
// An observer which detects when a gfx::NativeWindow is closed.
class VIEWS_EXPORT NativeWindowTracker {
public:
virtual ~NativeWindowTracker() = default;
static std::unique_ptr<NativeWindowTracker> Create(gfx::NativeWindow window);
// Returns true if the native window passed to Create() has been closed.
virtual bool WasNativeWindowDestroyed() const = 0;
};
} // namespace views
#endif // UI_VIEWS_NATIVE_WINDOW_TRACKER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/native_window_tracker.h | C++ | unknown | 784 |
// 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/native_window_tracker_aura.h"
#include <memory>
#include "ui/aura/window.h"
namespace views {
NativeWindowTrackerAura::NativeWindowTrackerAura(gfx::NativeWindow window)
: window_(window) {
window->AddObserver(this);
}
NativeWindowTrackerAura::~NativeWindowTrackerAura() {
if (window_)
window_->RemoveObserver(this);
}
bool NativeWindowTrackerAura::WasNativeWindowDestroyed() const {
return window_ == nullptr;
}
void NativeWindowTrackerAura::OnWindowDestroying(aura::Window* window) {
window_->RemoveObserver(this);
window_ = nullptr;
}
// static
std::unique_ptr<NativeWindowTracker> NativeWindowTracker::Create(
gfx::NativeWindow window) {
return std::make_unique<NativeWindowTrackerAura>(window);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/native_window_tracker_aura.cc | C++ | unknown | 919 |
// 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_NATIVE_WINDOW_TRACKER_AURA_H_
#define UI_VIEWS_NATIVE_WINDOW_TRACKER_AURA_H_
#include "base/memory/raw_ptr.h"
#include "ui/aura/window_observer.h"
#include "ui/views/native_window_tracker.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT NativeWindowTrackerAura : public NativeWindowTracker,
public aura::WindowObserver {
public:
explicit NativeWindowTrackerAura(gfx::NativeWindow window);
NativeWindowTrackerAura(const NativeWindowTrackerAura&) = delete;
NativeWindowTrackerAura& operator=(const NativeWindowTrackerAura&) = delete;
~NativeWindowTrackerAura() override;
// NativeWindowTracker:
bool WasNativeWindowDestroyed() const override;
private:
// aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override;
raw_ptr<aura::Window> window_;
};
} // namespace views
#endif // UI_VIEWS_NATIVE_WINDOW_TRACKER_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/native_window_tracker_aura.h | C++ | unknown | 1,099 |
// 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/paint_info.h"
#include "base/feature_list.h"
#include "ui/views/views_features.h"
namespace views {
namespace {
gfx::Rect GetSnappedRecordingBoundsInternal(
const gfx::Rect& paint_recording_bounds,
float device_scale_factor,
const gfx::Size& parent_size,
const gfx::Rect& child_bounds) {
const gfx::Vector2d& child_origin = child_bounds.OffsetFromOrigin();
int right = child_origin.x() + child_bounds.width();
int bottom = child_origin.y() + child_bounds.height();
int new_x = std::round(child_origin.x() * device_scale_factor);
int new_y = std::round(child_origin.y() * device_scale_factor);
int new_right;
int new_bottom;
bool empty = paint_recording_bounds.IsEmpty();
if (right == parent_size.width() && !empty)
new_right = paint_recording_bounds.width();
else
new_right = std::round(right * device_scale_factor);
if (bottom == parent_size.height() && !empty)
new_bottom = paint_recording_bounds.height();
else
new_bottom = std::round(bottom * device_scale_factor);
return gfx::Rect(new_x + paint_recording_bounds.x(),
new_y + paint_recording_bounds.y(), new_right - new_x,
new_bottom - new_y);
}
// Layer's paint info should use the corner scaling logic to compute
// the recording which is what Views uses to compte the view's
// paint_recording_bounds_, with exception that a view touches the right/bottom
// edges of the parent, and its layer has to be able to paint to these
// edges. Such cases should be handled case by case basis.
gfx::Rect GetViewsLayerRecordingBounds(const ui::PaintContext& context,
const gfx::Rect& child_bounds) {
if (!context.is_pixel_canvas())
return gfx::Rect(child_bounds.size());
return gfx::Rect(GetSnappedRecordingBoundsInternal(
gfx::Rect(), context.device_scale_factor(),
gfx::Size() /* not used */, child_bounds)
.size());
}
} // namespace
// static
PaintInfo PaintInfo::CreateRootPaintInfo(const ui::PaintContext& root_context,
const gfx::Size& size) {
return PaintInfo(root_context, size);
}
// static
PaintInfo PaintInfo::CreateChildPaintInfo(const PaintInfo& parent_paint_info,
const gfx::Rect& bounds,
const gfx::Size& parent_size,
ScaleType scale_type,
bool is_layer,
bool needs_paint) {
return PaintInfo(parent_paint_info, bounds, parent_size, scale_type, is_layer,
needs_paint);
}
PaintInfo::~PaintInfo() = default;
bool PaintInfo::IsPixelCanvas() const {
return context().is_pixel_canvas();
}
bool PaintInfo::ShouldPaint() const {
if (base::FeatureList::IsEnabled(features::kEnableViewPaintOptimization))
return needs_paint_;
return context().IsRectInvalid(gfx::Rect(paint_recording_size()));
}
PaintInfo::PaintInfo(const PaintInfo& other)
: paint_recording_scale_x_(other.paint_recording_scale_x_),
paint_recording_scale_y_(other.paint_recording_scale_y_),
paint_recording_bounds_(other.paint_recording_bounds_),
offset_from_parent_(other.offset_from_parent_),
context_(other.context(), gfx::Vector2d()),
root_context_(nullptr) {}
// The root layer should use the ScaleToEnclosingRect, the same logic that
// cc(chrome compositor) is using.
PaintInfo::PaintInfo(const ui::PaintContext& root_context,
const gfx::Size& size)
: paint_recording_scale_x_(root_context.is_pixel_canvas()
? root_context.device_scale_factor()
: 1.f),
paint_recording_scale_y_(paint_recording_scale_x_),
paint_recording_bounds_(
gfx::ScaleToEnclosingRect(gfx::Rect(size), paint_recording_scale_x_)),
context_(root_context, gfx::Vector2d()),
root_context_(&root_context) {}
PaintInfo::PaintInfo(const PaintInfo& parent_paint_info,
const gfx::Rect& bounds,
const gfx::Size& parent_size,
ScaleType scale_type,
bool is_layer,
bool needs_paint)
: paint_recording_scale_x_(1.f),
paint_recording_scale_y_(1.f),
paint_recording_bounds_(
is_layer ? GetViewsLayerRecordingBounds(parent_paint_info.context(),
bounds)
: parent_paint_info.GetSnappedRecordingBounds(parent_size,
bounds)),
offset_from_parent_(
paint_recording_bounds_.OffsetFromOrigin() -
parent_paint_info.paint_recording_bounds_.OffsetFromOrigin()),
context_(parent_paint_info.context(), offset_from_parent_),
root_context_(nullptr),
needs_paint_(needs_paint) {
if (IsPixelCanvas()) {
if (scale_type == ScaleType::kUniformScaling) {
paint_recording_scale_x_ = paint_recording_scale_y_ =
context().device_scale_factor();
} else if (scale_type == ScaleType::kScaleWithEdgeSnapping) {
if (bounds.size().width() > 0) {
paint_recording_scale_x_ =
static_cast<float>(paint_recording_bounds_.width()) /
static_cast<float>(bounds.size().width());
}
if (bounds.size().height() > 0) {
paint_recording_scale_y_ =
static_cast<float>(paint_recording_bounds_.height()) /
static_cast<float>(bounds.size().height());
}
}
}
}
gfx::Rect PaintInfo::GetSnappedRecordingBounds(
const gfx::Size& parent_size,
const gfx::Rect& child_bounds) const {
if (!IsPixelCanvas())
return (child_bounds + paint_recording_bounds_.OffsetFromOrigin());
return GetSnappedRecordingBoundsInternal(paint_recording_bounds_,
context().device_scale_factor(),
parent_size, child_bounds);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/paint_info.cc | C++ | unknown | 6,326 |
// 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_PAINT_INFO_H_
#define UI_VIEWS_PAINT_INFO_H_
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "ui/compositor/paint_context.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/views_export.h"
namespace views {
// This class manages the context required during View::Paint(). It is
// responsible for setting the paint recording size and the paint recording
// scale factors for an individual View.
// Each PaintInfo instance has paint recording offset relative to a root
// PaintInfo.
// All coordinates are in paint recording space. If pixel canvas is enabled this
// essentially becomes pixel coordinate space.
class VIEWS_EXPORT PaintInfo {
public:
enum class ScaleType {
// Scale the recordings by the default device scale factor while maintaining
// the aspect ratio. Use this when a view contains an image or icon that
// should not get distorted due to scaling.
kUniformScaling = 0,
// Scale the recordings based on the device scale factor but snap to the
// parent's bottom or right edge whenever possible. This may lead to minor
// distortion and is not recommended to be used with views that contain
// images.
kScaleWithEdgeSnapping
};
// Instantiates a root PaintInfo. This should only be initialized at the Paint
// root, ie., a layer or the root of a widget.
static PaintInfo CreateRootPaintInfo(const ui::PaintContext& root_context,
const gfx::Size& size);
// Instantiate a child PaintInfo instance. All bounds for this object are
// relative to its root PaintInfo.
static PaintInfo CreateChildPaintInfo(const PaintInfo& parent_paint_info,
const gfx::Rect& bounds,
const gfx::Size& parent_size,
ScaleType scale_type,
bool is_layer,
bool needs_paint = false);
PaintInfo(const PaintInfo& other);
~PaintInfo();
// Returns true if all paint commands are recorded at pixel size.
bool IsPixelCanvas() const;
// Returns true if the View should be painted based on whether per-view
// invalidation is enabled or not.
bool ShouldPaint() const;
const ui::PaintContext& context() const {
return root_context_ ? *root_context_ : context_;
}
gfx::Vector2d offset_from_root() const {
return paint_recording_bounds_.OffsetFromOrigin();
}
const gfx::Vector2d& offset_from_parent() const {
return offset_from_parent_;
}
float paint_recording_scale_x() const { return paint_recording_scale_x_; }
float paint_recording_scale_y() const { return paint_recording_scale_y_; }
const gfx::Size& paint_recording_size() const {
return paint_recording_bounds_.size();
}
const gfx::Rect& paint_recording_bounds() const {
return paint_recording_bounds_;
}
private:
friend class PaintInfoTest;
FRIEND_TEST_ALL_PREFIXES(PaintInfoTest, LayerPaintInfo);
PaintInfo(const ui::PaintContext& root_context, const gfx::Size& size);
PaintInfo(const PaintInfo& parent_paint_info,
const gfx::Rect& bounds,
const gfx::Size& parent_size,
ScaleType scale_type,
bool is_layer,
bool needs_paint = false);
// Scales the |child_bounds| to its recording bounds based on the
// |context.device_scale_factor()|. The recording bounds are snapped to the
// parent's right and/or bottom edge if required.
// If pixel canvas is disabled, this function returns |child_bounds| as is.
gfx::Rect GetSnappedRecordingBounds(const gfx::Size& parent_size,
const gfx::Rect& child_bounds) const;
// The scale at which the paint commands are recorded at. Due to the decimal
// rounding and snapping to edges during the scale operation, the effective
// paint recording scale may end up being slightly different between the x and
// y axis.
float paint_recording_scale_x_;
float paint_recording_scale_y_;
// Paint Recording bounds of the view. The offset is relative to the root
// PaintInfo.
const gfx::Rect paint_recording_bounds_;
// Offset relative to the parent view's paint recording bounds. Returns 0
// offset if this is the root.
gfx::Vector2d offset_from_parent_;
// Compositor PaintContext associated with the view this object belongs to.
ui::PaintContext context_;
raw_ptr<const ui::PaintContext> root_context_;
// True if the individual View has been marked invalid for paint (i.e.
// SchedulePaint() was invoked on the View).
bool needs_paint_ = false;
};
} // namespace views
#endif // UI_VIEWS_PAINT_INFO_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/paint_info.h | C++ | unknown | 4,892 |
// 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/paint_info.h"
#include <memory>
#include <vector>
#include "base/memory/ref_counted.h"
#include "cc/base/region.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/compositor/paint_context.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace views {
namespace {
using PaintInfos = std::vector<std::unique_ptr<PaintInfo>>;
// Device scale factors
constexpr float DSF100 = 1.f;
constexpr float DSF125 = 1.25f;
constexpr float DSF150 = 1.5f;
constexpr float DSF160 = 1.6f;
constexpr float DSF166 = 1.66f;
const std::vector<float> kDsfList = {DSF100, DSF125, DSF150, DSF160, DSF166};
constexpr gfx::Size kLayerSize(123, 456);
// ___________
// | 1 |
// |___________|
// | 3 | 4 | 5 | <-- 2 (encapsulates 3, 4 and 5)
// |___|___|___|
// | 7 | 8 | <-- 6 (encapsulates 7 and 8)
// |_______|___|
//
// |r_0| encapsulates 1, 2 and 6.
const gfx::Rect r_0(kLayerSize);
constexpr gfx::Rect r_1(0, 0, 123, 152);
constexpr gfx::Rect r_2(0, 152, 123, 152);
constexpr gfx::Rect r_3(0, 0, 41, 152);
constexpr gfx::Rect r_4(41, 0, 41, 152);
constexpr gfx::Rect r_5(82, 0, 41, 152);
constexpr gfx::Rect r_6(0, 304, 123, 152);
constexpr gfx::Rect r_7(0, 0, 82, 152);
constexpr gfx::Rect r_8(82, 0, 41, 152);
// Verifies that the child recording bounds completely cover the parent
// recording bounds.
void VerifyChildBoundsCoversParent(const PaintInfo* parent_paint_info,
const std::vector<PaintInfo*>& info_list) {
cc::Region remaining(gfx::Rect(parent_paint_info->paint_recording_size()));
int times_empty = 0;
for (auto* const paint_info : info_list) {
const gfx::Rect& child_recording_bounds =
paint_info->paint_recording_bounds() -
parent_paint_info->paint_recording_bounds().OffsetFromOrigin();
EXPECT_TRUE(remaining.Contains(child_recording_bounds))
<< "Remaining: " << remaining.ToString()
<< " paint recording bounds: " << child_recording_bounds.ToString();
remaining.Subtract(child_recording_bounds);
times_empty += remaining.IsEmpty();
}
EXPECT_EQ(times_empty, 1);
}
void VerifyPixelCanvasCornerScaling(const PaintInfos& info_list) {
// child 1, child 2 and child 6 should completely cover child 0.
std::vector<PaintInfo*> child_info_list;
child_info_list.push_back(info_list[1].get());
child_info_list.push_back(info_list[2].get());
child_info_list.push_back(info_list[6].get());
VerifyChildBoundsCoversParent(info_list[0].get(), child_info_list);
child_info_list.clear();
// Child 3,4 and 5 should completely cover child 2.
child_info_list.push_back(info_list[3].get());
child_info_list.push_back(info_list[4].get());
child_info_list.push_back(info_list[5].get());
VerifyChildBoundsCoversParent(info_list[2].get(), child_info_list);
child_info_list.clear();
// Child 7 and 8 should completely cover child 6.
child_info_list.push_back(info_list[7].get());
child_info_list.push_back(info_list[8].get());
VerifyChildBoundsCoversParent(info_list[6].get(), child_info_list);
child_info_list.clear();
}
void VerifyPixelSizesAreSameAsDIPSize(const PaintInfos& info_list) {
EXPECT_EQ(info_list[0]->paint_recording_size(), r_0.size());
EXPECT_EQ(info_list[1]->paint_recording_size(), r_1.size());
EXPECT_EQ(info_list[2]->paint_recording_size(), r_2.size());
EXPECT_EQ(info_list[3]->paint_recording_size(), r_3.size());
EXPECT_EQ(info_list[4]->paint_recording_size(), r_4.size());
EXPECT_EQ(info_list[5]->paint_recording_size(), r_5.size());
EXPECT_EQ(info_list[6]->paint_recording_size(), r_6.size());
EXPECT_EQ(info_list[7]->paint_recording_size(), r_7.size());
EXPECT_EQ(info_list[8]->paint_recording_size(), r_8.size());
}
} // namespace
class PaintInfoTest : public ::testing::Test {
public:
PaintInfoTest() = default;
~PaintInfoTest() override = default;
// ___________
// | 1 |
// |___________|
// | 3 | 4 | 5 | <-- 2 (encapsulates 3, 4 and 5)
// |___|___|___|
// | 7 | 8 | <-- 6 (encapsulates 7 and 8)
// |_______|___|
//
// |r_0| encapsulates 1, 2 and 6.
//
// Returns the following arrangement of paint recording bounds for the given
// |dsf|
PaintInfos GetPaintInfoSetup(const ui::PaintContext& context) {
PaintInfos info_list(9);
info_list[0].reset(new PaintInfo(context, kLayerSize));
info_list[1].reset(
new PaintInfo(*info_list[0], r_1, r_0.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[2].reset(
new PaintInfo(*info_list[0], r_2, r_0.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[3].reset(
new PaintInfo(*info_list[2], r_3, r_2.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[4].reset(
new PaintInfo(*info_list[2], r_4, r_2.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[5].reset(
new PaintInfo(*info_list[2], r_5, r_2.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[6].reset(
new PaintInfo(*info_list[0], r_6, r_0.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[7].reset(
new PaintInfo(*info_list[6], r_7, r_6.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
info_list[8].reset(
new PaintInfo(*info_list[6], r_8, r_6.size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, false));
return info_list;
}
void VerifyInvalidationRects(float dsf, bool pixel_canvas_enabled) {
std::vector<gfx::Rect> invalidation_rects = {
gfx::Rect(0, 0, 123, 41), // Intersects with 0 & 1.
gfx::Rect(0, 76, 60, 152), // Intersects 0, 1, 2, 3 & 4.
gfx::Rect(41, 152, 41, 152), // Intersects with 0, 2 & 4.
gfx::Rect(80, 320, 4, 4), // Intersects with 0, 6, 7 & 8.
gfx::Rect(40, 151, 43, 154), // Intersects all
gfx::Rect(82, 304, 1, 1), // Intersects with 0, 6 & 8.
gfx::Rect(81, 303, 2, 2) // Intersects with 0, 2, 4, 5, 6, 7, 8
};
std::vector<std::vector<int>> repaint_indices = {
std::vector<int>{0, 1},
std::vector<int>{0, 1, 2, 3, 4},
std::vector<int>{0, 2, 4},
std::vector<int>{0, 6, 7, 8},
std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8},
std::vector<int>{0, 6, 8},
std::vector<int>{0, 2, 4, 5, 6, 7, 8}};
PaintInfos info_list;
EXPECT_EQ(repaint_indices.size(), invalidation_rects.size());
for (size_t i = 0; i < invalidation_rects.size(); i++) {
ui::PaintContext context(nullptr, dsf, invalidation_rects[i],
pixel_canvas_enabled);
info_list = GetPaintInfoSetup(context);
for (int repaint_index : repaint_indices[i]) {
EXPECT_TRUE(info_list[repaint_index]->context().IsRectInvalid(
gfx::Rect(info_list[repaint_index]->paint_recording_size())));
}
info_list.clear();
}
}
};
TEST_F(PaintInfoTest, CornerScalingPixelCanvasEnabled) {
PaintInfos info_list;
for (float dsf : kDsfList) {
ui::PaintContext context(nullptr, dsf, gfx::Rect(), true);
info_list = GetPaintInfoSetup(context);
VerifyPixelCanvasCornerScaling(info_list);
info_list.clear();
}
// More accurate testing for 1.25 dsf
ui::PaintContext context(nullptr, DSF125, gfx::Rect(), true);
info_list = GetPaintInfoSetup(context);
VerifyPixelCanvasCornerScaling(info_list);
EXPECT_EQ(info_list[0]->paint_recording_size(), gfx::Size(154, 570));
EXPECT_EQ(info_list[1]->paint_recording_size(), gfx::Size(154, 190));
EXPECT_EQ(info_list[2]->paint_recording_bounds(),
gfx::Rect(0, 190, 154, 190));
EXPECT_EQ(info_list[3]->paint_recording_size(), gfx::Size(51, 190));
EXPECT_EQ(info_list[4]->paint_recording_bounds(),
gfx::Rect(51, 190, 52, 190));
EXPECT_EQ(info_list[5]->paint_recording_bounds(),
gfx::Rect(103, 190, 51, 190));
EXPECT_EQ(info_list[6]->paint_recording_bounds(),
gfx::Rect(0, 380, 154, 190));
EXPECT_EQ(info_list[7]->paint_recording_size(), gfx::Size(103, 190));
EXPECT_EQ(info_list[8]->paint_recording_bounds(),
gfx::Rect(103, 380, 51, 190));
}
TEST_F(PaintInfoTest, ScalingWithPixelCanvasDisabled) {
for (float dsf : kDsfList) {
ui::PaintContext context(nullptr, dsf, gfx::Rect(), false);
PaintInfos info_list = GetPaintInfoSetup(context);
VerifyPixelCanvasCornerScaling(info_list);
VerifyPixelSizesAreSameAsDIPSize(info_list);
info_list.clear();
}
}
TEST_F(PaintInfoTest, Invalidation) {
for (float dsf : kDsfList) {
VerifyInvalidationRects(dsf, false);
VerifyInvalidationRects(dsf, true);
}
}
// Make sure the PaintInfo used for view's layer uses the
// corderedbounds.
TEST_F(PaintInfoTest, LayerPaintInfo) {
const gfx::Rect kViewBounds(15, 20, 7, 13);
struct TestData {
const float dsf;
const gfx::Size size;
};
const TestData kTestData[6]{
{1.0f, {7, 13}}, // rounded enclosing (if these scaling is appleid)
{1.25f, {9, 16}}, // 9x16 10x17
{1.5f, {10, 20}}, // 11x20 11x20
{1.6f, {11, 21}}, // 11x21 12x21
{1.75f, {13, 23}}, // 12x23 13x23
{2.f, {14, 26}}, // 14x26 14x26
};
for (const TestData& data : kTestData) {
SCOPED_TRACE(testing::Message() << "dsf:" << data.dsf);
ui::PaintContext context(nullptr, data.dsf, gfx::Rect(), true);
PaintInfo parent_paint_info(context, gfx::Size());
PaintInfo paint_info = PaintInfo::CreateChildPaintInfo(
parent_paint_info, kViewBounds, gfx::Size(),
PaintInfo::ScaleType::kScaleWithEdgeSnapping, true);
EXPECT_EQ(gfx::Rect(data.size), paint_info.paint_recording_bounds());
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/paint_info_unittest.cc | C++ | unknown | 10,164 |
// 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/painter.h"
#include <utility>
#include "base/check.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/compositor/layer_owner.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/insets_f.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/nine_image_painter.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/views/view.h"
namespace views {
namespace {
// SolidRoundRectPainter -------------------------------------------------------
// Creates a round rect painter with a 1 pixel border. The border paints on top
// of the background.
class SolidRoundRectPainter : public Painter {
public:
SolidRoundRectPainter(SkColor bg_color,
SkColor stroke_color,
float radius,
const gfx::Insets& insets,
SkBlendMode blend_mode,
bool antialias);
SolidRoundRectPainter(const SolidRoundRectPainter&) = delete;
SolidRoundRectPainter& operator=(const SolidRoundRectPainter&) = delete;
~SolidRoundRectPainter() override;
// Painter:
gfx::Size GetMinimumSize() const override;
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override;
private:
const SkColor bg_color_;
const SkColor stroke_color_;
const float radius_;
const gfx::Insets insets_;
const SkBlendMode blend_mode_;
const bool antialias_;
};
SolidRoundRectPainter::SolidRoundRectPainter(SkColor bg_color,
SkColor stroke_color,
float radius,
const gfx::Insets& insets,
SkBlendMode blend_mode,
bool antialias)
: bg_color_(bg_color),
stroke_color_(stroke_color),
radius_(radius),
insets_(insets),
blend_mode_(blend_mode),
antialias_(antialias) {}
SolidRoundRectPainter::~SolidRoundRectPainter() = default;
gfx::Size SolidRoundRectPainter::GetMinimumSize() const {
return gfx::Size();
}
void SolidRoundRectPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) {
gfx::ScopedCanvas scoped_canvas(canvas);
const float scale = canvas->UndoDeviceScaleFactor();
gfx::Rect inset_rect(size);
inset_rect.Inset(insets_);
gfx::RectF fill_rect(gfx::ScaleToEnclosingRect(inset_rect, scale));
gfx::RectF stroke_rect = fill_rect;
float scaled_radius = radius_ * scale;
cc::PaintFlags flags;
flags.setBlendMode(blend_mode_);
if (antialias_)
flags.setAntiAlias(true);
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setColor(bg_color_);
canvas->DrawRoundRect(fill_rect, scaled_radius, flags);
if (stroke_color_ != SK_ColorTRANSPARENT) {
constexpr float kStrokeWidth = 1.0f;
stroke_rect.Inset(gfx::InsetsF(kStrokeWidth / 2));
scaled_radius -= kStrokeWidth / 2;
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(kStrokeWidth);
flags.setColor(stroke_color_);
canvas->DrawRoundRect(stroke_rect, scaled_radius, flags);
}
}
// SolidFocusPainter -----------------------------------------------------------
class SolidFocusPainter : public Painter {
public:
SolidFocusPainter(SkColor color, int thickness, const gfx::InsetsF& insets);
SolidFocusPainter(const SolidFocusPainter&) = delete;
SolidFocusPainter& operator=(const SolidFocusPainter&) = delete;
~SolidFocusPainter() override;
// Painter:
gfx::Size GetMinimumSize() const override;
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override;
private:
const SkColor color_;
const int thickness_;
const gfx::InsetsF insets_;
};
SolidFocusPainter::SolidFocusPainter(SkColor color,
int thickness,
const gfx::InsetsF& insets)
: color_(color), thickness_(thickness), insets_(insets) {}
SolidFocusPainter::~SolidFocusPainter() = default;
gfx::Size SolidFocusPainter::GetMinimumSize() const {
return gfx::Size();
}
void SolidFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) {
gfx::RectF rect((gfx::Rect(size)));
rect.Inset(insets_);
canvas->DrawSolidFocusRect(rect, color_, thickness_);
}
// ImagePainter ---------------------------------------------------------------
// ImagePainter stores and paints nine images as a scalable grid.
class ImagePainter : public Painter {
public:
// Constructs an ImagePainter with the specified image resource ids.
// See CreateImageGridPainter()'s comment regarding image ID count and order.
explicit ImagePainter(const int image_ids[]);
// Constructs an ImagePainter with the specified image and insets.
ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets);
ImagePainter(const ImagePainter&) = delete;
ImagePainter& operator=(const ImagePainter&) = delete;
~ImagePainter() override;
// Painter:
gfx::Size GetMinimumSize() const override;
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override;
private:
std::unique_ptr<gfx::NineImagePainter> nine_painter_;
};
ImagePainter::ImagePainter(const int image_ids[])
: nine_painter_(ui::CreateNineImagePainter(image_ids)) {}
ImagePainter::ImagePainter(const gfx::ImageSkia& image,
const gfx::Insets& insets)
: nine_painter_(new gfx::NineImagePainter(image, insets)) {}
ImagePainter::~ImagePainter() = default;
gfx::Size ImagePainter::GetMinimumSize() const {
return nine_painter_->GetMinimumSize();
}
void ImagePainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) {
nine_painter_->Paint(canvas, gfx::Rect(size));
}
class PaintedLayer : public ui::LayerOwner, public ui::LayerDelegate {
public:
explicit PaintedLayer(std::unique_ptr<Painter> painter);
PaintedLayer(const PaintedLayer&) = delete;
PaintedLayer& operator=(const PaintedLayer&) = delete;
~PaintedLayer() override;
// LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override;
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
private:
std::unique_ptr<Painter> painter_;
};
PaintedLayer::PaintedLayer(std::unique_ptr<Painter> painter)
: painter_(std::move(painter)) {
SetLayer(std::make_unique<ui::Layer>(ui::LAYER_TEXTURED));
layer()->set_delegate(this);
}
PaintedLayer::~PaintedLayer() = default;
void PaintedLayer::OnPaintLayer(const ui::PaintContext& context) {
ui::PaintRecorder recorder(context, layer()->size());
painter_->Paint(recorder.canvas(), layer()->size());
}
void PaintedLayer::OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {}
} // namespace
// Painter --------------------------------------------------------------------
Painter::Painter() = default;
Painter::~Painter() = default;
// static
void Painter::PaintPainterAt(gfx::Canvas* canvas,
Painter* painter,
const gfx::Rect& rect) {
DCHECK(canvas);
DCHECK(painter);
canvas->Save();
canvas->Translate(rect.OffsetFromOrigin());
painter->Paint(canvas, rect.size());
canvas->Restore();
}
// static
void Painter::PaintFocusPainter(View* view,
gfx::Canvas* canvas,
Painter* focus_painter) {
if (focus_painter && view->HasFocus())
PaintPainterAt(canvas, focus_painter, view->GetLocalBounds());
}
// static
std::unique_ptr<Painter> Painter::CreateSolidRoundRectPainter(
SkColor color,
float radius,
const gfx::Insets& insets,
SkBlendMode blend_mode,
bool antialias) {
return std::make_unique<SolidRoundRectPainter>(
color, SK_ColorTRANSPARENT, radius, insets, blend_mode, antialias);
}
// static
std::unique_ptr<Painter> Painter::CreateRoundRectWith1PxBorderPainter(
SkColor bg_color,
SkColor stroke_color,
float radius,
SkBlendMode blend_mode,
bool antialias) {
return std::make_unique<SolidRoundRectPainter>(
bg_color, stroke_color, radius, gfx::Insets(), blend_mode, antialias);
}
// static
std::unique_ptr<Painter> Painter::CreateImagePainter(
const gfx::ImageSkia& image,
const gfx::Insets& insets) {
return std::make_unique<ImagePainter>(image, insets);
}
// static
std::unique_ptr<Painter> Painter::CreateImageGridPainter(
const int image_ids[]) {
return std::make_unique<ImagePainter>(image_ids);
}
// static
std::unique_ptr<Painter> Painter::CreateSolidFocusPainter(
SkColor color,
const gfx::Insets& insets) {
// Before Canvas::DrawSolidFocusRect correctly inset the rect's bounds based
// on the thickness, callers had to add 1 to the bottom and right insets.
// Subtract that here so it works the same way with the new
// Canvas::DrawSolidFocusRect.
const gfx::InsetsF corrected_insets(insets - gfx::Insets::TLBR(0, 0, 1, 1));
return std::make_unique<SolidFocusPainter>(color, 1, corrected_insets);
}
// static
std::unique_ptr<Painter> Painter::CreateSolidFocusPainter(
SkColor color,
int thickness,
const gfx::InsetsF& insets) {
return std::make_unique<SolidFocusPainter>(color, thickness, insets);
}
// static
std::unique_ptr<ui::LayerOwner> Painter::CreatePaintedLayer(
std::unique_ptr<Painter> painter) {
return std::make_unique<PaintedLayer>(std::move(painter));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/painter.cc | C++ | unknown | 9,759 |
// 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_PAINTER_H_
#define UI_VIEWS_PAINTER_H_
#include <stddef.h>
#include <memory>
#include "third_party/skia/include/core/SkBlendMode.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/nine_image_painter_factory.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/views_export.h"
namespace gfx {
class Canvas;
class ImageSkia;
class InsetsF;
class Rect;
class Size;
} // namespace gfx
namespace ui {
class LayerOwner;
}
namespace views {
class View;
// Painter, as the name implies, is responsible for painting in a particular
// region. Think of Painter as a Border or Background that can be painted
// in any region of a View.
class VIEWS_EXPORT Painter {
public:
Painter();
Painter(const Painter&) = delete;
Painter& operator=(const Painter&) = delete;
virtual ~Painter();
// A convenience method for painting a Painter in a particular region.
// This translates the canvas to x/y and paints the painter.
static void PaintPainterAt(gfx::Canvas* canvas,
Painter* painter,
const gfx::Rect& rect);
// Convenience that paints |focus_painter| only if |view| HasFocus() and
// |focus_painter| is non-NULL.
static void PaintFocusPainter(View* view,
gfx::Canvas* canvas,
Painter* focus_painter);
// Creates a painter that draws a RoundRect with a solid color and given
// corner radius.
static std::unique_ptr<Painter> CreateSolidRoundRectPainter(
SkColor color,
float radius,
const gfx::Insets& insets = gfx::Insets(),
SkBlendMode blend_mode = SkBlendMode::kSrcOver,
bool antialias = true);
// Creates a painter that draws a RoundRect with a solid color and a given
// corner radius, and also adds a 1px border (inset) in the given color.
static std::unique_ptr<Painter> CreateRoundRectWith1PxBorderPainter(
SkColor bg_color,
SkColor stroke_color,
float radius,
SkBlendMode blend_mode = SkBlendMode::kSrcOver,
bool antialias = true);
// Creates a painter that divides |image| into nine regions. The four corners
// are rendered at the size specified in insets (eg. the upper-left corner is
// rendered at 0 x 0 with a size of insets.left() x insets.top()). The center
// and edge images are stretched to fill the painted area.
static std::unique_ptr<Painter> CreateImagePainter(
const gfx::ImageSkia& image,
const gfx::Insets& insets);
// Creates a painter that paints images in a scalable grid. The images must
// share widths by column and heights by row. The corners are painted at full
// size, while center and edge images are stretched to fill the painted area.
// The center image may be zero (to be skipped). This ordering must be used:
// Top-Left/Top/Top-Right/Left/[Center]/Right/Bottom-Left/Bottom/Bottom-Right.
static std::unique_ptr<Painter> CreateImageGridPainter(const int image_ids[]);
// Deprecated: used the InsetsF version below.
static std::unique_ptr<Painter> CreateSolidFocusPainter(
SkColor color,
const gfx::Insets& insets);
// |thickness| is in dip.
static std::unique_ptr<Painter> CreateSolidFocusPainter(
SkColor color,
int thickness,
const gfx::InsetsF& insets);
// Creates and returns a texture layer that is painted by |painter|.
static std::unique_ptr<ui::LayerOwner> CreatePaintedLayer(
std::unique_ptr<Painter> painter);
// Returns the minimum size this painter can paint without obvious graphical
// problems (e.g. overlapping images).
virtual gfx::Size GetMinimumSize() const = 0;
// Paints the painter in the specified region.
virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) = 0;
};
} // namespace views
#endif // UI_VIEWS_PAINTER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/painter.h | C++ | unknown | 3,997 |
// 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/rect_based_targeting_utils.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
namespace views {
bool UsePointBasedTargeting(const gfx::Rect& rect) {
return rect.width() == 1 && rect.height() == 1;
}
float PercentCoveredBy(const gfx::Rect& rect_1, const gfx::Rect& rect_2) {
gfx::Rect intersection(rect_1);
intersection.Intersect(rect_2);
int intersect_area = intersection.size().GetArea();
int rect_1_area = rect_1.size().GetArea();
return rect_1_area ? static_cast<float>(intersect_area) /
static_cast<float>(rect_1_area)
: 0;
}
int DistanceSquaredFromCenterToPoint(const gfx::Point& point,
const gfx::Rect& rect) {
gfx::Point center_point = rect.CenterPoint();
int dx = center_point.x() - point.x();
int dy = center_point.y() - point.y();
return (dx * dx) + (dy * dy);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/rect_based_targeting_utils.cc | C++ | unknown | 1,090 |
// 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_RECT_BASED_TARGETING_UTILS_H_
#define UI_VIEWS_RECT_BASED_TARGETING_UTILS_H_
#include "ui/views/views_export.h"
namespace gfx {
class Point;
class Rect;
} // namespace gfx
namespace views {
// Returns true if |rect| is 1x1.
VIEWS_EXPORT bool UsePointBasedTargeting(const gfx::Rect& rect);
// Returns the percentage of |rect_1|'s area that is covered by |rect_2|.
VIEWS_EXPORT float PercentCoveredBy(const gfx::Rect& rect_1,
const gfx::Rect& rect_2);
// Returns the square of the distance from |point| to the center of |rect|.
VIEWS_EXPORT int DistanceSquaredFromCenterToPoint(const gfx::Point& point,
const gfx::Rect& rect);
} // namespace views
#endif // UI_VIEWS_RECT_BASED_TARGETING_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/rect_based_targeting_utils.h | C++ | unknown | 953 |
// 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/rect_based_targeting_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/rect.h"
namespace views {
TEST(RectBasedTargetingUtils, UsePointBasedTargeting) {
gfx::Rect rect_1(gfx::Point(-22, 30), gfx::Size(1, 1));
gfx::Rect rect_2(gfx::Point(0, 0), gfx::Size(34, 55));
gfx::Rect rect_3(gfx::Point(12, 12), gfx::Size(1, 0));
gfx::Rect rect_4(gfx::Point(12, 120), gfx::Size(0, 0));
EXPECT_TRUE(UsePointBasedTargeting(rect_1));
EXPECT_FALSE(UsePointBasedTargeting(rect_2));
EXPECT_FALSE(UsePointBasedTargeting(rect_3));
EXPECT_FALSE(UsePointBasedTargeting(rect_4));
}
TEST(RectBasedTargetingUtils, PercentCoveredBy) {
gfx::Rect rect_1(gfx::Point(0, 0), gfx::Size(300, 120));
gfx::Rect rect_2(gfx::Point(20, 10), gfx::Size(30, 90));
gfx::Rect rect_3(gfx::Point(160, 50), gfx::Size(150, 85));
gfx::Rect rect_4(gfx::Point(20, 55), gfx::Size(0, 15));
float error = 0.001f;
// Passing in identical rectangles.
EXPECT_FLOAT_EQ(1.0f, PercentCoveredBy(rect_1, rect_1));
// |rect_1| completely contains |rect_2|.
EXPECT_FLOAT_EQ(0.075f, PercentCoveredBy(rect_1, rect_2));
EXPECT_FLOAT_EQ(1.0f, PercentCoveredBy(rect_2, rect_1));
// |rect_2| and |rect_3| do not intersect.
EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_2, rect_3));
// |rect_1| and |rect_3| have a nonzero area of intersection which
// is smaller than the area of either rectangle.
EXPECT_NEAR(0.272f, PercentCoveredBy(rect_1, rect_3), error);
EXPECT_NEAR(0.768f, PercentCoveredBy(rect_3, rect_1), error);
// |rect_4| has no area.
EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_2, rect_4));
EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_4, rect_2));
}
TEST(RectBasedTargetingUtils, DistanceSquaredFromCenterToPoint) {
gfx::Rect rect_1(gfx::Point(0, 0), gfx::Size(10, 10));
gfx::Rect rect_2(gfx::Point(20, 0), gfx::Size(80, 10));
gfx::Rect rect_3(gfx::Point(0, 20), gfx::Size(10, 20));
gfx::Point point_1(5, 5);
gfx::Point point_2(25, 5);
gfx::Point point_3(11, 15);
gfx::Point point_4(33, 44);
EXPECT_EQ(0, DistanceSquaredFromCenterToPoint(point_1, rect_1));
EXPECT_EQ(1225, DistanceSquaredFromCenterToPoint(point_2, rect_2));
EXPECT_EQ(3025, DistanceSquaredFromCenterToPoint(point_1, rect_2));
EXPECT_EQ(1025, DistanceSquaredFromCenterToPoint(point_2, rect_3));
EXPECT_EQ(2501, DistanceSquaredFromCenterToPoint(point_3, rect_2));
EXPECT_EQ(136, DistanceSquaredFromCenterToPoint(point_3, rect_1));
EXPECT_EQ(980, DistanceSquaredFromCenterToPoint(point_4, rect_3));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/rect_based_targeting_utils_unittest.cc | C++ | unknown | 2,721 |
// 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/repeat_controller.h"
#include <utility>
namespace views {
///////////////////////////////////////////////////////////////////////////////
// RepeatController, public:
RepeatController::RepeatController(base::RepeatingClosure callback,
const base::TickClock* tick_clock)
: timer_(tick_clock), callback_(std::move(callback)) {}
RepeatController::~RepeatController() = default;
void RepeatController::Start() {
// The first timer is slightly longer than subsequent repeats.
timer_.Start(FROM_HERE, kInitialWait, this, &RepeatController::Run);
}
void RepeatController::Stop() {
timer_.Stop();
}
///////////////////////////////////////////////////////////////////////////////
// RepeatController, private:
// static
constexpr base::TimeDelta RepeatController::kInitialWait;
// static
constexpr base::TimeDelta RepeatController::kRepeatingWait;
void RepeatController::Run() {
timer_.Start(FROM_HERE, kRepeatingWait, this, &RepeatController::Run);
callback_.Run();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/repeat_controller.cc | C++ | unknown | 1,206 |
// 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_REPEAT_CONTROLLER_H_
#define UI_VIEWS_REPEAT_CONTROLLER_H_
#include "base/functional/callback.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "ui/views/views_export.h"
namespace base {
class TickClock;
}
namespace views {
///////////////////////////////////////////////////////////////////////////////
//
// RepeatController
//
// An object that handles auto-repeating UI actions. There is a longer initial
// delay after which point repeats become constant. Users provide a callback
// that is notified when each repeat occurs so that they can perform the
// associated action.
//
///////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT RepeatController {
public:
explicit RepeatController(base::RepeatingClosure callback,
const base::TickClock* tick_clock = nullptr);
RepeatController(const RepeatController&) = delete;
RepeatController& operator=(const RepeatController&) = delete;
virtual ~RepeatController();
// Start repeating.
void Start();
// Stop repeating.
void Stop();
static constexpr base::TimeDelta GetInitialWaitForTesting() {
return kInitialWait;
}
static constexpr base::TimeDelta GetRepeatingWaitForTesting() {
return kRepeatingWait;
}
const base::OneShotTimer& timer_for_testing() const { return timer_; }
private:
// Initial time required before the first callback occurs.
static constexpr base::TimeDelta kInitialWait = base::Milliseconds(250);
// Period of callbacks after the first callback.
static constexpr base::TimeDelta kRepeatingWait = base::Milliseconds(50);
// Called when the timer expires.
void Run();
// The current timer.
base::OneShotTimer timer_;
base::RepeatingClosure callback_;
};
} // namespace views
#endif // UI_VIEWS_REPEAT_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/repeat_controller.h | C++ | unknown | 2,013 |
// 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/repeat_controller.h"
#include "base/functional/bind.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace views {
namespace {
class RepeatControllerTest : public testing::Test {
public:
RepeatControllerTest() = default;
~RepeatControllerTest() override = default;
void SetUp() override {
// Ensures that the callback hasn't fired at initialization.
ASSERT_EQ(0, times_called_);
}
protected:
// Short wait that must be below both
// RepeatController::GetInitialWaitForTesting() and
// RepeatController::GetRepeatingWaitForTesting().
static constexpr base::TimeDelta kShortWait = base::Milliseconds(10);
static_assert(
kShortWait < RepeatController::GetInitialWaitForTesting(),
"kShortWait must be shorter than the RepeatController initial wait.");
static_assert(
kShortWait < RepeatController::GetRepeatingWaitForTesting(),
"kShortWait must be shorter than the RepeatController repeating wait.");
int times_called() const { return times_called_; }
RepeatController& repeat_controller() { return repeat_controller_; }
void AdvanceTime(base::TimeDelta time_delta) {
task_environment_.FastForwardBy(time_delta);
}
private:
void IncrementTimesCalled() { ++times_called_; }
int times_called_ = 0;
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
RepeatController repeat_controller_{
base::BindRepeating(&RepeatControllerTest::IncrementTimesCalled,
base::Unretained(this)),
task_environment_.GetMockTickClock()};
};
// static
constexpr base::TimeDelta RepeatControllerTest::kShortWait;
} // namespace
TEST_F(RepeatControllerTest, StartStop) {
repeat_controller().Start();
repeat_controller().Stop();
EXPECT_EQ(0, times_called());
}
TEST_F(RepeatControllerTest, StartShortWait) {
repeat_controller().Start();
AdvanceTime(RepeatController::GetInitialWaitForTesting() - kShortWait);
EXPECT_EQ(0, times_called());
repeat_controller().Stop();
}
TEST_F(RepeatControllerTest, StartInitialWait) {
repeat_controller().Start();
AdvanceTime(RepeatController::GetInitialWaitForTesting() +
RepeatController::GetRepeatingWaitForTesting() - kShortWait);
EXPECT_EQ(1, times_called());
repeat_controller().Stop();
}
TEST_F(RepeatControllerTest, StartLongerWait) {
constexpr int kExpectedCallbacks = 34;
repeat_controller().Start();
AdvanceTime(RepeatController::GetInitialWaitForTesting() +
(RepeatController::GetRepeatingWaitForTesting() *
(kExpectedCallbacks - 1)) +
kShortWait);
EXPECT_EQ(kExpectedCallbacks, times_called());
repeat_controller().Stop();
}
TEST_F(RepeatControllerTest, NoCallbacksAfterStop) {
constexpr int kExpectedCallbacks = 34;
repeat_controller().Start();
AdvanceTime(RepeatController::GetInitialWaitForTesting() +
(RepeatController::GetRepeatingWaitForTesting() *
(kExpectedCallbacks - 1)) +
kShortWait);
repeat_controller().Stop();
AdvanceTime(RepeatController::GetInitialWaitForTesting() +
RepeatController::GetRepeatingWaitForTesting());
EXPECT_EQ(kExpectedCallbacks, times_called());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/repeat_controller_unittest.cc | C++ | unknown | 3,497 |
// 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/round_rect_painter.h"
#include "cc/paint/paint_canvas.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/skia_conversions.h"
namespace views {
RoundRectPainter::RoundRectPainter(SkColor border_color, int corner_radius)
: border_color_(border_color), corner_radius_(corner_radius) {}
RoundRectPainter::~RoundRectPainter() = default;
gfx::Size RoundRectPainter::GetMinimumSize() const {
return gfx::Size(1, 1);
}
void RoundRectPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) {
cc::PaintFlags flags;
flags.setColor(border_color_);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(kBorderWidth);
flags.setAntiAlias(true);
gfx::Rect rect(size);
rect.Inset(gfx::Insets::TLBR(0, 0, kBorderWidth, kBorderWidth));
SkRect skia_rect = gfx::RectToSkRect(rect);
skia_rect.offset(kBorderWidth / 2.f, kBorderWidth / 2.f);
canvas->sk_canvas()->drawRoundRect(skia_rect, SkIntToScalar(corner_radius_),
SkIntToScalar(corner_radius_), flags);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/round_rect_painter.cc | C++ | unknown | 1,215 |
// 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_ROUND_RECT_PAINTER_H_
#define UI_VIEWS_ROUND_RECT_PAINTER_H_
#include "ui/gfx/geometry/rect.h"
#include "ui/views/painter.h"
#include "ui/views/views_export.h"
namespace gfx {
class Canvas;
class Size;
} // namespace gfx
namespace views {
// Painter to draw a border with rounded corners.
class VIEWS_EXPORT RoundRectPainter : public Painter {
public:
static constexpr int kBorderWidth = 1;
RoundRectPainter(SkColor border_color, int corner_radius);
RoundRectPainter(const RoundRectPainter&) = delete;
RoundRectPainter& operator=(const RoundRectPainter&) = delete;
~RoundRectPainter() override;
// Painter:
gfx::Size GetMinimumSize() const override;
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override;
private:
const SkColor border_color_;
const int corner_radius_;
};
} // namespace views
#endif // UI_VIEWS_ROUND_RECT_PAINTER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/round_rect_painter.h | C++ | unknown | 1,041 |
// 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 "mojo/core/embedder/embedder.h"
#include "ui/views/views_test_suite.h"
int main(int argc, char** argv) {
mojo::core::Init();
return views::ViewsTestSuite(argc, argv).RunTests();
}
| Zhao-PengFei35/chromium_src_4 | ui/views/run_all_unittests_main.cc | C++ | unknown | 338 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/selection_controller.h"
#include <algorithm>
#include <vector>
#include "build/build_config.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/events/event.h"
#include "ui/gfx/render_text.h"
#include "ui/views/metrics.h"
#include "ui/views/selection_controller_delegate.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/view.h"
namespace views {
SelectionController::SelectionController(SelectionControllerDelegate* delegate)
: delegate_(delegate) {
// If selection clipboard is used, update it on a text selection.
if (ui::Clipboard::IsSupportedClipboardBuffer(
ui::ClipboardBuffer::kSelection)) {
set_handles_selection_clipboard(true);
}
DCHECK(delegate);
}
bool SelectionController::OnMousePressed(
const ui::MouseEvent& event,
bool handled,
InitialFocusStateOnMousePress initial_focus_state) {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
TrackMouseClicks(event);
if (handled)
return true;
if (event.IsOnlyLeftMouseButton()) {
first_drag_location_ = event.location();
if (delegate_->SupportsDrag())
delegate_->SetTextBeingDragged(false);
switch (aggregated_clicks_) {
case 0:
// If the click location is within an existing selection, it may be a
// potential drag and drop.
if (delegate_->SupportsDrag() &&
render_text->IsPointInSelection(event.location())) {
delegate_->SetTextBeingDragged(true);
} else {
delegate_->OnBeforePointerAction();
const bool selection_changed = render_text->MoveCursorToPoint(
event.location(), event.IsShiftDown());
delegate_->OnAfterPointerAction(false, selection_changed);
}
break;
case 1:
// Select the word at the click location on a double click.
SelectWord(event.location());
double_click_word_ = render_text->selection();
break;
case 2:
// Select all the text on a triple click.
SelectAll();
break;
default:
NOTREACHED_NORETURN();
}
}
if (event.IsOnlyRightMouseButton()) {
if (PlatformStyle::kSelectAllOnRightClickWhenUnfocused &&
initial_focus_state == InitialFocusStateOnMousePress::kUnFocused) {
SelectAll();
} else if (PlatformStyle::kSelectWordOnRightClick &&
!render_text->IsPointInSelection(event.location()) &&
IsInsideText(event.location())) {
SelectWord(event.location());
}
}
if (handles_selection_clipboard_ && event.IsOnlyMiddleMouseButton() &&
!delegate_->IsReadOnly()) {
delegate_->OnBeforePointerAction();
const bool selection_changed =
render_text->MoveCursorToPoint(event.location(), false);
const bool text_changed = delegate_->PasteSelectionClipboard();
delegate_->OnAfterPointerAction(text_changed,
selection_changed | text_changed);
}
return true;
}
bool SelectionController::OnMouseDragged(const ui::MouseEvent& event) {
DCHECK(GetRenderText());
// If |drag_selection_timer_| is running, |last_drag_location_| will be used
// to update the selection.
last_drag_location_ = event.location();
// Don't adjust the cursor on a potential drag and drop.
if (delegate_->HasTextBeingDragged() || !event.IsOnlyLeftMouseButton())
return true;
// A timer is used to continuously scroll while selecting beyond side edges.
const int x = event.location().x();
const int width = delegate_->GetViewWidth();
const int drag_selection_delay = delegate_->GetDragSelectionDelay();
if ((x >= 0 && x <= width) || drag_selection_delay == 0) {
drag_selection_timer_.Stop();
SelectThroughLastDragLocation();
} else if (!drag_selection_timer_.IsRunning()) {
// Select through the edge of the visible text, then start the scroll timer.
last_drag_location_.set_x(std::clamp(x, 0, width));
SelectThroughLastDragLocation();
drag_selection_timer_.Start(
FROM_HERE, base::Milliseconds(drag_selection_delay), this,
&SelectionController::SelectThroughLastDragLocation);
}
return true;
}
void SelectionController::OnMouseReleased(const ui::MouseEvent& event) {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
drag_selection_timer_.Stop();
// Cancel suspected drag initiations, the user was clicking in the selection.
if (delegate_->HasTextBeingDragged()) {
delegate_->OnBeforePointerAction();
const bool selection_changed =
render_text->MoveCursorToPoint(event.location(), false);
delegate_->OnAfterPointerAction(false, selection_changed);
}
if (delegate_->SupportsDrag())
delegate_->SetTextBeingDragged(false);
if (handles_selection_clipboard_ && !render_text->selection().is_empty())
delegate_->UpdateSelectionClipboard();
}
void SelectionController::OnMouseCaptureLost() {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
drag_selection_timer_.Stop();
if (handles_selection_clipboard_ && !render_text->selection().is_empty())
delegate_->UpdateSelectionClipboard();
}
void SelectionController::OffsetDoubleClickWord(size_t offset) {
double_click_word_.set_start(double_click_word_.start() + offset);
double_click_word_.set_end(double_click_word_.end() + offset);
}
void SelectionController::TrackMouseClicks(const ui::MouseEvent& event) {
if (event.IsOnlyLeftMouseButton()) {
base::TimeDelta time_delta = event.time_stamp() - last_click_time_;
if (!last_click_time_.is_null() &&
time_delta.InMilliseconds() <= GetDoubleClickInterval() &&
!View::ExceededDragThreshold(event.root_location() -
last_click_root_location_)) {
// Upon clicking after a triple click, the count should go back to
// double click and alternate between double and triple. This assignment
// maps 0 to 1, 1 to 2, 2 to 1.
aggregated_clicks_ = (aggregated_clicks_ % 2) + 1;
} else {
aggregated_clicks_ = 0;
}
last_click_time_ = event.time_stamp();
last_click_root_location_ = event.root_location();
}
}
void SelectionController::SelectWord(const gfx::Point& point) {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
delegate_->OnBeforePointerAction();
render_text->MoveCursorToPoint(point, false);
render_text->SelectWord();
delegate_->OnAfterPointerAction(false, true);
}
void SelectionController::SelectAll() {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
delegate_->OnBeforePointerAction();
render_text->SelectAll(false);
delegate_->OnAfterPointerAction(false, true);
}
gfx::RenderText* SelectionController::GetRenderText() {
return delegate_->GetRenderTextForSelectionController();
}
void SelectionController::SelectThroughLastDragLocation() {
gfx::RenderText* render_text = GetRenderText();
DCHECK(render_text);
delegate_->OnBeforePointerAction();
// Note that |first_drag_location_| is only used when
// RenderText::kDragToEndIfOutsideVerticalBounds, which is platform-specific.
render_text->MoveCursorToPoint(last_drag_location_, true,
first_drag_location_);
if (aggregated_clicks_ == 1) {
render_text->SelectWord();
// Expand the selection so the initially selected word remains selected.
gfx::Range selection = render_text->selection();
const size_t min =
std::min(selection.GetMin(), double_click_word_.GetMin());
const size_t max =
std::max(selection.GetMax(), double_click_word_.GetMax());
const bool reversed = selection.is_reversed();
selection.set_start(reversed ? max : min);
selection.set_end(reversed ? min : max);
render_text->SelectRange(selection);
}
delegate_->OnAfterPointerAction(false, true);
}
bool SelectionController::IsInsideText(const gfx::Point& point) {
gfx::RenderText* render_text = GetRenderText();
std::vector<gfx::Rect> bounds_rects = render_text->GetSubstringBounds(
gfx::Range(0, render_text->text().length()));
for (const auto& bounds : bounds_rects)
if (bounds.Contains(point))
return true;
return false;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/selection_controller.cc | C++ | unknown | 8,411 |
// 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_SELECTION_CONTROLLER_H_
#define UI_VIEWS_SELECTION_CONTROLLER_H_
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/range/range.h"
#include "ui/gfx/selection_model.h"
#include "ui/views/views_export.h"
namespace gfx {
class RenderText;
}
namespace ui {
class MouseEvent;
}
namespace views {
class SelectionControllerDelegate;
// Helper class used to facilitate mouse event handling and text selection. To
// use, clients must implement the SelectionControllerDelegate interface.
// TODO(karandeepb): Also make this class handle gesture events.
class VIEWS_EXPORT SelectionController {
public:
// Describes whether the view managing the delegate was initially focused when
// the mouse press was received.
enum class InitialFocusStateOnMousePress {
kFocused,
kUnFocused,
};
// |delegate| must be non-null.
explicit SelectionController(SelectionControllerDelegate* delegate);
SelectionController(const SelectionController&) = delete;
SelectionController& operator=(const SelectionController&) = delete;
// Handle mouse events forwarded by |delegate_|. |handled| specifies whether
// the event has already been handled by the |delegate_|. If |handled| is
// true, the mouse event is just used to update the internal state without
// updating the state of the associated RenderText instance.
bool OnMousePressed(const ui::MouseEvent& event,
bool handled,
InitialFocusStateOnMousePress initial_focus_state);
bool OnMouseDragged(const ui::MouseEvent& event);
void OnMouseReleased(const ui::MouseEvent& event);
void OnMouseCaptureLost();
// Returns the latest click location in root coordinates.
const gfx::Point& last_click_root_location() const {
return last_click_root_location_;
}
// Sets whether the SelectionController should update or paste the
// selection clipboard on middle-click. Default is false.
void set_handles_selection_clipboard(bool value) {
handles_selection_clipboard_ = value;
}
// Offsets the double-clicked word's range. This is only used in the unusual
// case where the text changes on the second mousedown of a double-click.
// This is harmless if there is not a currently double-clicked word.
void OffsetDoubleClickWord(size_t offset);
private:
// Tracks the mouse clicks for single/double/triple clicks.
void TrackMouseClicks(const ui::MouseEvent& event);
// Selects the word at the given |point|.
void SelectWord(const gfx::Point& point);
// Selects all the text.
void SelectAll();
// Returns the associated render text instance via the |delegate_|.
gfx::RenderText* GetRenderText();
// Helper function to update the selection on a mouse drag as per
// |last_drag_location_|. Can be called asynchronously, through a timer.
void SelectThroughLastDragLocation();
// Returns whether |point| is inside any substring of the text.
bool IsInsideText(const gfx::Point& point);
// A timer and point used to modify the selection when dragging. The
// |first_drag_location_| field is used to store where the drag-to-select
// started.
base::RepeatingTimer drag_selection_timer_;
gfx::Point last_drag_location_;
gfx::Point first_drag_location_;
// State variables used to track the last click time and location.
base::TimeTicks last_click_time_;
gfx::Point last_click_root_location_;
// Used to track double and triple clicks. Can take the values 0, 1 and 2
// which specify a single, double and triple click respectively. Alternates
// between a double and triple click for continuous clicks.
size_t aggregated_clicks_ = 0;
// The range selected on a double click.
gfx::Range double_click_word_;
// Weak pointer.
raw_ptr<SelectionControllerDelegate> delegate_;
// Whether the selection clipboard is handled.
bool handles_selection_clipboard_ = false;
};
} // namespace views
#endif // UI_VIEWS_SELECTION_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/selection_controller.h | C++ | unknown | 4,190 |
// 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_SELECTION_CONTROLLER_DELEGATE_H_
#define UI_VIEWS_SELECTION_CONTROLLER_DELEGATE_H_
#include "ui/views/views_export.h"
namespace views {
// An interface implemented/managed by a view which uses the
// SelectionController.
class VIEWS_EXPORT SelectionControllerDelegate {
public:
// Returns the associated RenderText instance to be used for selection.
virtual gfx::RenderText* GetRenderTextForSelectionController() = 0;
// Methods related to properties of the associated view.
// Returns true if the associated text view is read only.
virtual bool IsReadOnly() const = 0;
// Returns whether the associated view supports drag-and-drop.
virtual bool SupportsDrag() const = 0;
// Returns whether there is a drag operation originating from the associated
// view.
virtual bool HasTextBeingDragged() const = 0;
// Sets whether text is being dragged from the associated view. Called only if
// the delegate supports drag.
virtual void SetTextBeingDragged(bool value) = 0;
// Returns the height of the associated view.
virtual int GetViewHeight() const = 0;
// Returns the width of the associated view.
virtual int GetViewWidth() const = 0;
// Returns the drag selection timer delay. This is the duration after which a
// drag selection is updated when the event location is outside the text
// bounds.
virtual int GetDragSelectionDelay() const = 0;
// Called before a pointer action which may change the associated view's
// selection and/or text. Should not be called in succession and must always
// be followed by an OnAfterPointerAction call.
virtual void OnBeforePointerAction() = 0;
// Called after a pointer action. |text_changed| and |selection_changed| can
// be used by subclasses to make any necessary updates like redraw the text.
// Must always be preceeded by an OnBeforePointerAction call.
virtual void OnAfterPointerAction(bool text_changed,
bool selection_changed) = 0;
// Pastes the text from the selection clipboard at the current cursor
// position. Always called within a pointer action for a non-readonly view.
// Returns true if some text was pasted.
virtual bool PasteSelectionClipboard() = 0;
// Updates the selection clipboard with the currently selected text. Should
// empty the selection clipboard if no text is currently selected.
// NO-OP if the associated text view is obscured. Since this does not modify
// the render text instance, it may be called outside of a pointer action.
virtual void UpdateSelectionClipboard() = 0;
protected:
virtual ~SelectionControllerDelegate() = default;
};
} // namespace views
#endif // UI_VIEWS_SELECTION_CONTROLLER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/selection_controller_delegate.h | C++ | unknown | 2,876 |
// 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/selection_controller.h"
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/render_text.h"
#include "ui/views/metrics.h"
#include "ui/views/selection_controller_delegate.h"
#include "ui/views/style/platform_style.h"
namespace views {
namespace {
const gfx::Point CenterLeft(const gfx::Rect& rect) {
return gfx::Point(rect.x(), rect.CenterPoint().y());
}
const gfx::Point CenterRight(const gfx::Rect& rect) {
return gfx::Point(rect.right(), rect.CenterPoint().y());
}
class TestSelectionControllerDelegate : public SelectionControllerDelegate {
public:
explicit TestSelectionControllerDelegate(gfx::RenderText* render_text)
: render_text_(render_text) {}
TestSelectionControllerDelegate(const TestSelectionControllerDelegate&) =
delete;
TestSelectionControllerDelegate& operator=(
const TestSelectionControllerDelegate&) = delete;
~TestSelectionControllerDelegate() override = default;
gfx::RenderText* GetRenderTextForSelectionController() override {
return render_text_;
}
bool IsReadOnly() const override { return true; }
bool SupportsDrag() const override { return true; }
bool HasTextBeingDragged() const override { return false; }
void SetTextBeingDragged(bool value) override {}
int GetViewHeight() const override {
return render_text_->GetStringSize().height();
}
int GetViewWidth() const override {
return render_text_->GetStringSize().width();
}
int GetDragSelectionDelay() const override { return 0; }
void OnBeforePointerAction() override {}
void OnAfterPointerAction(bool text_changed,
bool selection_changed) override {}
bool PasteSelectionClipboard() override { return false; }
void UpdateSelectionClipboard() override {}
private:
raw_ptr<gfx::RenderText> render_text_;
};
class SelectionControllerTest : public ::testing::Test {
public:
void SetUp() override {
render_text_ = gfx::RenderText::CreateRenderText();
delegate_ =
std::make_unique<TestSelectionControllerDelegate>(render_text_.get());
controller_ = std::make_unique<SelectionController>(delegate_.get());
}
SelectionControllerTest()
: task_environment_(base::test::TaskEnvironment::MainThreadType::UI) {}
SelectionControllerTest(const SelectionControllerTest&) = delete;
SelectionControllerTest& operator=(const SelectionControllerTest&) = delete;
~SelectionControllerTest() override = default;
void SetText(const std::string& text) {
render_text_->SetText(base::ASCIIToUTF16(text));
}
std::string GetSelectedText() {
return base::UTF16ToASCII(
render_text_->GetTextFromRange(render_text_->selection()));
}
void LeftMouseDown(const gfx::Point& location, bool focused = false) {
PressMouseButton(location, ui::EF_LEFT_MOUSE_BUTTON, focused);
}
void LeftMouseUp() { ReleaseMouseButton(ui::EF_LEFT_MOUSE_BUTTON); }
void DragMouse(const gfx::Point& location) {
mouse_location_ = location;
controller_->OnMouseDragged(ui::MouseEvent(ui::ET_MOUSE_DRAGGED, location,
location, last_event_time_,
mouse_flags_, 0));
}
void RightMouseDown(const gfx::Point& location, bool focused = false) {
PressMouseButton(location, ui::EF_RIGHT_MOUSE_BUTTON, focused);
}
void RightMouseUp() { ReleaseMouseButton(ui::EF_RIGHT_MOUSE_BUTTON); }
const gfx::Rect BoundsOfChar(int index) {
return render_text_->GetSubstringBounds(gfx::Range(index, index + 1))[0];
}
gfx::Point TranslatePointX(const gfx::Point& point, int delta) {
return point + gfx::Vector2d(delta, 0);
}
private:
void PressMouseButton(const gfx::Point& location, int button, bool focused) {
DCHECK(!(mouse_flags_ & button));
mouse_flags_ |= button;
mouse_location_ = location;
// Ensure that mouse presses are spaced apart by at least the double-click
// interval to avoid triggering a double-click.
last_event_time_ += base::Milliseconds(views::GetDoubleClickInterval() + 1);
controller_->OnMousePressed(
ui::MouseEvent(ui::ET_MOUSE_PRESSED, location, location,
last_event_time_, mouse_flags_, button),
false,
focused
? SelectionController::InitialFocusStateOnMousePress::kFocused
: SelectionController::InitialFocusStateOnMousePress::kUnFocused);
}
void ReleaseMouseButton(int button) {
DCHECK(mouse_flags_ & button);
mouse_flags_ &= ~button;
controller_->OnMouseReleased(
ui::MouseEvent(ui::ET_MOUSE_RELEASED, mouse_location_, mouse_location_,
last_event_time_, mouse_flags_, button));
}
base::test::TaskEnvironment task_environment_;
std::unique_ptr<gfx::RenderText> render_text_;
std::unique_ptr<TestSelectionControllerDelegate> delegate_;
std::unique_ptr<SelectionController> controller_;
int mouse_flags_ = 0;
gfx::Point mouse_location_;
base::TimeTicks last_event_time_;
};
TEST_F(SelectionControllerTest, ClickAndDragToSelect) {
SetText("abc def");
EXPECT_EQ("", GetSelectedText());
LeftMouseDown(CenterLeft(BoundsOfChar(0)));
DragMouse(CenterRight(BoundsOfChar(0)));
EXPECT_EQ("a", GetSelectedText());
DragMouse(CenterRight(BoundsOfChar(2)));
EXPECT_EQ("abc", GetSelectedText());
LeftMouseUp();
EXPECT_EQ("abc", GetSelectedText());
LeftMouseDown(CenterRight(BoundsOfChar(3)));
EXPECT_EQ("", GetSelectedText());
DragMouse(CenterRight(BoundsOfChar(4)));
EXPECT_EQ("d", GetSelectedText());
}
TEST_F(SelectionControllerTest, RightClickWhenUnfocused) {
SetText("abc def");
RightMouseDown(CenterRight(BoundsOfChar(0)));
if (PlatformStyle::kSelectAllOnRightClickWhenUnfocused)
EXPECT_EQ("abc def", GetSelectedText());
else
EXPECT_EQ("", GetSelectedText());
}
TEST_F(SelectionControllerTest, RightClickSelectsWord) {
SetText("abc def");
RightMouseDown(CenterRight(BoundsOfChar(5)), true);
if (PlatformStyle::kSelectWordOnRightClick)
EXPECT_EQ("def", GetSelectedText());
else
EXPECT_EQ("", GetSelectedText());
}
// Regression test for https://crbug.com/856609
TEST_F(SelectionControllerTest, RightClickPastEndDoesntSelectLastWord) {
SetText("abc def");
RightMouseDown(CenterRight(BoundsOfChar(6)), true);
EXPECT_EQ("", GetSelectedText());
}
// Regression test for https://crbug.com/731252
// This test validates that drags which are:
// a) Above or below the text, and
// b) Past one end of the text
// behave properly with regard to RenderText::kDragToEndIfOutsideVerticalBounds.
// When that option is true, drags outside the text that are horizontally
// "towards" the text should select all of it; when that option is false, those
// drags should have no effect.
TEST_F(SelectionControllerTest, DragPastEndUsesProperOrigin) {
SetText("abc def");
gfx::Point point = BoundsOfChar(6).top_right() + gfx::Vector2d(100, -10);
LeftMouseDown(point);
EXPECT_EQ("", GetSelectedText());
DragMouse(TranslatePointX(point, -1));
if (gfx::RenderText::kDragToEndIfOutsideVerticalBounds)
EXPECT_EQ("abc def", GetSelectedText());
else
EXPECT_EQ("", GetSelectedText());
DragMouse(TranslatePointX(point, 1));
EXPECT_EQ("", GetSelectedText());
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/selection_controller_unittest.cc | C++ | unknown | 7,766 |
// 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/style/platform_style.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/range/range.h"
#include "ui/gfx/utf16_indexing.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/background.h"
#include "ui/views/buildflags.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/controls/focusable_border.h"
#include "ui/views/controls/scrollbar/scroll_bar_views.h"
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
#include "ui/views/controls/scrollbar/overlay_scroll_bar.h"
#endif
namespace views {
#if BUILDFLAG(IS_WIN)
const bool PlatformStyle::kIsOkButtonLeading = true;
#else
const bool PlatformStyle::kIsOkButtonLeading = false;
#endif
#if !BUILDFLAG(IS_MAC)
const int PlatformStyle::kMinLabelButtonWidth = 70;
const int PlatformStyle::kMinLabelButtonHeight = 33;
const bool PlatformStyle::kDialogDefaultButtonCanBeCancel = true;
const bool PlatformStyle::kSelectWordOnRightClick = false;
const bool PlatformStyle::kSelectAllOnRightClickWhenUnfocused = false;
const Button::KeyClickAction PlatformStyle::kKeyClickActionOnSpace =
Button::KeyClickAction::kOnKeyRelease;
const bool PlatformStyle::kReturnClicksFocusedControl = true;
const bool PlatformStyle::kTableViewSupportsKeyboardNavigationByCell = true;
const bool PlatformStyle::kTreeViewSelectionPaintsEntireRow = false;
const bool PlatformStyle::kUseRipples = true;
const bool PlatformStyle::kTextfieldUsesDragCursorWhenDraggable = true;
const bool PlatformStyle::kInactiveWidgetControlsAppearDisabled = false;
const View::FocusBehavior PlatformStyle::kDefaultFocusBehavior =
View::FocusBehavior::ALWAYS;
// Linux clips bubble windows that extend outside their parent window
// bounds.
const bool PlatformStyle::kAdjustBubbleIfOffscreen =
#if BUILDFLAG(IS_LINUX)
false;
#else
true;
#endif
// static
std::unique_ptr<ScrollBar> PlatformStyle::CreateScrollBar(bool is_horizontal) {
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
return std::make_unique<OverlayScrollBar>(is_horizontal);
#else
return std::make_unique<ScrollBarViews>(is_horizontal);
#endif
}
// static
void PlatformStyle::OnTextfieldEditFailed() {}
// static
gfx::Range PlatformStyle::RangeToDeleteBackwards(const std::u16string& text,
size_t cursor_position) {
// Delete one code point, which may be two UTF-16 words.
size_t previous_grapheme_index =
gfx::UTF16OffsetToIndex(text, cursor_position, -1);
return gfx::Range(cursor_position, previous_grapheme_index);
}
#endif // !BUILDFLAG(IS_MAC)
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/style/platform_style.cc | C++ | unknown | 2,869 |
// 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_STYLE_PLATFORM_STYLE_H_
#define UI_VIEWS_STYLE_PLATFORM_STYLE_H_
#include <memory>
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace gfx {
class Range;
} // namespace gfx
namespace views {
class ScrollBar;
// Cross-platform API for providing platform-specific styling for toolkit-views.
class VIEWS_EXPORT PlatformStyle {
public:
PlatformStyle() = delete;
PlatformStyle(const PlatformStyle&) = delete;
PlatformStyle& operator=(const PlatformStyle&) = delete;
// Whether the ok button is in the leading position (left in LTR) in a
// typical Cancel/OK button group.
static const bool kIsOkButtonLeading;
// Minimum size for platform-styled buttons.
static const int kMinLabelButtonWidth;
static const int kMinLabelButtonHeight;
// Whether the default button for a dialog can be the Cancel button.
static const bool kDialogDefaultButtonCanBeCancel;
// Whether right clicking on text, selects the word under cursor.
static const bool kSelectWordOnRightClick;
// Whether right clicking inside an unfocused text view selects all the text.
static const bool kSelectAllOnRightClickWhenUnfocused;
// Whether the Space key clicks a button on key press or key release.
static const Button::KeyClickAction kKeyClickActionOnSpace;
// Whether the Return key clicks the focused control (on key press).
// Otherwise, Return does nothing unless it is handled by an accelerator.
static const bool kReturnClicksFocusedControl;
// Whether cursor left and right can be used in a TableView to select and
// resize columns and whether a focus ring should be shown around the active
// cell.
static const bool kTableViewSupportsKeyboardNavigationByCell;
// Whether selecting a row in a TreeView selects the entire row or only the
// label for that row.
static const bool kTreeViewSelectionPaintsEntireRow;
// Whether ripples should be used for visual feedback on control activation.
static const bool kUseRipples;
// Whether text fields should use a "drag" cursor when not actually
// dragging but available to do so.
static const bool kTextfieldUsesDragCursorWhenDraggable;
// Whether controls in inactive widgets appear disabled.
static const bool kInactiveWidgetControlsAppearDisabled;
// Default setting at bubble creation time for whether arrow will be adjusted
// for bubbles going off-screen to bring more bubble area into view.
static const bool kAdjustBubbleIfOffscreen;
// Default focus behavior on the platform.
static const View::FocusBehavior kDefaultFocusBehavior;
// Creates the default scrollbar for the given orientation.
static std::unique_ptr<ScrollBar> CreateScrollBar(bool is_horizontal);
// Called whenever a textfield edit fails. Gives visual/audio feedback about
// the failed edit if platform-appropriate.
static void OnTextfieldEditFailed();
// When deleting backwards in |string| with the cursor at index
// |cursor_position|, return the range of UTF-16 words to be deleted.
// This is to support deleting entire graphemes instead of individual
// characters when necessary on Mac, and code points made from surrogate
// pairs on other platforms.
static gfx::Range RangeToDeleteBackwards(const std::u16string& text,
size_t cursor_position);
};
} // namespace views
#endif // UI_VIEWS_STYLE_PLATFORM_STYLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/style/platform_style.h | C++ | unknown | 3,612 |
// 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/style/platform_style.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "ui/base/buildflags.h"
#include "ui/gfx/color_utils.h"
#include "ui/views/controls/button/label_button.h"
#import "ui/views/controls/scrollbar/cocoa_scroll_bar.h"
#import <Cocoa/Cocoa.h>
extern "C" {
// From CFString private headers.
typedef CF_ENUM(CFIndex, CFStringCharacterClusterType) {
kCFStringGraphemeCluster = 1, /* Unicode Grapheme Cluster */
kCFStringComposedCharacterCluster =
2, /* Compose all non-base (including spacing marks) */
kCFStringCursorMovementCluster =
3, /* Cluster suitable for cursor movements */
kCFStringBackwardDeletionCluster =
4 /* Cluster suitable for backward deletion */
};
CFRange CFStringGetRangeOfCharacterClusterAtIndex(
CFStringRef string,
CFIndex index,
CFStringCharacterClusterType type);
}
namespace views {
const int PlatformStyle::kMinLabelButtonWidth = 32;
const int PlatformStyle::kMinLabelButtonHeight = 30;
const bool PlatformStyle::kDialogDefaultButtonCanBeCancel = false;
const bool PlatformStyle::kSelectWordOnRightClick = true;
const bool PlatformStyle::kSelectAllOnRightClickWhenUnfocused = true;
const bool PlatformStyle::kTextfieldUsesDragCursorWhenDraggable = false;
const bool PlatformStyle::kTableViewSupportsKeyboardNavigationByCell = false;
const bool PlatformStyle::kTreeViewSelectionPaintsEntireRow = true;
const bool PlatformStyle::kUseRipples = false;
const bool PlatformStyle::kInactiveWidgetControlsAppearDisabled = true;
const bool PlatformStyle::kAdjustBubbleIfOffscreen = false;
const View::FocusBehavior PlatformStyle::kDefaultFocusBehavior =
View::FocusBehavior::ACCESSIBLE_ONLY;
const Button::KeyClickAction PlatformStyle::kKeyClickActionOnSpace =
Button::KeyClickAction::kOnKeyPress;
// On Mac, the Return key is used to perform the default action even when a
// control is focused.
const bool PlatformStyle::kReturnClicksFocusedControl = false;
// static
std::unique_ptr<ScrollBar> PlatformStyle::CreateScrollBar(bool is_horizontal) {
return std::make_unique<CocoaScrollBar>(is_horizontal);
}
// static
void PlatformStyle::OnTextfieldEditFailed() {
NSBeep();
}
// static
gfx::Range PlatformStyle::RangeToDeleteBackwards(const std::u16string& text,
size_t cursor_position) {
if (cursor_position == 0)
return gfx::Range();
base::ScopedCFTypeRef<CFStringRef> cf_string(CFStringCreateWithCharacters(
kCFAllocatorDefault, reinterpret_cast<const UniChar*>(text.data()),
base::checked_cast<CFIndex>(text.size())));
CFRange range_to_delete = CFStringGetRangeOfCharacterClusterAtIndex(
cf_string, base::checked_cast<CFIndex>(cursor_position - 1),
kCFStringBackwardDeletionCluster);
if (range_to_delete.location == NSNotFound)
return gfx::Range();
// The range needs to be reversed to undo correctly.
return gfx::Range(base::checked_cast<size_t>(range_to_delete.location +
range_to_delete.length),
base::checked_cast<size_t>(range_to_delete.location));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/style/platform_style_mac.mm | Objective-C++ | unknown | 3,356 |
// 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/style/typography.h"
#include "base/check_op.h"
#include "ui/color/color_id.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/typography_provider.h"
namespace views::style {
namespace {
void ValidateContextAndStyle(int context, int style) {
DCHECK_GE(context, VIEWS_TEXT_CONTEXT_START);
DCHECK_LT(context, TEXT_CONTEXT_MAX);
DCHECK_GE(style, VIEWS_TEXT_STYLE_START);
}
} // namespace
ui::ResourceBundle::FontDetails GetFontDetails(int context, int style) {
ValidateContextAndStyle(context, style);
return LayoutProvider::Get()->GetTypographyProvider().GetFontDetails(context,
style);
}
const gfx::FontList& GetFont(int context, int style) {
ValidateContextAndStyle(context, style);
return LayoutProvider::Get()->GetTypographyProvider().GetFont(context, style);
}
ui::ColorId GetColorId(int context, int style) {
ValidateContextAndStyle(context, style);
return LayoutProvider::Get()->GetTypographyProvider().GetColorId(context,
style);
}
int GetLineHeight(int context, int style) {
ValidateContextAndStyle(context, style);
return LayoutProvider::Get()->GetTypographyProvider().GetLineHeight(context,
style);
}
} // namespace views::style
| Zhao-PengFei35/chromium_src_4 | ui/views/style/typography.cc | C++ | unknown | 1,563 |
// 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_STYLE_TYPOGRAPHY_H_
#define UI_VIEWS_STYLE_TYPOGRAPHY_H_
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/views/views_export.h"
namespace gfx {
class FontList;
}
namespace views::style {
// Where a piece of text appears in the UI. This influences size and weight, but
// typically not style or color.
enum TextContext {
// Embedders can extend this enum with additional values that are understood
// by the TypographyProvider offered by their ViewsDelegate. Embedders define
// enum values from VIEWS_TEXT_CONTEXT_END. Values named beginning with
// "CONTEXT_" represent the actual TextContexts: the rest are markers.
VIEWS_TEXT_CONTEXT_START = 0,
// Text that appears on a views::Badge. Always 9pt.
CONTEXT_BADGE = VIEWS_TEXT_CONTEXT_START,
// Text that appears on a button control. Usually 12pt. This includes controls
// with button-like behavior, such as Checkbox.
CONTEXT_BUTTON,
// Text that appears on an MD-styled dialog button control. Usually 12pt.
CONTEXT_BUTTON_MD,
// A title for a dialog window. Usually 15pt. Multi-line OK.
CONTEXT_DIALOG_TITLE,
// Text to label a control, usually next to it. "Body 2". Usually 12pt.
CONTEXT_LABEL,
// Text used for body text in dialogs.
CONTEXT_DIALOG_BODY_TEXT,
// Text in a table row.
CONTEXT_TABLE_ROW,
// An editable text field. Usually matches CONTROL_LABEL.
CONTEXT_TEXTFIELD,
// Placeholder text in a text field.
CONTEXT_TEXTFIELD_PLACEHOLDER,
// Text in a menu.
CONTEXT_MENU,
// Text for the menu items that appear in the touch-selection context menu.
CONTEXT_TOUCH_MENU,
// Embedders must start TextContext enum values from this value.
VIEWS_TEXT_CONTEXT_END,
// All TextContext enum values must be below this value.
TEXT_CONTEXT_MAX = 0x1000
};
// How a piece of text should be presented. This influences color and style, but
// typically not size.
enum TextStyle {
// TextStyle enum values must always be greater than any TextContext value.
// This allows the code to verify at runtime that arguments of the two types
// have not been swapped.
VIEWS_TEXT_STYLE_START = TEXT_CONTEXT_MAX,
// Primary text: solid black, normal weight. Converts to DISABLED in some
// contexts (e.g. BUTTON_TEXT, FIELD).
STYLE_PRIMARY = VIEWS_TEXT_STYLE_START,
// Secondary text: Appears near the primary text.
STYLE_SECONDARY,
// "Hint" text, usually a line that gives context to something more important.
STYLE_HINT,
// Style for text that is displayed in a selection.
STYLE_SELECTED,
// Style for text is part of a static highlight.
STYLE_HIGHLIGHTED,
// Style for the default button on a dialog.
STYLE_DIALOG_BUTTON_DEFAULT,
// Style for the tonal button on a dialog.
STYLE_DIALOG_BUTTON_TONAL,
// Disabled "greyed out" text.
STYLE_DISABLED,
// Used to draw attention to a section of body text such as an extension name
// or hostname.
STYLE_EMPHASIZED,
// Emphasized secondary style. Like STYLE_EMPHASIZED but styled to match
// surrounding STYLE_SECONDARY text.
STYLE_EMPHASIZED_SECONDARY,
// Style for invalid text. Can be either primary or solid red color.
STYLE_INVALID,
// The style used for links. Usually a solid shade of blue.
STYLE_LINK,
// Active tab in a tabbed pane.
STYLE_TAB_ACTIVE,
// Embedders must start TextStyle enum values from here.
VIEWS_TEXT_STYLE_END
};
// Helpers to obtain text properties from the TypographyProvider given by the
// current LayoutProvider. `view` is the View requesting the property. `context`
// can be an enum value from TextContext, or a value understood by the
// embedder's TypographyProvider. Similarly, `style` corresponds to TextStyle.
VIEWS_EXPORT ui::ResourceBundle::FontDetails GetFontDetails(int context,
int style);
VIEWS_EXPORT const gfx::FontList& GetFont(int context, int style);
VIEWS_EXPORT int GetLineHeight(int context, int style);
VIEWS_EXPORT ui::ColorId GetColorId(int context, int style);
} // namespace views::style
#endif // UI_VIEWS_STYLE_TYPOGRAPHY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/style/typography.h | C++ | unknown | 4,302 |
// 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/style/typography_provider.h"
#include <string>
#include "build/build_config.h"
#include "ui/base/default_style.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_id.h"
#include "ui/views/style/typography.h"
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif
namespace views {
namespace {
gfx::Font::Weight GetValueBolderThan(gfx::Font::Weight weight) {
switch (weight) {
case gfx::Font::Weight::BOLD:
return gfx::Font::Weight::EXTRA_BOLD;
case gfx::Font::Weight::EXTRA_BOLD:
case gfx::Font::Weight::BLACK:
return gfx::Font::Weight::BLACK;
default:
return gfx::Font::Weight::BOLD;
}
}
ui::ColorId GetDisabledColorId(int context) {
switch (context) {
case style::CONTEXT_BUTTON_MD:
return ui::kColorButtonForegroundDisabled;
case style::CONTEXT_TEXTFIELD:
return ui::kColorTextfieldForegroundDisabled;
case style::CONTEXT_MENU:
case style::CONTEXT_TOUCH_MENU:
return ui::kColorMenuItemForegroundDisabled;
default:
return ui::kColorLabelForegroundDisabled;
}
}
ui::ColorId GetMenuColorId(int style) {
switch (style) {
case style::STYLE_SECONDARY:
return ui::kColorMenuItemForegroundSecondary;
case style::STYLE_SELECTED:
return ui::kColorMenuItemForegroundSelected;
case style::STYLE_HIGHLIGHTED:
return ui::kColorMenuItemForegroundHighlighted;
default:
return ui::kColorMenuItemForeground;
}
}
ui::ColorId GetHintColorId(int context) {
return (context == style::CONTEXT_TEXTFIELD)
? ui::kColorTextfieldForegroundPlaceholder
: ui::kColorLabelForegroundSecondary;
}
} // namespace
ui::ResourceBundle::FontDetails TypographyProvider::GetFontDetails(
int context,
int style) const {
DCHECK(StyleAllowedForContext(context, style))
<< "context: " << context << " style: " << style;
ui::ResourceBundle::FontDetails details;
switch (context) {
case style::CONTEXT_BADGE:
details.size_delta = ui::kBadgeFontSizeDelta;
details.weight = gfx::Font::Weight::BOLD;
break;
case style::CONTEXT_BUTTON_MD:
details.size_delta = features::IsChromeRefresh2023()
? ui::kLabelFontSizeDeltaChromeRefresh2023
: ui::kLabelFontSizeDelta;
details.weight = TypographyProvider::MediumWeightForUI();
break;
case style::CONTEXT_DIALOG_TITLE:
details.size_delta = ui::kTitleFontSizeDelta;
break;
case style::CONTEXT_TOUCH_MENU:
details.size_delta = 2;
break;
default:
details.size_delta = ui::kLabelFontSizeDelta;
break;
}
switch (style) {
case style::STYLE_TAB_ACTIVE:
details.weight = gfx::Font::Weight::BOLD;
break;
case style::STYLE_DIALOG_BUTTON_DEFAULT:
// Only non-MD default buttons should "increase" in boldness.
if (context == style::CONTEXT_BUTTON) {
details.weight =
GetValueBolderThan(ui::ResourceBundle::GetSharedInstance()
.GetFontListForDetails(details)
.GetFontWeight());
}
break;
case style::STYLE_EMPHASIZED:
case style::STYLE_EMPHASIZED_SECONDARY:
details.weight = gfx::Font::Weight::SEMIBOLD;
break;
}
return details;
}
const gfx::FontList& TypographyProvider::GetFont(int context, int style) const {
return ui::ResourceBundle::GetSharedInstance().GetFontListForDetails(
GetFontDetails(context, style));
}
ui::ColorId TypographyProvider::GetColorId(int context, int style) const {
switch (style) {
case style::STYLE_DIALOG_BUTTON_DEFAULT:
return ui::kColorButtonForegroundProminent;
case style::STYLE_DIALOG_BUTTON_TONAL:
return ui::kColorButtonForegroundTonal;
case style::STYLE_DISABLED:
return GetDisabledColorId(context);
case style::STYLE_LINK:
return ui::kColorLinkForeground;
case style::STYLE_HINT:
return GetHintColorId(context);
}
switch (context) {
case style::CONTEXT_BUTTON_MD:
return ui::kColorButtonForeground;
case style::CONTEXT_LABEL:
if (style == style::STYLE_SECONDARY) {
return ui::kColorLabelForegroundSecondary;
}
break;
case style::CONTEXT_DIALOG_BODY_TEXT:
if (style == style::STYLE_PRIMARY || style == style::STYLE_SECONDARY) {
return ui::kColorDialogForeground;
}
break;
case style::CONTEXT_TEXTFIELD:
return ui::kColorTextfieldForeground;
case style::CONTEXT_TEXTFIELD_PLACEHOLDER:
return (style == style::STYLE_INVALID)
? ui::kColorTextfieldForegroundPlaceholderInvalid
: ui::kColorTextfieldForegroundPlaceholder;
case style::CONTEXT_MENU:
case style::CONTEXT_TOUCH_MENU:
return GetMenuColorId(style);
}
return ui::kColorLabelForeground;
}
int TypographyProvider::GetLineHeight(int context, int style) const {
return GetFont(context, style).GetHeight();
}
bool TypographyProvider::StyleAllowedForContext(int context, int style) const {
// TODO(https://crbug.com/1352340): Limit emphasizing text to contexts where
// it's obviously correct. chrome_typography_provider.cc implements this
// correctly, but that does not cover uses outside of //chrome or //ash.
return true;
}
// static
gfx::Font::Weight TypographyProvider::MediumWeightForUI() {
#if BUILDFLAG(IS_MAC)
// System fonts are not user-configurable on Mac, so it's simpler.
return gfx::Font::Weight::MEDIUM;
#else
// NORMAL may already have at least MEDIUM weight. Return NORMAL in that case
// since trying to return MEDIUM would actually make the font lighter-weight
// than the surrounding text. For example, Windows can be configured to use a
// BOLD font for dialog text; deriving MEDIUM from that would replace the BOLD
// attribute with something lighter.
if (ui::ResourceBundle::GetSharedInstance()
.GetFontListForDetails(ui::ResourceBundle::FontDetails())
.GetFontWeight() < gfx::Font::Weight::MEDIUM)
return gfx::Font::Weight::MEDIUM;
return gfx::Font::Weight::NORMAL;
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/style/typography_provider.cc | C++ | unknown | 6,393 |
// 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_STYLE_TYPOGRAPHY_PROVIDER_H_
#define UI_VIEWS_STYLE_TYPOGRAPHY_PROVIDER_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/gfx/font.h"
#include "ui/views/views_export.h"
namespace gfx {
class FontList;
}
namespace views {
// Provides a default provider of fonts to use in toolkit-views UI.
class VIEWS_EXPORT TypographyProvider {
public:
TypographyProvider() = default;
TypographyProvider(const TypographyProvider&) = delete;
TypographyProvider& operator=(const TypographyProvider&) = delete;
virtual ~TypographyProvider() = default;
// Gets the FontDetails for the given `context` and `style`.
virtual ui::ResourceBundle::FontDetails GetFontDetails(int context,
int style) const;
// Convenience wrapper that gets a FontList for `context` and `style`.
const gfx::FontList& GetFont(int context, int style) const;
// Returns the color id for the given `context` and `style`.
virtual ui::ColorId GetColorId(int context, int style) const;
// Gets the line spacing. By default this is the font height.
virtual int GetLineHeight(int context, int style) const;
// Returns whether the given style can be used in the given context.
virtual bool StyleAllowedForContext(int context, int style) const;
// Returns the weight that will result in the ResourceBundle returning an
// appropriate "medium" weight for UI. This caters for systems that are known
// to be unable to provide a system font with weight other than NORMAL or BOLD
// and for user configurations where the NORMAL font is already BOLD. In both
// of these cases, NORMAL is returned instead.
static gfx::Font::Weight MediumWeightForUI();
};
} // namespace views
#endif // UI_VIEWS_STYLE_TYPOGRAPHY_PROVIDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/style/typography_provider.h | C++ | unknown | 2,033 |
include_rules = [
"+content/public/test",
]
specific_include_rules = {
"views_test_base\.cc": [
"+mojo/core/embedder",
"+ui/gl",
],
"view_skia_gold_pixel_diff.cc" : [
"+ui/snapshot",
],
}
| Zhao-PengFei35/chromium_src_4 | ui/views/test/DEPS | Python | unknown | 211 |
// 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 <utility>
#include "ui/views/test/ax_event_counter.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/views/view.h"
namespace views::test {
AXEventCounter::AXEventCounter(views::AXEventManager* event_manager) {
tree_observation_.Observe(event_manager);
}
AXEventCounter::~AXEventCounter() = default;
void AXEventCounter::OnViewEvent(views::View* view,
ax::mojom::Event event_type) {
++event_counts_[event_type];
++event_counts_for_view_[std::make_pair(event_type, view)];
// TODO(accessibility): There are a non-trivial number of events, mostly
// kChildrenChanged, being fired during the creation process. When this
// occurs calling GetAccessibleNodeData() on the related View can lead
// to null dereference errors and at least one pure-virtual-function call.
// We should either fix those errors or stop firing the events. For now,
// require the presence of a Widget to count events by role.
if (view->GetWidget()) {
ui::AXNodeData node_data;
view->GetAccessibleNodeData(&node_data);
++event_counts_for_role_[std::make_pair(event_type, node_data.role)];
}
if (run_loop_ && event_type == wait_for_event_type_) {
wait_for_event_type_ = ax::mojom::Event::kNone;
run_loop_->Quit();
}
}
int AXEventCounter::GetCount(ax::mojom::Event event_type) {
return event_counts_[event_type];
}
int AXEventCounter::GetCount(ax::mojom::Event event_type,
ax::mojom::Role role) {
return event_counts_for_role_[std::make_pair(event_type, role)];
}
int AXEventCounter::GetCount(ax::mojom::Event event_type, views::View* view) {
return event_counts_for_view_[std::make_pair(event_type, view)];
}
void AXEventCounter::ResetAllCounts() {
event_counts_.clear();
event_counts_for_role_.clear();
event_counts_for_view_.clear();
}
void AXEventCounter::WaitForEvent(ax::mojom::Event event_type) {
wait_for_event_type_ = event_type;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop_->Run();
run_loop_ = nullptr;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/ax_event_counter.cc | C++ | unknown | 2,229 |
// 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_AX_EVENT_COUNTER_H_
#define UI_VIEWS_TEST_AX_EVENT_COUNTER_H_
#include <utility>
#include "base/containers/flat_map.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/ax_event_observer.h"
namespace views::test {
// AXEventCounter provides a convenient way to count events registered by the
// AXEventManager by their event type, and wait for events of a specific type.
class AXEventCounter : public views::AXEventObserver {
public:
explicit AXEventCounter(views::AXEventManager* event_manager);
~AXEventCounter() override;
AXEventCounter(const AXEventCounter&) = delete;
AXEventCounter& operator=(const AXEventCounter&) = delete;
// Returns the number of events of a certain type registered since the
// creation of this AXEventManager object and prior to the count being
// manually reset.
int GetCount(ax::mojom::Event event_type);
// Returns the number of events of a certain type on a certain role registered
// since the creation of this AXEventManager object and prior to the count
// being manually reset.
int GetCount(ax::mojom::Event event_type, ax::mojom::Role role);
// Returns the number of events of a certain type on a specific view since the
// creation of this AXEventManager object and prior to the count being
// manually reset.
int GetCount(ax::mojom::Event event_type, views::View* view);
// Sets all counters to 0.
void ResetAllCounts();
// Blocks until an event of the specified type is received.
void WaitForEvent(ax::mojom::Event event_type);
// views::AXEventObserver
void OnViewEvent(views::View* view, ax::mojom::Event event_type) override;
private:
base::flat_map<ax::mojom::Event, int> event_counts_;
base::flat_map<std::pair<ax::mojom::Event, ax::mojom::Role>, int>
event_counts_for_role_;
base::flat_map<std::pair<ax::mojom::Event, views::View*>, int>
event_counts_for_view_;
ax::mojom::Event wait_for_event_type_ = ax::mojom::Event::kNone;
raw_ptr<base::RunLoop> run_loop_ = nullptr;
base::ScopedObservation<views::AXEventManager, views::AXEventObserver>
tree_observation_{this};
};
} // namespace views::test
#endif // UI_VIEWS_TEST_AX_EVENT_COUNTER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/ax_event_counter.h | C++ | unknown | 2,524 |
// 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/test/button_test_api.h"
#include "ui/views/controls/button/button.h"
namespace views::test {
void ButtonTestApi::NotifyClick(const ui::Event& event) {
button_->NotifyClick(event);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/button_test_api.cc | C++ | unknown | 379 |
// 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_BUTTON_TEST_API_H_
#define UI_VIEWS_TEST_BUTTON_TEST_API_H_
#include "base/memory/raw_ptr.h"
namespace ui {
class Event;
}
namespace views {
class Button;
namespace test {
// A wrapper of Button to access private members for testing.
class ButtonTestApi {
public:
explicit ButtonTestApi(Button* button) : button_(button) {}
ButtonTestApi(const ButtonTestApi&) = delete;
ButtonTestApi& operator=(const ButtonTestApi&) = delete;
void NotifyClick(const ui::Event& event);
private:
raw_ptr<Button, DanglingUntriaged> button_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_BUTTON_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/button_test_api.h | C++ | unknown | 801 |
// 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/capture_tracking_view.h"
namespace views::test {
CaptureTrackingView::CaptureTrackingView() = default;
CaptureTrackingView::~CaptureTrackingView() = default;
bool CaptureTrackingView::OnMousePressed(const ui::MouseEvent& event) {
got_press_ = true;
return true;
}
void CaptureTrackingView::OnMouseCaptureLost() {
got_capture_lost_ = true;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/capture_tracking_view.cc | C++ | unknown | 549 |
// 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_CAPTURE_TRACKING_VIEW_H_
#define UI_VIEWS_TEST_CAPTURE_TRACKING_VIEW_H_
#include "ui/views/view.h"
namespace views::test {
// Used to track OnMousePressed() and OnMouseCaptureLost().
class CaptureTrackingView : public views::View {
public:
CaptureTrackingView();
CaptureTrackingView(const CaptureTrackingView&) = delete;
CaptureTrackingView& operator=(const CaptureTrackingView&) = delete;
~CaptureTrackingView() override;
// Returns true if OnMousePressed() has been invoked.
bool got_press() const { return got_press_; }
// Returns true if OnMouseCaptureLost() has been invoked.
bool got_capture_lost() const { return got_capture_lost_; }
void reset() { got_press_ = got_capture_lost_ = false; }
// Overridden from views::View
bool OnMousePressed(const ui::MouseEvent& event) override;
void OnMouseCaptureLost() override;
private:
// See description above getters.
bool got_press_ = false;
bool got_capture_lost_ = false;
};
} // namespace views::test
#endif // UI_VIEWS_TEST_CAPTURE_TRACKING_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/capture_tracking_view.h | C++ | unknown | 1,215 |
// 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/test/combobox_test_api.h"
#include <stdint.h>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/base/models/menu_model.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/menu_runner_handler.h"
#include "ui/views/test/menu_runner_test_api.h"
namespace views::test {
namespace {
// An dummy implementation of MenuRunnerHandler to check if the dropdown menu is
// shown or not.
class TestMenuRunnerHandler : public MenuRunnerHandler {
public:
explicit TestMenuRunnerHandler(int* show_counter)
: show_counter_(show_counter) {}
TestMenuRunnerHandler(const TestMenuRunnerHandler&) = delete;
TestMenuRunnerHandler& operator=(const TestMenuRunnerHandler&) = delete;
void RunMenuAt(Widget* parent,
MenuButtonController* button_controller,
const gfx::Rect& bounds,
MenuAnchorPosition anchor,
ui::MenuSourceType source_type,
int32_t types) override {
*show_counter_ += 1;
}
private:
raw_ptr<int> show_counter_;
};
} // namespace
void ComboboxTestApi::PerformActionAt(int index) {
menu_model()->ActivatedAt(index);
}
void ComboboxTestApi::InstallTestMenuRunner(int* menu_show_count) {
combobox_->menu_runner_ =
std::make_unique<MenuRunner>(menu_model(), MenuRunner::COMBOBOX);
test::MenuRunnerTestAPI test_api(combobox_->menu_runner_.get());
test_api.SetMenuRunnerHandler(
std::make_unique<TestMenuRunnerHandler>(menu_show_count));
}
gfx::Size ComboboxTestApi::content_size() {
return combobox_->content_size_;
}
ui::MenuModel* ComboboxTestApi::menu_model() {
return combobox_->menu_model_.get();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/combobox_test_api.cc | C++ | unknown | 1,922 |
// 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_TEST_COMBOBOX_TEST_API_H_
#define UI_VIEWS_TEST_COMBOBOX_TEST_API_H_
#include "base/memory/raw_ptr.h"
namespace gfx {
class Size;
}
namespace ui {
class MenuModel;
}
namespace views {
class Combobox;
namespace test {
// A wrapper of Combobox to access private members for testing.
class ComboboxTestApi {
public:
explicit ComboboxTestApi(Combobox* combobox) : combobox_(combobox) {}
ComboboxTestApi(const ComboboxTestApi&) = delete;
ComboboxTestApi& operator=(const ComboboxTestApi&) = delete;
// Activates the Combobox menu item at |index|, as if selected by the user.
void PerformActionAt(int index);
// Installs a testing views::MenuRunnerHandler to test when a menu should be
// shown. The test runner will immediately dismiss itself and increment the
// given |menu_show_count| by one.
void InstallTestMenuRunner(int* menu_show_count);
// Accessors for private data members of Combobox.
gfx::Size content_size();
ui::MenuModel* menu_model();
private:
raw_ptr<Combobox> combobox_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_COMBOBOX_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/combobox_test_api.h | C++ | unknown | 1,280 |
// 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_DESKTOP_TEST_VIEWS_DELEGATE_H_
#define UI_VIEWS_TEST_DESKTOP_TEST_VIEWS_DELEGATE_H_
#include "ui/views/test/test_views_delegate.h"
namespace views {
// Most aura test code is written assuming a single RootWindow view, however,
// at higher levels like content_browsertests and
// views_examples_with_content_exe, we must use the Desktop variants.
class DesktopTestViewsDelegate : public TestViewsDelegate {
public:
DesktopTestViewsDelegate();
DesktopTestViewsDelegate(const DesktopTestViewsDelegate&) = delete;
DesktopTestViewsDelegate& operator=(const DesktopTestViewsDelegate&) = delete;
~DesktopTestViewsDelegate() override;
// Overridden from ViewsDelegate:
void OnBeforeWidgetInit(Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) override;
};
} // namespace views
#endif // UI_VIEWS_TEST_DESKTOP_TEST_VIEWS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/desktop_test_views_delegate.h | C++ | unknown | 1,060 |
// 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/desktop_test_views_delegate.h"
#include "build/build_config.h"
#include "ui/views/buildflags.h"
#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
namespace views {
DesktopTestViewsDelegate::DesktopTestViewsDelegate() = default;
DesktopTestViewsDelegate::~DesktopTestViewsDelegate() = default;
void DesktopTestViewsDelegate::OnBeforeWidgetInit(
Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) {
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// If we already have a native_widget, we don't have to try to come
// up with one.
if (params->native_widget)
return;
if (params->parent && params->type != views::Widget::InitParams::TYPE_MENU &&
params->type != views::Widget::InitParams::TYPE_TOOLTIP) {
params->native_widget = new views::NativeWidgetAura(delegate);
} else {
params->native_widget = new views::DesktopNativeWidgetAura(delegate);
}
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/desktop_test_views_delegate_aura.cc | C++ | unknown | 1,205 |
// 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/desktop_test_views_delegate.h"
#include "ui/views/widget/native_widget_mac.h"
namespace views {
DesktopTestViewsDelegate::DesktopTestViewsDelegate() = default;
DesktopTestViewsDelegate::~DesktopTestViewsDelegate() = default;
void DesktopTestViewsDelegate::OnBeforeWidgetInit(
Widget::InitParams* params,
internal::NativeWidgetDelegate* delegate) {
// If we already have a native_widget, we don't have to try to come
// up with one.
if (params->native_widget)
return;
if (params->parent && params->type != views::Widget::InitParams::TYPE_MENU) {
params->native_widget = new NativeWidgetMac(delegate);
} else if (!params->parent && !params->context) {
NOTIMPLEMENTED();
// TODO(tapted): Implement DesktopNativeWidgetAura.
params->native_widget = new NativeWidgetMac(delegate);
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/desktop_test_views_delegate_mac.mm | Objective-C++ | unknown | 1,016 |
// 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/desktop_window_tree_host_win_test_api.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
#include "ui/views/win/hwnd_message_handler.h"
namespace views {
namespace test {
DesktopWindowTreeHostWinTestApi::DesktopWindowTreeHostWinTestApi(
DesktopWindowTreeHostWin* host)
: host_(host) {}
void DesktopWindowTreeHostWinTestApi::EnsureAXSystemCaretCreated() {
host_->message_handler_->OnCaretBoundsChanged(nullptr);
}
ui::AXSystemCaretWin* DesktopWindowTreeHostWinTestApi::GetAXSystemCaret() {
return host_->message_handler_->ax_system_caret_.get();
}
gfx::NativeViewAccessible
DesktopWindowTreeHostWinTestApi::GetNativeViewAccessible() {
return host_->GetNativeViewAccessible();
}
HWNDMessageHandler* DesktopWindowTreeHostWinTestApi::GetHwndMessageHandler() {
return host_->message_handler_.get();
}
void DesktopWindowTreeHostWinTestApi::SetMockCursorPositionForTesting(
const gfx::Point& position) {
GetHwndMessageHandler()->mock_cursor_position_ = position;
}
LRESULT DesktopWindowTreeHostWinTestApi::SimulatePenEventForTesting(
UINT message,
UINT32 pointer_id,
POINTER_PEN_INFO pointer_pen_info) {
return host_->message_handler_->HandlePointerEventTypePen(message, pointer_id,
pointer_pen_info);
}
} // namespace test
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/desktop_window_tree_host_win_test_api.cc | C++ | unknown | 1,537 |
// 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_DESKTOP_WINDOW_TREE_HOST_WIN_TEST_API_H_
#define UI_VIEWS_TEST_DESKTOP_WINDOW_TREE_HOST_WIN_TEST_API_H_
#include <windows.h>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/native_widget_types.h"
namespace ui {
class AXSystemCaretWin;
}
namespace views {
class DesktopWindowTreeHostWin;
class HWNDMessageHandler;
namespace test {
// A wrapper of DesktopWindowTreeHostWin to access private members for testing.
class DesktopWindowTreeHostWinTestApi {
public:
explicit DesktopWindowTreeHostWinTestApi(DesktopWindowTreeHostWin* host);
DesktopWindowTreeHostWinTestApi(const DesktopWindowTreeHostWinTestApi&) =
delete;
DesktopWindowTreeHostWinTestApi& operator=(
const DesktopWindowTreeHostWinTestApi&) = delete;
void EnsureAXSystemCaretCreated();
ui::AXSystemCaretWin* GetAXSystemCaret();
gfx::NativeViewAccessible GetNativeViewAccessible();
HWNDMessageHandler* GetHwndMessageHandler();
LRESULT SimulatePenEventForTesting(UINT message,
UINT32 pointer_id,
POINTER_PEN_INFO pointer_pen_info);
void SetMockCursorPositionForTesting(const gfx::Point& position);
private:
raw_ptr<DesktopWindowTreeHostWin> host_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_DESKTOP_WINDOW_TREE_HOST_WIN_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/desktop_window_tree_host_win_test_api.h | C++ | unknown | 1,541 |
// 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/dialog_test.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views::test {
namespace {
DialogDelegate* DialogDelegateFor(Widget* widget) {
auto* delegate = widget->widget_delegate()->AsDialogDelegate();
return delegate;
}
} // namespace
void AcceptDialog(Widget* widget) {
WidgetDestroyedWaiter waiter(widget);
DialogDelegateFor(widget)->AcceptDialog();
waiter.Wait();
}
void CancelDialog(Widget* widget) {
WidgetDestroyedWaiter waiter(widget);
DialogDelegateFor(widget)->CancelDialog();
waiter.Wait();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/dialog_test.cc | C++ | unknown | 809 |
// 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_DIALOG_TEST_H_
#define UI_VIEWS_TEST_DIALOG_TEST_H_
namespace views {
class Widget;
namespace test {
void AcceptDialog(Widget* widget);
void CancelDialog(Widget* widget);
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_DIALOG_TEST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/dialog_test.h | C++ | unknown | 426 |
// 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_EVENT_GENERATOR_DELEGATE_MAC_H_
#define UI_VIEWS_TEST_EVENT_GENERATOR_DELEGATE_MAC_H_
#include <memory>
#include "ui/gfx/native_widget_types.h"
namespace ui::test {
class EventGenerator;
class EventGeneratorDelegate;
} // namespace ui::test
namespace views::test {
std::unique_ptr<ui::test::EventGeneratorDelegate>
CreateEventGeneratorDelegateMac(ui::test::EventGenerator* owner,
gfx::NativeWindow root_window,
gfx::NativeWindow target_window);
} // namespace views::test
#endif // UI_VIEWS_TEST_EVENT_GENERATOR_DELEGATE_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/event_generator_delegate_mac.h | C++ | unknown | 768 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#import <Cocoa/Cocoa.h>
#include <stddef.h>
#import "base/mac/scoped_nsobject.h"
#import "base/mac/scoped_objc_class_swizzler.h"
#include "base/memory/singleton.h"
#include "base/time/time.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/event_dispatcher.h"
#include "ui/events/event_processor.h"
#include "ui/events/event_target.h"
#include "ui/events/event_target_iterator.h"
#include "ui/events/event_targeter.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/mac/coordinate_conversion.h"
namespace {
// Set (and always cleared) in EmulateSendEvent() to provide an answer for
// [NSApp currentEvent].
NSEvent* g_current_event = nil;
} // namespace
@interface NSEventDonor : NSObject
@end
@interface NSApplicationDonor : NSObject
@end
namespace {
// Return the current owner of the EventGeneratorDelegate. May be null.
ui::test::EventGenerator* GetActiveGenerator();
NSPoint ConvertRootPointToTarget(NSWindow* target,
const gfx::Point& point_in_root) {
DCHECK(GetActiveGenerator());
gfx::Point point = point_in_root;
point -= gfx::ScreenRectFromNSRect([target frame]).OffsetFromOrigin();
return NSMakePoint(point.x(), NSHeight([target frame]) - point.y());
}
// Inverse of ui::EventFlagsFromModifiers().
NSUInteger EventFlagsToModifiers(int flags) {
NSUInteger modifiers = 0;
modifiers |= (flags & ui::EF_SHIFT_DOWN) ? NSEventModifierFlagShift : 0;
modifiers |= (flags & ui::EF_CONTROL_DOWN) ? NSEventModifierFlagControl : 0;
modifiers |= (flags & ui::EF_ALT_DOWN) ? NSEventModifierFlagOption : 0;
modifiers |= (flags & ui::EF_COMMAND_DOWN) ? NSEventModifierFlagCommand : 0;
modifiers |= (flags & ui::EF_CAPS_LOCK_ON) ? NSEventModifierFlagCapsLock : 0;
// ui::EF_*_MOUSE_BUTTON not handled here.
// NSEventModifierFlagFunction, NSEventModifierFlagNumericPad and
// NSHelpKeyMask not mapped.
return modifiers;
}
// Picks the corresponding mouse event type for the buttons set in |flags|.
NSEventType PickMouseEventType(int flags,
NSEventType left,
NSEventType right,
NSEventType other) {
if (flags & ui::EF_LEFT_MOUSE_BUTTON)
return left;
if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
return right;
return other;
}
// Inverse of ui::EventTypeFromNative(). If non-null |modifiers| will be set
// using the inverse of ui::EventFlagsFromNSEventWithModifiers().
NSEventType EventTypeToNative(ui::EventType ui_event_type,
int flags,
NSUInteger* modifiers) {
if (modifiers)
*modifiers = EventFlagsToModifiers(flags);
switch (ui_event_type) {
case ui::ET_KEY_PRESSED:
return NSEventTypeKeyDown;
case ui::ET_KEY_RELEASED:
return NSEventTypeKeyUp;
case ui::ET_MOUSE_PRESSED:
return PickMouseEventType(flags, NSEventTypeLeftMouseDown,
NSEventTypeRightMouseDown,
NSEventTypeOtherMouseDown);
case ui::ET_MOUSE_RELEASED:
return PickMouseEventType(flags, NSEventTypeLeftMouseUp,
NSEventTypeRightMouseUp,
NSEventTypeOtherMouseUp);
case ui::ET_MOUSE_DRAGGED:
return PickMouseEventType(flags, NSEventTypeLeftMouseDragged,
NSEventTypeRightMouseDragged,
NSEventTypeOtherMouseDragged);
case ui::ET_MOUSE_MOVED:
return NSEventTypeMouseMoved;
case ui::ET_MOUSEWHEEL:
return NSEventTypeScrollWheel;
case ui::ET_MOUSE_ENTERED:
return NSEventTypeMouseEntered;
case ui::ET_MOUSE_EXITED:
return NSEventTypeMouseExited;
case ui::ET_SCROLL_FLING_START:
return NSEventTypeSwipe;
default:
NOTREACHED_NORETURN();
}
}
// Emulate the dispatching that would be performed by -[NSWindow sendEvent:].
// sendEvent is a black box which (among other things) will try to peek at the
// event queue and can block indefinitely.
void EmulateSendEvent(NSWindow* window, NSEvent* event) {
base::AutoReset<NSEvent*> reset(&g_current_event, event);
NSResponder* responder = [window firstResponder];
switch ([event type]) {
case NSEventTypeKeyDown:
[responder keyDown:event];
return;
case NSEventTypeKeyUp:
[responder keyUp:event];
return;
default:
break;
}
// For mouse events, NSWindow will use -[NSView hitTest:] for the initial
// mouseDown, and then keep track of the NSView returned. The toolkit-views
// RootView does this too. So, for tests, assume tracking will be done there,
// and the NSWindow's contentView is wrapping a views::internal::RootView.
responder = [window contentView];
switch ([event type]) {
case NSEventTypeLeftMouseDown:
[responder mouseDown:event];
break;
case NSEventTypeRightMouseDown:
[responder rightMouseDown:event];
break;
case NSEventTypeOtherMouseDown:
[responder otherMouseDown:event];
break;
case NSEventTypeLeftMouseUp:
[responder mouseUp:event];
break;
case NSEventTypeRightMouseUp:
[responder rightMouseUp:event];
break;
case NSEventTypeOtherMouseUp:
[responder otherMouseUp:event];
break;
case NSEventTypeLeftMouseDragged:
[responder mouseDragged:event];
break;
case NSEventTypeRightMouseDragged:
[responder rightMouseDragged:event];
break;
case NSEventTypeOtherMouseDragged:
[responder otherMouseDragged:event];
break;
case NSEventTypeMouseMoved:
// Assumes [NSWindow acceptsMouseMovedEvents] would return YES, and that
// NSTrackingAreas have been appropriately installed on |responder|.
[responder mouseMoved:event];
break;
case NSEventTypeScrollWheel:
[responder scrollWheel:event];
break;
case NSEventTypeMouseEntered:
case NSEventTypeMouseExited:
// With the assumptions in NSEventTypeMouseMoved, it doesn't make sense
// for the generator to handle entered/exited separately. It's the
// responsibility of views::internal::RootView to convert the moved events
// into entered and exited events for the individual views.
NOTREACHED_NORETURN();
case NSEventTypeSwipe:
// NSEventTypeSwipe events can't be generated using public interfaces on
// NSEvent, so this will need to be handled at a higher level.
NOTREACHED_NORETURN();
default:
NOTREACHED_NORETURN();
}
}
NSEvent* CreateMouseEventInWindow(NSWindow* window,
ui::EventType event_type,
const gfx::Point& point_in_root,
const base::TimeTicks time_stamp,
int flags) {
NSUInteger click_count = 0;
if (event_type == ui::ET_MOUSE_PRESSED ||
event_type == ui::ET_MOUSE_RELEASED) {
if (flags & ui::EF_IS_TRIPLE_CLICK)
click_count = 3;
else if (flags & ui::EF_IS_DOUBLE_CLICK)
click_count = 2;
else
click_count = 1;
}
NSPoint point = ConvertRootPointToTarget(window, point_in_root);
NSUInteger modifiers = 0;
NSEventType type = EventTypeToNative(event_type, flags, &modifiers);
return [NSEvent mouseEventWithType:type
location:point
modifierFlags:modifiers
timestamp:ui::EventTimeStampToSeconds(time_stamp)
windowNumber:[window windowNumber]
context:nil
eventNumber:0
clickCount:click_count
pressure:1.0];
}
NSEvent* CreateMouseWheelEventInWindow(NSWindow* window,
const ui::MouseEvent* mouse_event) {
DCHECK_EQ(mouse_event->type(), ui::ET_MOUSEWHEEL);
const ui::MouseWheelEvent* mouse_wheel_event =
mouse_event->AsMouseWheelEvent();
return cocoa_test_event_utils::TestScrollEvent(
ConvertRootPointToTarget(window, mouse_wheel_event->location()), window,
mouse_wheel_event->x_offset(), mouse_wheel_event->y_offset(), false,
NSEventPhaseNone, NSEventPhaseNone);
}
// Implementation of ui::test::EventGeneratorDelegate for Mac. Everything
// defined inline is just a stub. Interesting overrides are defined below the
// class.
class EventGeneratorDelegateMac : public ui::EventTarget,
public ui::EventSource,
public ui::EventHandler,
public ui::EventProcessor,
public ui::EventTargeter,
public ui::test::EventGeneratorDelegate {
public:
EventGeneratorDelegateMac(ui::test::EventGenerator* owner,
gfx::NativeWindow root_window,
gfx::NativeWindow target_window);
EventGeneratorDelegateMac(const EventGeneratorDelegateMac&) = delete;
EventGeneratorDelegateMac& operator=(const EventGeneratorDelegateMac&) =
delete;
~EventGeneratorDelegateMac() override;
static EventGeneratorDelegateMac* instance() { return instance_; }
NSEvent* OriginalCurrentEvent(id receiver, SEL selector) {
return swizzle_current_event_->InvokeOriginal<NSEvent*>(receiver, selector);
}
NSWindow* target_window() { return target_window_.get(); }
ui::test::EventGenerator* owner() { return owner_; }
// Overridden from ui::EventTarget:
bool CanAcceptEvent(const ui::Event& event) override { return true; }
ui::EventTarget* GetParentTarget() override { return nullptr; }
std::unique_ptr<ui::EventTargetIterator> GetChildIterator() const override;
ui::EventTargeter* GetEventTargeter() override { return this; }
// Overridden from ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
void OnKeyEvent(ui::KeyEvent* event) override;
void OnTouchEvent(ui::TouchEvent* event) override;
void OnScrollEvent(ui::ScrollEvent* event) override;
// Overridden from ui::EventSource:
ui::EventSink* GetEventSink() override { return this; }
// Overridden from ui::EventProcessor:
ui::EventTarget* GetRootForEvent(ui::Event* event) override { return this; }
ui::EventTargeter* GetDefaultEventTargeter() override {
return this->GetEventTargeter();
}
// Overridden from ui::EventDispatcherDelegate (via ui::EventProcessor):
bool CanDispatchToTarget(EventTarget* target) override { return true; }
// Overridden from ui::EventTargeter:
ui::EventTarget* FindTargetForEvent(ui::EventTarget* root,
ui::Event* event) override {
return root;
}
ui::EventTarget* FindNextBestTarget(ui::EventTarget* previous_target,
ui::Event* event) override {
return nullptr;
}
// Overridden from ui::test::EventGeneratorDelegate:
ui::EventTarget* GetTargetAt(const gfx::Point& location) override {
return this;
}
void SetTargetWindow(gfx::NativeWindow target_window) override {
// Retain the NSWindow (note it can be nil). This matches Cocoa's tendency
// to have autoreleased objects, or objects still in the event queue, that
// reference the NSWindow.
target_window_.reset([target_window.GetNativeNSWindow() retain]);
}
ui::EventSource* GetEventSource(ui::EventTarget* target) override {
return this;
}
gfx::Point CenterOfTarget(const ui::EventTarget* target) const override;
gfx::Point CenterOfWindow(gfx::NativeWindow window) const override;
void ConvertPointFromTarget(const ui::EventTarget* target,
gfx::Point* point) const override {}
void ConvertPointToTarget(const ui::EventTarget* target,
gfx::Point* point) const override {}
void ConvertPointFromWindow(gfx::NativeWindow window,
gfx::Point* point) const override {}
void ConvertPointFromHost(const ui::EventTarget* hosted_target,
gfx::Point* point) const override {}
protected:
// Overridden from ui::EventDispatcherDelegate (via ui::EventProcessor)
[[nodiscard]] ui::EventDispatchDetails PreDispatchEvent(
ui::EventTarget* target,
ui::Event* event) override;
private:
static EventGeneratorDelegateMac* instance_;
raw_ptr<ui::test::EventGenerator> owner_;
base::scoped_nsobject<NSWindow> target_window_;
std::unique_ptr<base::mac::ScopedObjCClassSwizzler> swizzle_pressed_;
std::unique_ptr<base::mac::ScopedObjCClassSwizzler> swizzle_location_;
std::unique_ptr<base::mac::ScopedObjCClassSwizzler> swizzle_current_event_;
base::scoped_nsobject<NSMenu> fake_menu_;
// Mac always sends trackpad scroll events between begin/end phase event
// markers. If |in_trackpad_scroll| is false, a phase begin event is sent
// before any trackpad scroll update.
bool in_trackpad_scroll = false;
// Timestamp on the last scroll update, used to simulate scroll momentum.
base::TimeTicks last_scroll_timestamp_;
};
// static
EventGeneratorDelegateMac* EventGeneratorDelegateMac::instance_ = nullptr;
EventGeneratorDelegateMac::EventGeneratorDelegateMac(
ui::test::EventGenerator* owner,
gfx::NativeWindow root_window,
gfx::NativeWindow target_window)
: owner_(owner) {
DCHECK(!instance_);
instance_ = this;
SetTargetHandler(this);
// Install a fake "edit" menu. This is normally provided by Chrome's
// MainMenu.xib, but src/ui shouldn't depend on that.
fake_menu_.reset([[NSMenu alloc] initWithTitle:@"Edit"]);
struct {
NSString* title;
SEL action;
NSString* key_equivalent;
} fake_menu_item[] = {
{@"Undo", @selector(undo:), @"z"},
{@"Redo", @selector(redo:), @"Z"},
{@"Copy", @selector(copy:), @"c"},
{@"Cut", @selector(cut:), @"x"},
{@"Paste", @selector(paste:), @"v"},
{@"Select All", @selector(selectAll:), @"a"},
};
for (size_t i = 0; i < std::size(fake_menu_item); ++i) {
[fake_menu_ insertItemWithTitle:fake_menu_item[i].title
action:fake_menu_item[i].action
keyEquivalent:fake_menu_item[i].key_equivalent
atIndex:i];
}
// Mac doesn't use a |root_window|. Assume that if a single-argument
// constructor was used, it should be the actual |target_window|.
// TODO(tluk) fix use of the API so this doesn't have to be assumed.
// (crbug.com/1071628)
if (!target_window)
target_window = root_window;
swizzle_pressed_.reset();
swizzle_location_.reset();
swizzle_current_event_.reset();
SetTargetWindow(target_window);
// Normally, edit menu items have a `nil` target. This results in -[NSMenu
// performKeyEquivalent:] relying on -[NSApplication targetForAction:to:from:]
// to find a target starting at the first responder of the key window. Since
// non-interactive tests have no key window, that won't work. So set (or
// clear) the target explicitly on all menu items.
[[fake_menu_ itemArray]
makeObjectsPerformSelector:@selector(setTarget:)
withObject:[target_window.GetNativeNSWindow()
firstResponder]];
if (owner_) {
swizzle_pressed_ = std::make_unique<base::mac::ScopedObjCClassSwizzler>(
[NSEvent class], [NSEventDonor class], @selector(pressedMouseButtons));
swizzle_location_ = std::make_unique<base::mac::ScopedObjCClassSwizzler>(
[NSEvent class], [NSEventDonor class], @selector(mouseLocation));
swizzle_current_event_ =
std::make_unique<base::mac::ScopedObjCClassSwizzler>(
[NSApplication class], [NSApplicationDonor class],
@selector(currentEvent));
}
}
EventGeneratorDelegateMac::~EventGeneratorDelegateMac() {
DCHECK_EQ(instance_, this);
instance_ = nullptr;
}
std::unique_ptr<ui::EventTargetIterator>
EventGeneratorDelegateMac::GetChildIterator() const {
// Return nullptr to dispatch all events to the result of GetRootTarget().
return nullptr;
}
void EventGeneratorDelegateMac::OnMouseEvent(ui::MouseEvent* event) {
NSEvent* ns_event =
event->type() == ui::ET_MOUSEWHEEL
? CreateMouseWheelEventInWindow(target_window_, event)
: CreateMouseEventInWindow(target_window_, event->type(),
event->location(), event->time_stamp(),
event->flags());
using Target = ui::test::EventGenerator::Target;
switch (owner_->target()) {
case Target::APPLICATION:
[NSApp sendEvent:ns_event];
break;
case Target::WINDOW:
[target_window_ sendEvent:ns_event];
break;
case Target::WIDGET:
EmulateSendEvent(target_window_, ns_event);
break;
}
}
void EventGeneratorDelegateMac::OnKeyEvent(ui::KeyEvent* event) {
NSUInteger modifiers = EventFlagsToModifiers(event->flags());
NSEvent* ns_event = cocoa_test_event_utils::SynthesizeKeyEvent(
target_window_, event->type() == ui::ET_KEY_PRESSED, event->key_code(),
modifiers, event->is_char() ? event->GetDomKey() : ui::DomKey::NONE);
using Target = ui::test::EventGenerator::Target;
switch (owner_->target()) {
case Target::APPLICATION:
[NSApp sendEvent:ns_event];
break;
case Target::WINDOW:
// -[NSApp sendEvent:] sends -performKeyEquivalent: if Command or Control
// modifiers are pressed. Emulate that behavior.
if ([ns_event type] == NSEventTypeKeyDown &&
([ns_event modifierFlags] &
(NSEventModifierFlagControl | NSEventModifierFlagCommand)) &&
[target_window_ performKeyEquivalent:ns_event])
break; // Handled by performKeyEquivalent:.
[target_window_ sendEvent:ns_event];
break;
case Target::WIDGET:
if ([fake_menu_ performKeyEquivalent:ns_event])
return;
EmulateSendEvent(target_window_, ns_event);
break;
}
}
void EventGeneratorDelegateMac::OnTouchEvent(ui::TouchEvent* event) {
NOTREACHED_NORETURN() << "Touchscreen events not supported on Chrome Mac.";
}
void EventGeneratorDelegateMac::OnScrollEvent(ui::ScrollEvent* event) {
// Ignore FLING_CANCEL. Cocoa provides a continuous stream of events during a
// fling. For now, this method simulates a momentum stream using a single
// update with a momentum phase (plus begin/end phase events), triggered when
// the EventGenerator requests a FLING_START.
if (event->type() == ui::ET_SCROLL_FLING_CANCEL)
return;
NSPoint location =
ConvertRootPointToTarget(target_window_, event->location());
// MAY_BEGIN/END comes from the EventGenerator for trackpad rests.
if (event->momentum_phase() == ui::EventMomentumPhase::MAY_BEGIN ||
event->momentum_phase() == ui::EventMomentumPhase::END) {
DCHECK_EQ(0, event->x_offset());
DCHECK_EQ(0, event->y_offset());
NSEventPhase phase =
event->momentum_phase() == ui::EventMomentumPhase::MAY_BEGIN
? NSEventPhaseMayBegin
: NSEventPhaseCancelled;
NSEvent* rest = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, 0, 0, true, phase, NSEventPhaseNone);
EmulateSendEvent(target_window_, rest);
// Allow the next ScrollSequence to skip the "begin".
in_trackpad_scroll = phase == NSEventPhaseMayBegin;
return;
}
NSEventPhase event_phase = NSEventPhaseBegan;
NSEventPhase momentum_phase = NSEventPhaseNone;
// Treat FLING_START as the beginning of a momentum phase.
if (event->type() == ui::ET_SCROLL_FLING_START) {
DCHECK(in_trackpad_scroll);
// First end the non-momentum phase.
NSEvent* end = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, 0, 0, true, NSEventPhaseEnded,
NSEventPhaseNone);
EmulateSendEvent(target_window_, end);
in_trackpad_scroll = false;
// Assume a zero time delta means no fling. Just end the event phase.
if (event->time_stamp() == last_scroll_timestamp_)
return;
// Otherwise, switch phases for the "fling".
std::swap(event_phase, momentum_phase);
}
// Send a begin for the current event phase, unless it's already in progress.
if (!in_trackpad_scroll) {
NSEvent* begin = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, 0, 0, true, event_phase, momentum_phase);
EmulateSendEvent(target_window_, begin);
in_trackpad_scroll = true;
}
if (event->type() == ui::ET_SCROLL) {
NSEvent* update = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, -event->x_offset(), -event->y_offset(), true,
NSEventPhaseChanged, NSEventPhaseNone);
EmulateSendEvent(target_window_, update);
} else {
DCHECK_EQ(event->type(), ui::ET_SCROLL_FLING_START);
// Mac generates a stream of events. For the purposes of testing, just
// generate one.
NSEvent* update = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, -event->x_offset(), -event->y_offset(), true,
NSEventPhaseNone, NSEventPhaseChanged);
EmulateSendEvent(target_window_, update);
// Never leave the momentum part hanging.
NSEvent* end = cocoa_test_event_utils::TestScrollEvent(
location, target_window_, 0, 0, true, NSEventPhaseNone,
NSEventPhaseEnded);
EmulateSendEvent(target_window_, end);
in_trackpad_scroll = false;
}
last_scroll_timestamp_ = event->time_stamp();
}
gfx::Point EventGeneratorDelegateMac::CenterOfTarget(
const ui::EventTarget* target) const {
DCHECK_EQ(target, this);
return CenterOfWindow(gfx::NativeWindow(target_window_));
}
gfx::Point EventGeneratorDelegateMac::CenterOfWindow(
gfx::NativeWindow native_window) const {
NSWindow* window = native_window.GetNativeNSWindow();
DCHECK_EQ(window, target_window_);
// Assume the window is at the top-left of the coordinate system (even if
// AppKit has moved it into the work area) see ConvertRootPointToTarget().
return gfx::Point(NSWidth([window frame]) / 2, NSHeight([window frame]) / 2);
}
ui::EventDispatchDetails EventGeneratorDelegateMac::PreDispatchEvent(
ui::EventTarget* target,
ui::Event* event) {
// Set the TestScreen's cursor point before mouse event dispatch. The
// Screen's value is checked by views controls and other UI components; this
// pattern matches aura::WindowEventDispatcher::PreDispatchMouseEvent().
if (event->IsMouseEvent()) {
ui::MouseEvent* mouse_event = event->AsMouseEvent();
// Similar to the logic in Aura's
// EnvInputStateController::UpdateStateForMouseEvent(), capture change and
// synthesized events don't need to update the cursor location.
if (mouse_event->type() != ui::ET_MOUSE_CAPTURE_CHANGED &&
!(mouse_event->flags() & ui::EF_IS_SYNTHESIZED)) {
// Update the cursor location on screen.
owner_->set_current_screen_location(mouse_event->root_location());
display::Screen::GetScreen()->SetCursorScreenPointForTesting(
mouse_event->root_location());
}
}
return ui::EventDispatchDetails();
}
ui::test::EventGenerator* GetActiveGenerator() {
return EventGeneratorDelegateMac::instance()
? EventGeneratorDelegateMac::instance()->owner()
: nullptr;
}
} // namespace
namespace views::test {
std::unique_ptr<ui::test::EventGeneratorDelegate>
CreateEventGeneratorDelegateMac(ui::test::EventGenerator* owner,
gfx::NativeWindow root_window,
gfx::NativeWindow target_window) {
return std::make_unique<EventGeneratorDelegateMac>(owner, root_window,
target_window);
}
} // namespace views::test
@implementation NSEventDonor
// Donate +[NSEvent pressedMouseButtons] by retrieving the flags from the
// active generator.
+ (NSUInteger)pressedMouseButtons {
ui::test::EventGenerator* generator = GetActiveGenerator();
if (!generator)
return [NSEventDonor pressedMouseButtons]; // Call original implementation.
int flags = generator->flags();
NSUInteger bitmask = 0;
if (flags & ui::EF_LEFT_MOUSE_BUTTON)
bitmask |= 1;
if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
bitmask |= 1 << 1;
if (flags & ui::EF_MIDDLE_MOUSE_BUTTON)
bitmask |= 1 << 2;
return bitmask;
}
// Donate +[NSEvent mouseLocation] by retrieving the current position on screen.
+ (NSPoint)mouseLocation {
ui::test::EventGenerator* generator = GetActiveGenerator();
if (!generator)
return [NSEventDonor mouseLocation]; // Call original implementation.
// The location is the point in the root window which, for desktop widgets, is
// the widget itself.
gfx::Point point_in_root = generator->current_screen_location();
NSWindow* window = EventGeneratorDelegateMac::instance()->target_window();
NSPoint point_in_window = ConvertRootPointToTarget(window, point_in_root);
return [window convertPointToScreen:point_in_window];
}
@end
@implementation NSApplicationDonor
- (NSEvent*)currentEvent {
if (g_current_event)
return g_current_event;
// Find the original implementation and invoke it.
return EventGeneratorDelegateMac::instance()->OriginalCurrentEvent(self,
_cmd);
}
@end
| Zhao-PengFei35/chromium_src_4 | ui/views/test/event_generator_delegate_mac.mm | Objective-C++ | unknown | 25,720 |
// 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/focus_manager_test.h"
#include "base/ranges/algorithm.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/widget/widget.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// FocusManagerTest
FocusManagerTest::FocusManagerTest() : contents_view_(new View) {}
FocusManagerTest::~FocusManagerTest() = default;
FocusManager* FocusManagerTest::GetFocusManager() {
return GetWidget()->GetFocusManager();
}
void FocusManagerTest::SetUp() {
ViewsTestBase::SetUp();
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.delegate = this;
params.bounds = gfx::Rect(0, 0, 1024, 768);
widget->Init(std::move(params));
InitContentView();
widget->Show();
}
void FocusManagerTest::TearDown() {
if (focus_change_listener_)
GetFocusManager()->RemoveFocusChangeListener(focus_change_listener_);
if (widget_focus_change_listener_) {
WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(
widget_focus_change_listener_);
}
GetWidget()->Close();
// Flush the message loop to make application verifiers happy.
RunPendingMessages();
ViewsTestBase::TearDown();
}
View* FocusManagerTest::GetContentsView() {
return contents_view_;
}
Widget* FocusManagerTest::GetWidget() {
return contents_view_->GetWidget();
}
const Widget* FocusManagerTest::GetWidget() const {
return contents_view_->GetWidget();
}
void FocusManagerTest::GetAccessiblePanes(std::vector<View*>* panes) {
base::ranges::copy(accessible_panes_, std::back_inserter(*panes));
}
void FocusManagerTest::InitContentView() {}
void FocusManagerTest::AddFocusChangeListener(FocusChangeListener* listener) {
ASSERT_FALSE(focus_change_listener_);
focus_change_listener_ = listener;
GetFocusManager()->AddFocusChangeListener(listener);
}
void FocusManagerTest::AddWidgetFocusChangeListener(
WidgetFocusChangeListener* listener) {
ASSERT_FALSE(widget_focus_change_listener_);
widget_focus_change_listener_ = listener;
WidgetFocusManager::GetInstance()->AddFocusChangeListener(listener);
}
void FocusManagerTest::SetAccessiblePanes(const std::vector<View*>& panes) {
accessible_panes_ = panes;
}
////////////////////////////////////////////////////////////////////////////////
// TestFocusChangeListener
TestFocusChangeListener::TestFocusChangeListener() = default;
TestFocusChangeListener::~TestFocusChangeListener() = default;
void TestFocusChangeListener::OnWillChangeFocus(View* focused_before,
View* focused_now) {
focus_changes_.emplace_back(focused_before, focused_now);
}
void TestFocusChangeListener::OnDidChangeFocus(View* focused_before,
View* focused_now) {}
void TestFocusChangeListener::ClearFocusChanges() {
focus_changes_.clear();
}
////////////////////////////////////////////////////////////////////////////////
// TestWidgetFocusChangeListener
TestWidgetFocusChangeListener::TestWidgetFocusChangeListener() = default;
TestWidgetFocusChangeListener::~TestWidgetFocusChangeListener() = default;
void TestWidgetFocusChangeListener::ClearFocusChanges() {
focus_changes_.clear();
}
void TestWidgetFocusChangeListener::OnNativeFocusChanged(
gfx::NativeView focused_now) {
focus_changes_.push_back(focused_now);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/focus_manager_test.cc | C++ | unknown | 3,580 |
// 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_FOCUS_MANAGER_TEST_H_
#define UI_VIEWS_TEST_FOCUS_MANAGER_TEST_H_
#include "ui/views/focus/focus_manager.h"
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/views/focus/widget_focus_manager.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
class FocusChangeListener;
class FocusManagerTest : public ViewsTestBase, public WidgetDelegate {
public:
using FocusChangeReason = FocusManager::FocusChangeReason;
FocusManagerTest();
FocusManagerTest(const FocusManagerTest&) = delete;
FocusManagerTest& operator=(const FocusManagerTest&) = delete;
~FocusManagerTest() override;
// Convenience to obtain the focus manager for the test's hosting widget.
FocusManager* GetFocusManager();
// ViewsTestBase:
void SetUp() override;
void TearDown() override;
// WidgetDelegate:
View* GetContentsView() override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
void GetAccessiblePanes(std::vector<View*>* panes) override;
protected:
// Called after the Widget is initialized and the content view is added.
// Override to add controls to the layout.
virtual void InitContentView();
void AddFocusChangeListener(FocusChangeListener* listener);
void AddWidgetFocusChangeListener(WidgetFocusChangeListener* listener);
// For testing FocusManager::RotatePaneFocus().
void SetAccessiblePanes(const std::vector<View*>& panes);
private:
raw_ptr<View> contents_view_;
raw_ptr<FocusChangeListener> focus_change_listener_ = nullptr;
raw_ptr<WidgetFocusChangeListener> widget_focus_change_listener_ = nullptr;
std::vector<View*> accessible_panes_;
};
using ViewPair = std::pair<View*, View*>;
// Use to record focus change notifications.
class TestFocusChangeListener : public FocusChangeListener {
public:
TestFocusChangeListener();
TestFocusChangeListener(const TestFocusChangeListener&) = delete;
TestFocusChangeListener& operator=(const TestFocusChangeListener&) = delete;
~TestFocusChangeListener() override;
const std::vector<ViewPair>& focus_changes() const { return focus_changes_; }
void ClearFocusChanges();
// Overridden from FocusChangeListener:
void OnWillChangeFocus(View* focused_before, View* focused_now) override;
void OnDidChangeFocus(View* focused_before, View* focused_now) override;
private:
// A vector of which views lost/gained focus.
std::vector<ViewPair> focus_changes_;
};
// Use to record widget focus change notifications.
class TestWidgetFocusChangeListener : public WidgetFocusChangeListener {
public:
TestWidgetFocusChangeListener();
TestWidgetFocusChangeListener(const TestWidgetFocusChangeListener&) = delete;
TestWidgetFocusChangeListener& operator=(
const TestWidgetFocusChangeListener&) = delete;
~TestWidgetFocusChangeListener() override;
const std::vector<gfx::NativeView>& focus_changes() const {
return focus_changes_;
}
void ClearFocusChanges();
// Overridden from WidgetFocusChangeListener:
void OnNativeFocusChanged(gfx::NativeView focused_now) override;
private:
// Parameter received via OnNativeFocusChanged in oldest-to-newest-received
// order.
std::vector<gfx::NativeView> focus_changes_;
};
} // namespace views
#endif // UI_VIEWS_TEST_FOCUS_MANAGER_TEST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/focus_manager_test.h | C++ | unknown | 3,512 |
// 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 <ostream>
#include "ui/views/layout/flex_layout_types.h"
#include "ui/views/layout/layout_types.h"
namespace views {
void PrintTo(const SizeBounds& size_bounds, ::std::ostream* os) {
*os << size_bounds.ToString();
}
void PrintTo(LayoutOrientation layout_orientation, ::std::ostream* os) {
switch (layout_orientation) {
case LayoutOrientation::kHorizontal:
*os << "LayoutOrientation::kHorizontal";
break;
case LayoutOrientation::kVertical:
*os << "LayoutOrientation::kVertical";
break;
}
}
void PrintTo(MinimumFlexSizeRule minimum_flex_size_rule, ::std::ostream* os) {
switch (minimum_flex_size_rule) {
case MinimumFlexSizeRule::kPreferred:
*os << "MinimumFlexSizeRule::kPreferred";
break;
case MinimumFlexSizeRule::kPreferredSnapToMinimum:
*os << "MinimumFlexSizeRule::kPreferredSnapToMinimum";
break;
case MinimumFlexSizeRule::kPreferredSnapToZero:
*os << "MinimumFlexSizeRule::kPreferredSnapToZero";
break;
case MinimumFlexSizeRule::kScaleToMinimum:
*os << "MinimumFlexSizeRule::kScaleToMinimum";
break;
case MinimumFlexSizeRule::kScaleToMinimumSnapToZero:
*os << "MinimumFlexSizeRule::kScaleToMinimumSnapToZero";
break;
case MinimumFlexSizeRule::kScaleToZero:
*os << "MinimumFlexSizeRule::kScaleToZero";
break;
}
}
void PrintTo(MaximumFlexSizeRule maximum_flex_size_rule, ::std::ostream* os) {
switch (maximum_flex_size_rule) {
case MaximumFlexSizeRule::kPreferred:
*os << "MaximumFlexSizeRule::kPreferred";
break;
case MaximumFlexSizeRule::kScaleToMaximum:
*os << "MaximumFlexSizeRule::kScaleToMaximum";
break;
case MaximumFlexSizeRule::kUnbounded:
*os << "MaximumFlexSizeRule::kUnbounded";
break;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/layout_test_utils.cc | C++ | unknown | 1,978 |
// 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/menu_runner_test_api.h"
#include <utility>
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/menu_runner_handler.h"
namespace views::test {
MenuRunnerTestAPI::MenuRunnerTestAPI(MenuRunner* menu_runner)
: menu_runner_(menu_runner) {}
MenuRunnerTestAPI::~MenuRunnerTestAPI() = default;
void MenuRunnerTestAPI::SetMenuRunnerHandler(
std::unique_ptr<MenuRunnerHandler> menu_runner_handler) {
menu_runner_->SetRunnerHandler(std::move(menu_runner_handler));
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/menu_runner_test_api.cc | C++ | unknown | 698 |
// 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_MENU_RUNNER_TEST_API_H_
#define UI_VIEWS_TEST_MENU_RUNNER_TEST_API_H_
#include <memory>
#include "base/memory/raw_ptr.h"
namespace views {
class MenuRunner;
class MenuRunnerHandler;
namespace test {
// A wrapper of MenuRunner to use testing methods of MenuRunner.
class MenuRunnerTestAPI {
public:
explicit MenuRunnerTestAPI(MenuRunner* menu_runner);
MenuRunnerTestAPI(const MenuRunnerTestAPI&) = delete;
MenuRunnerTestAPI& operator=(const MenuRunnerTestAPI&) = delete;
~MenuRunnerTestAPI();
// Sets the menu runner handler.
void SetMenuRunnerHandler(
std::unique_ptr<MenuRunnerHandler> menu_runner_handler);
private:
raw_ptr<MenuRunner> menu_runner_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_MENU_RUNNER_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/menu_runner_test_api.h | C++ | unknown | 948 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/menu_test_utils.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/views/controls/menu/menu_controller.h"
#if BUILDFLAG(IS_MAC)
#include "ui/views/controls/menu/menu_closure_animation_mac.h"
#endif
namespace views::test {
// TestMenuDelegate -----------------------------------------------------------
TestMenuDelegate::TestMenuDelegate() = default;
TestMenuDelegate::~TestMenuDelegate() = default;
bool TestMenuDelegate::ShowContextMenu(MenuItemView* source,
int id,
const gfx::Point& p,
ui::MenuSourceType source_type) {
show_context_menu_count_++;
show_context_menu_source_ = source;
return true;
}
void TestMenuDelegate::ExecuteCommand(int id) {
execute_command_id_ = id;
}
void TestMenuDelegate::OnMenuClosed(MenuItemView* menu) {
on_menu_closed_called_count_++;
on_menu_closed_menu_ = menu;
}
views::View::DropCallback TestMenuDelegate::GetDropCallback(
MenuItemView* menu,
DropPosition position,
const ui::DropTargetEvent& event) {
return base::BindOnce(&TestMenuDelegate::PerformDrop, base::Unretained(this));
}
int TestMenuDelegate::GetDragOperations(MenuItemView* sender) {
return ui::DragDropTypes::DRAG_COPY;
}
void TestMenuDelegate::WriteDragData(MenuItemView* sender,
OSExchangeData* data) {}
void TestMenuDelegate::WillHideMenu(MenuItemView* menu) {
will_hide_menu_count_++;
will_hide_menu_ = menu;
}
bool TestMenuDelegate::ShouldExecuteCommandWithoutClosingMenu(
int id,
const ui::Event& e) {
return should_execute_command_without_closing_menu_;
}
void TestMenuDelegate::PerformDrop(
const ui::DropTargetEvent& event,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) {
is_drop_performed_ = true;
output_drag_op = ui::mojom::DragOperation::kCopy;
}
// MenuControllerTestApi ------------------------------------------------------
MenuControllerTestApi::MenuControllerTestApi()
: controller_(MenuController::GetActiveInstance()->AsWeakPtr()) {}
MenuControllerTestApi::~MenuControllerTestApi() = default;
void MenuControllerTestApi::ClearState() {
if (!controller_)
return;
controller_->ClearStateForTest();
}
void MenuControllerTestApi::SetShowing(bool showing) {
if (!controller_)
return;
controller_->showing_ = showing;
}
void DisableMenuClosureAnimations() {
#if BUILDFLAG(IS_MAC)
MenuClosureAnimationMac::DisableAnimationsForTesting();
#endif
}
void WaitForMenuClosureAnimation() {
#if BUILDFLAG(IS_MAC)
// TODO(https://crbug.com/982815): Replace this with Quit+Run.
base::RunLoop().RunUntilIdle();
#endif
}
// ReleaseRefTestViewsDelegate ------------------------------------------------
ReleaseRefTestViewsDelegate::ReleaseRefTestViewsDelegate() = default;
ReleaseRefTestViewsDelegate::~ReleaseRefTestViewsDelegate() = default;
void ReleaseRefTestViewsDelegate::ReleaseRef() {
if (!release_ref_callback_.is_null())
release_ref_callback_.Run();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/menu_test_utils.cc | C++ | unknown | 3,413 |
// 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_TEST_MENU_TEST_UTILS_H_
#define UI_VIEWS_TEST_MENU_TEST_UTILS_H_
#include <memory>
#include <utility>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/view.h"
namespace views {
class MenuController;
namespace test {
// Test implementation of MenuDelegate that tracks calls to MenuDelegate, along
// with the provided parameters.
class TestMenuDelegate : public MenuDelegate {
public:
TestMenuDelegate();
TestMenuDelegate(const TestMenuDelegate&) = delete;
TestMenuDelegate& operator=(const TestMenuDelegate&) = delete;
~TestMenuDelegate() override;
int show_context_menu_count() { return show_context_menu_count_; }
MenuItemView* show_context_menu_source() { return show_context_menu_source_; }
int execute_command_id() const { return execute_command_id_; }
int on_menu_closed_called() const { return on_menu_closed_called_count_; }
MenuItemView* on_menu_closed_menu() const { return on_menu_closed_menu_; }
bool is_drop_performed() { return is_drop_performed_; }
int will_hide_menu_count() { return will_hide_menu_count_; }
MenuItemView* will_hide_menu() { return will_hide_menu_; }
void set_should_execute_command_without_closing_menu(bool val) {
should_execute_command_without_closing_menu_ = val;
}
// MenuDelegate:
bool ShowContextMenu(MenuItemView* source,
int id,
const gfx::Point& p,
ui::MenuSourceType source_type) override;
void ExecuteCommand(int id) override;
void OnMenuClosed(MenuItemView* menu) override;
views::View::DropCallback GetDropCallback(
MenuItemView* menu,
DropPosition position,
const ui::DropTargetEvent& event) override;
int GetDragOperations(MenuItemView* sender) override;
void WriteDragData(MenuItemView* sender, OSExchangeData* data) override;
void WillHideMenu(MenuItemView* menu) override;
bool ShouldExecuteCommandWithoutClosingMenu(int id,
const ui::Event& e) override;
private:
// Performs the drop operation and updates |output_drag_op| accordingly.
void PerformDrop(const ui::DropTargetEvent& event,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner);
// The number of times ShowContextMenu was called.
int show_context_menu_count_ = 0;
// The value of the last call to ShowContextMenu.
raw_ptr<MenuItemView> show_context_menu_source_ = nullptr;
// ID of last executed command.
int execute_command_id_ = 0;
// The number of times OnMenuClosed was called.
int on_menu_closed_called_count_ = 0;
// The value of the last call to OnMenuClosed.
raw_ptr<MenuItemView> on_menu_closed_menu_ = nullptr;
// The number of times WillHideMenu was called.
int will_hide_menu_count_ = 0;
// The value of the last call to WillHideMenu.
raw_ptr<MenuItemView> will_hide_menu_ = nullptr;
bool is_drop_performed_ = false;
bool should_execute_command_without_closing_menu_ = false;
};
// Test api which caches the currently active MenuController. Can be used to
// toggle visibility, and to clear seletion states, without performing full
// shutdown. This is used to simulate menus with varing states, such as during
// drags, without performing the entire operation. Used to test strange shutdown
// ordering.
class MenuControllerTestApi {
public:
MenuControllerTestApi();
MenuControllerTestApi(const MenuControllerTestApi&) = delete;
MenuControllerTestApi& operator=(const MenuControllerTestApi&) = delete;
~MenuControllerTestApi();
MenuController* controller() { return controller_.get(); }
// Clears out the current and pending states, without notifying the associated
// menu items.
void ClearState();
// Toggles the internal showing state of |controller_| without attempting
// to change associated Widgets.
void SetShowing(bool showing);
private:
base::WeakPtr<MenuController> controller_;
};
// On platforms which have menu closure animations, these functions are
// necessary to:
// 1) Disable those animations (make them take zero time) to avoid slowing
// down tests;
// 2) Wait for maybe-asynchronous menu closure to finish.
// On platforms without menu closure animations, these do nothing.
void DisableMenuClosureAnimations();
void WaitForMenuClosureAnimation();
// An implementation of TestViewsDelegate which overrides ReleaseRef in order to
// call a provided callback.
class ReleaseRefTestViewsDelegate : public TestViewsDelegate {
public:
ReleaseRefTestViewsDelegate();
ReleaseRefTestViewsDelegate(const ReleaseRefTestViewsDelegate&) = delete;
ReleaseRefTestViewsDelegate& operator=(const ReleaseRefTestViewsDelegate&) =
delete;
~ReleaseRefTestViewsDelegate() override;
void set_release_ref_callback(base::RepeatingClosure release_ref_callback) {
release_ref_callback_ = std::move(release_ref_callback);
}
// TestViewsDelegate:
void ReleaseRef() override;
private:
base::RepeatingClosure release_ref_callback_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_MENU_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/menu_test_utils.h | C++ | unknown | 5,525 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/mock_drag_controller.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/os_exchange_data.h"
namespace views {
MockDragController::MockDragController() = default;
MockDragController::~MockDragController() = default;
void MockDragController::WriteDragDataForView(View* sender,
const gfx::Point& press_pt,
ui::OSExchangeData* data) {
data->SetString(u"test");
}
int MockDragController::GetDragOperationsForView(View* sender,
const gfx::Point& p) {
return ui::DragDropTypes::DRAG_COPY;
}
bool MockDragController::CanStartDragForView(View* sender,
const gfx::Point& press_pt,
const gfx::Point& p) {
return true;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_drag_controller.cc | C++ | unknown | 1,069 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_MOCK_DRAG_CONTROLLER_H_
#define UI_VIEWS_TEST_MOCK_DRAG_CONTROLLER_H_
#include "ui/views/drag_controller.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace gfx {
class Point;
} // namespace gfx
namespace ui {
class OSExchangeData;
} // namespace ui
namespace views {
class View;
// A mocked drag controller for testing.
class MockDragController : public DragController {
public:
MockDragController();
MockDragController(const MockDragController&) = delete;
MockDragController& operator=(const MockDragController&) = delete;
~MockDragController() override;
// DragController:
void WriteDragDataForView(View* sender,
const gfx::Point& press_pt,
ui::OSExchangeData* data) override;
int GetDragOperationsForView(View* sender, const gfx::Point& p) override;
bool CanStartDragForView(View* sender,
const gfx::Point& press_pt,
const gfx::Point& p) override;
MOCK_METHOD(void, OnWillStartDragForView, (View * dragged_view), (override));
};
} // namespace views
#endif // UI_VIEWS_TEST_MOCK_DRAG_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_drag_controller.h | C++ | unknown | 1,318 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/mock_input_event_activation_protector.h"
namespace views {
MockInputEventActivationProtector::MockInputEventActivationProtector() =
default;
MockInputEventActivationProtector::~MockInputEventActivationProtector() =
default;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_input_event_activation_protector.cc | C++ | unknown | 423 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_MOCK_INPUT_EVENT_ACTIVATION_PROTECTOR_H_
#define UI_VIEWS_TEST_MOCK_INPUT_EVENT_ACTIVATION_PROTECTOR_H_
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/views/input_event_activation_protector.h"
namespace views {
// Mock version of InputEventActivationProtector for injection during tests, to
// allow verifying that protected Views work as expected.
class MockInputEventActivationProtector : public InputEventActivationProtector {
public:
MockInputEventActivationProtector();
~MockInputEventActivationProtector() override;
MockInputEventActivationProtector(const MockInputEventActivationProtector&) =
delete;
MockInputEventActivationProtector& operator=(
const MockInputEventActivationProtector&) = delete;
MOCK_METHOD(bool,
IsPossiblyUnintendedInteraction,
(const ui::Event& event),
(override));
};
} // namespace views
#endif // UI_VIEWS_TEST_MOCK_INPUT_EVENT_ACTIVATION_PROTECTOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_input_event_activation_protector.h | C++ | unknown | 1,138 |
//, Copyright 2023 The Chromium Authors
//, Use of this source code is governed by a BSD-style license that can be
//, found in the LICENSE file.
#include "ui/views/test/mock_native_widget.h"
using testing::Return;
namespace views {
MockNativeWidget::MockNativeWidget(Widget* widget) : widget_(widget) {}
MockNativeWidget::~MockNativeWidget() {
widget_->OnNativeWidgetDestroyed();
}
base::WeakPtr<internal::NativeWidgetPrivate> MockNativeWidget::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_native_widget.cc | C++ | unknown | 531 |
//, Copyright 2023 The Chromium Authors
//, Use of this source code is governed by a BSD-style license that can be
//, found in the LICENSE file.
#ifndef UI_VIEWS_TEST_MOCK_NATIVE_WIDGET_H_
#define UI_VIEWS_TEST_MOCK_NATIVE_WIDGET_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/views/widget/native_widget_private.h"
namespace views {
class MockNativeWidget : public internal::NativeWidgetPrivate {
public:
explicit MockNativeWidget(Widget*);
~MockNativeWidget() override;
MOCK_METHOD(void, InitNativeWidget, (Widget::InitParams), (override));
MOCK_METHOD(void, OnWidgetInitDone, (), (override));
MOCK_METHOD(std::unique_ptr<NonClientFrameView>,
CreateNonClientFrameView,
(),
(override));
MOCK_METHOD(bool, ShouldUseNativeFrame, (), (const override));
MOCK_METHOD(bool, ShouldWindowContentsBeTransparent, (), (const override));
MOCK_METHOD(void, FrameTypeChanged, (), (override));
MOCK_METHOD(Widget*, GetWidget, (), (override));
MOCK_METHOD(const Widget*, GetWidget, (), (const override));
MOCK_METHOD(gfx::NativeView, GetNativeView, (), (const override));
MOCK_METHOD(gfx::NativeWindow, GetNativeWindow, (), (const override));
MOCK_METHOD(Widget*, GetTopLevelWidget, (), (override));
MOCK_METHOD(const ui::Compositor*, GetCompositor, (), (const override));
MOCK_METHOD(const ui::Layer*, GetLayer, (), (const override));
MOCK_METHOD(void, ReorderNativeViews, (), (override));
MOCK_METHOD(void, ViewRemoved, (View * view), (override));
MOCK_METHOD(void,
SetNativeWindowProperty,
(const char* name, void* value),
(override));
MOCK_METHOD(void*,
GetNativeWindowProperty,
(const char* name),
(const override));
MOCK_METHOD(TooltipManager*, GetTooltipManager, (), (const override));
MOCK_METHOD(void, SetCapture, (), (override));
MOCK_METHOD(void, ReleaseCapture, (), (override));
MOCK_METHOD(bool, HasCapture, (), (const override));
MOCK_METHOD(ui::InputMethod*, GetInputMethod, (), (override));
MOCK_METHOD(void, CenterWindow, (const gfx::Size& size), (override));
MOCK_METHOD(void,
GetWindowPlacement,
(gfx::Rect * bounds, ui::WindowShowState* show_state),
(const override));
MOCK_METHOD(bool, SetWindowTitle, (const std::u16string& title), (override));
MOCK_METHOD(void,
SetWindowIcons,
(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon),
(override));
MOCK_METHOD(const gfx::ImageSkia*, GetWindowIcon, (), (override));
MOCK_METHOD(const gfx::ImageSkia*, GetWindowAppIcon, (), (override));
MOCK_METHOD(void, InitModalType, (ui::ModalType modal_type), (override));
MOCK_METHOD(gfx::Rect, GetWindowBoundsInScreen, (), (const override));
MOCK_METHOD(gfx::Rect, GetClientAreaBoundsInScreen, (), (const override));
MOCK_METHOD(gfx::Rect, GetRestoredBounds, (), (const override));
MOCK_METHOD(std::string, GetWorkspace, (), (const override));
MOCK_METHOD(void, SetBounds, (const gfx::Rect& bounds), (override));
MOCK_METHOD(void,
SetBoundsConstrained,
(const gfx::Rect& bounds),
(override));
MOCK_METHOD(void, SetSize, (const gfx::Size& size), (override));
MOCK_METHOD(void, StackAbove, (gfx::NativeView native_view), (override));
MOCK_METHOD(void, StackAtTop, (), (override));
MOCK_METHOD(bool, IsStackedAbove, (gfx::NativeView native_view), (override));
MOCK_METHOD(void,
SetShape,
(std::unique_ptr<Widget::ShapeRects> shape),
(override));
MOCK_METHOD(void, Close, (), (override));
MOCK_METHOD(void, CloseNow, (), (override));
MOCK_METHOD(void,
Show,
(ui::WindowShowState show_state, const gfx::Rect& restore_bounds),
(override));
MOCK_METHOD(void, Hide, (), (override));
MOCK_METHOD(bool, IsVisible, (), (const override));
MOCK_METHOD(void, Activate, (), (override));
MOCK_METHOD(void, Deactivate, (), (override));
MOCK_METHOD(bool, IsActive, (), (const override));
MOCK_METHOD(void, SetZOrderLevel, (ui::ZOrderLevel order), (override));
MOCK_METHOD(ui::ZOrderLevel, GetZOrderLevel, (), (const override));
MOCK_METHOD(void,
SetVisibleOnAllWorkspaces,
(bool always_visible),
(override));
MOCK_METHOD(bool, IsVisibleOnAllWorkspaces, (), (const override));
MOCK_METHOD(void, Maximize, (), (override));
MOCK_METHOD(void, Minimize, (), (override));
MOCK_METHOD(bool, IsMaximized, (), (const override));
MOCK_METHOD(bool, IsMinimized, (), (const override));
MOCK_METHOD(void, Restore, (), (override));
MOCK_METHOD(void,
SetFullscreen,
(bool fullscreen, int64_t target_display_id),
(override));
MOCK_METHOD(bool, IsFullscreen, (), (const override));
MOCK_METHOD(void,
SetCanAppearInExistingFullscreenSpaces,
(bool can_appear_in_existing_fullscreen_spaces),
(override));
MOCK_METHOD(void, SetOpacity, (float opacity), (override));
MOCK_METHOD(void,
SetAspectRatio,
(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin),
(override));
MOCK_METHOD(void, FlashFrame, (bool flash), (override));
MOCK_METHOD(void,
RunShellDrag,
(View * view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source),
(override));
MOCK_METHOD(void, SchedulePaintInRect, (const gfx::Rect& rect), (override));
MOCK_METHOD(void, ScheduleLayout, (), (override));
MOCK_METHOD(void, SetCursor, (const ui::Cursor& cursor), (override));
MOCK_METHOD(void, ShowEmojiPanel, (), (override));
MOCK_METHOD(bool, IsMouseEventsEnabled, (), (const override));
MOCK_METHOD(bool, IsMouseButtonDown, (), (const override));
MOCK_METHOD(void, ClearNativeFocus, (), (override));
MOCK_METHOD(gfx::Rect, GetWorkAreaBoundsInScreen, (), (const override));
MOCK_METHOD(bool, IsMoveLoopSupported, (), (const override));
MOCK_METHOD(Widget::MoveLoopResult,
RunMoveLoop,
(const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior),
(override));
MOCK_METHOD(void, EndMoveLoop, (), (override));
MOCK_METHOD(void,
SetVisibilityChangedAnimationsEnabled,
(bool value),
(override));
MOCK_METHOD(void,
SetVisibilityAnimationDuration,
(const base::TimeDelta& duration),
(override));
MOCK_METHOD(void,
SetVisibilityAnimationTransition,
(Widget::VisibilityTransition transition),
(override));
MOCK_METHOD(bool, IsTranslucentWindowOpacitySupported, (), (const override));
MOCK_METHOD(ui::GestureRecognizer*, GetGestureRecognizer, (), (override));
MOCK_METHOD(ui::GestureConsumer*, GetGestureConsumer, (), (override));
MOCK_METHOD(void, OnSizeConstraintsChanged, (), (override));
MOCK_METHOD(void, OnNativeViewHierarchyWillChange, (), (override));
MOCK_METHOD(void, OnNativeViewHierarchyChanged, (), (override));
MOCK_METHOD(std::string, GetName, (), (const override));
base::WeakPtr<NativeWidgetPrivate> GetWeakPtr() override;
private:
raw_ptr<Widget> widget_;
base::WeakPtrFactory<MockNativeWidget> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_TEST_MOCK_NATIVE_WIDGET_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/mock_native_widget.h | C++ | unknown | 7,808 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/native_widget_factory.h"
#include <utility>
#include "build/build_config.h"
#include "ui/views/buildflags.h"
#include "ui/views/test/test_platform_native_widget.h"
#if defined(USE_AURA)
#include "ui/views/widget/native_widget_aura.h"
#elif BUILDFLAG(IS_MAC)
#include "ui/views/widget/native_widget_mac.h"
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif
namespace views::test {
#if BUILDFLAG(IS_MAC)
using PlatformNativeWidget = NativeWidgetMac;
using PlatformDesktopNativeWidget = NativeWidgetMac;
#else
using PlatformNativeWidget = NativeWidgetAura;
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
using PlatformDesktopNativeWidget = DesktopNativeWidgetAura;
#endif
#endif
NativeWidget* CreatePlatformNativeWidgetImpl(
Widget* widget,
uint32_t type,
bool* destroyed) {
return new TestPlatformNativeWidget<PlatformNativeWidget>(
widget, type == kStubCapture, destroyed);
}
NativeWidget* CreatePlatformNativeWidgetImpl(
Widget* widget,
uint32_t type,
base::OnceClosure destroyed_callback) {
return new TestPlatformNativeWidget<PlatformNativeWidget>(
widget, type == kStubCapture, std::move(destroyed_callback));
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
NativeWidget* CreatePlatformDesktopNativeWidgetImpl(
Widget* widget,
uint32_t type,
base::OnceClosure destroyed_callback) {
return new TestPlatformNativeWidget<PlatformDesktopNativeWidget>(
widget, type == kStubCapture, std::move(destroyed_callback));
}
#endif
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/native_widget_factory.cc | C++ | unknown | 1,732 |
// 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_TEST_NATIVE_WIDGET_FACTORY_H_
#define UI_VIEWS_TEST_NATIVE_WIDGET_FACTORY_H_
#include <stdint.h>
#include "base/functional/callback_forward.h"
#include "ui/views/widget/widget.h"
namespace views {
class NativeWidget;
namespace test {
// Values supplied to |behavior|.
// NativeWidget implementation is not customized in anyway.
constexpr uint32_t kDefault = 0u;
// Indicates capture should be mocked out and not interact with the system.
constexpr uint32_t kStubCapture = 1 << 0;
// Creates the appropriate platform specific non-desktop NativeWidget
// implementation. If |destroyed| is non-null it it set to true from the
// destructor of the NativeWidget.
NativeWidget* CreatePlatformNativeWidgetImpl(
Widget* widget,
uint32_t behavior,
bool* destroyed);
// Creates the appropriate platform specific non-desktop NativeWidget
// implementation. Creates the appropriate platform specific desktop
// NativeWidget implementation. `destroyed_callback` is called from the
// destructor of the NativeWidget.
NativeWidget* CreatePlatformNativeWidgetImpl(
Widget* widget,
uint32_t behavior,
base::OnceClosure destroyed_callback);
// Creates the appropriate platform specific desktop NativeWidget
// implementation. `destroyed_callback` is called from the destructor of the
// NativeWidget.
NativeWidget* CreatePlatformDesktopNativeWidgetImpl(
Widget* widget,
uint32_t behavior,
base::OnceClosure destroyed_callback);
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_NATIVE_WIDGET_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/native_widget_factory.h | C++ | unknown | 1,711 |
// 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/test/scoped_views_test_helper.h"
#include <utility>
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/test/test_clipboard.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#endif
namespace views {
ScopedViewsTestHelper::ScopedViewsTestHelper(
std::unique_ptr<TestViewsDelegate> test_views_delegate,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory)
: test_views_delegate_(test_views_delegate
? std::move(test_views_delegate)
: test_helper_->GetFallbackTestViewsDelegate()) {
test_helper_->SetUpTestViewsDelegate(test_views_delegate_.get(),
std::move(factory));
test_helper_->SetUp();
// OS clipboard is a global resource, which causes flakiness when unit tests
// run in parallel. So, use a per-instance test clipboard.
ui::TestClipboard::CreateForCurrentThread();
}
ScopedViewsTestHelper::~ScopedViewsTestHelper() {
ui::Clipboard::DestroyClipboardForCurrentThread();
}
gfx::NativeWindow ScopedViewsTestHelper::GetContext() {
return test_helper_->GetContext();
}
#if defined(USE_AURA)
void ScopedViewsTestHelper::SimulateNativeDestroy(Widget* widget) {
delete widget->GetNativeView();
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
void ScopedViewsTestHelper::SimulateDesktopNativeDestroy(Widget* widget) {
static_cast<DesktopNativeWidgetAura*>(widget->native_widget())
->desktop_window_tree_host_for_testing()
->Close();
}
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA)
#endif // defined(USE_AURA)
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/scoped_views_test_helper.cc | C++ | unknown | 1,935 |
// 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_TEST_SCOPED_VIEWS_TEST_HELPER_H_
#define UI_VIEWS_TEST_SCOPED_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/test/test_views_delegate.h"
#include "ui/views/test/views_test_helper.h"
#include "ui/views/views_delegate.h"
namespace views {
class Widget;
// Creates a ViewsTestHelper that is destroyed automatically. Acts like
// ViewsTestBase but allows a test harness to use a different base class, or
// make use of a BrowserTaskEnvironment, rather than the MessageLoop provided
// by ViewsTestBase.
class ScopedViewsTestHelper {
public:
// Initialize with the given TestViewsDelegate instance.
explicit ScopedViewsTestHelper(
std::unique_ptr<TestViewsDelegate> test_views_delegate = nullptr,
absl::optional<ViewsDelegate::NativeWidgetFactory> factory =
absl::nullopt);
ScopedViewsTestHelper(const ScopedViewsTestHelper&) = delete;
ScopedViewsTestHelper& operator=(const ScopedViewsTestHelper&) = delete;
~ScopedViewsTestHelper();
// Returns the context for creating new windows. In Aura builds, this will be
// the RootWindow. Everywhere else, null.
gfx::NativeWindow GetContext();
// 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
TestViewsDelegate* test_views_delegate() {
return test_views_delegate_.get();
}
private:
std::unique_ptr<ViewsTestHelper> test_helper_ = ViewsTestHelper::Create();
std::unique_ptr<TestViewsDelegate> test_views_delegate_;
};
} // namespace views
#endif // UI_VIEWS_TEST_SCOPED_VIEWS_TEST_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/scoped_views_test_helper.h | C++ | unknown | 2,038 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/scoped_views_test_helper.h"
#include <Cocoa/Cocoa.h>
#import "base/mac/scoped_nsobject.h"
#include "ui/views/widget/widget.h"
namespace views {
void ScopedViewsTestHelper::SimulateNativeDestroy(Widget* widget) {
// Retain the window while closing it, otherwise the window may lose its
// last owner before -[NSWindow close] completes (this offends AppKit).
// Usually this reference will exist on an event delivered to the runloop.
base::scoped_nsobject<NSWindow> window(
[widget->GetNativeWindow().GetNativeNSWindow() retain]);
[window close];
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/test/scoped_views_test_helper_cocoa.mm | Objective-C++ | unknown | 758 |
// 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/slider_test_api.h"
#include "ui/views/controls/slider.h"
namespace views::test {
SliderTestApi::SliderTestApi(Slider* slider) : slider_(slider) {}
SliderTestApi::~SliderTestApi() = default;
void SliderTestApi::SetListener(SliderListener* listener) {
slider_->set_listener(listener);
}
int SliderTestApi::initial_button_offset() const {
return slider_->initial_button_offset_;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/slider_test_api.cc | C++ | unknown | 584 |
// 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_SLIDER_TEST_API_H_
#define UI_VIEWS_TEST_SLIDER_TEST_API_H_
#include "base/memory/raw_ptr.h"
namespace views {
class Slider;
class SliderListener;
namespace test {
// Can be used to update the private state of a views::Slider instance during a
// test. Updating the private state of an already created instance reduces
// the amount of test setup and test fixture code required.
class SliderTestApi {
public:
explicit SliderTestApi(Slider* slider);
SliderTestApi(const SliderTestApi&) = delete;
SliderTestApi& operator=(const SliderTestApi&) = delete;
virtual ~SliderTestApi();
// Set the SliderListener on the Slider.
void SetListener(SliderListener* listener);
int initial_button_offset() const;
private:
raw_ptr<Slider> slider_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_SLIDER_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/slider_test_api.h | C++ | unknown | 1,020 |
// 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/test_desktop_screen_ozone.h"
namespace views::test {
namespace {
TestDesktopScreenOzone* g_instance = nullptr;
}
// static
std::unique_ptr<display::Screen> TestDesktopScreenOzone::Create() {
auto screen = std::make_unique<TestDesktopScreenOzone>();
screen->Initialize();
return screen;
}
TestDesktopScreenOzone* TestDesktopScreenOzone::GetInstance() {
DCHECK_EQ(display::Screen::GetScreen(), g_instance);
return g_instance;
}
gfx::Point TestDesktopScreenOzone::GetCursorScreenPoint() {
return cursor_screen_point_;
}
TestDesktopScreenOzone::TestDesktopScreenOzone() {
DCHECK(!g_instance);
g_instance = this;
}
TestDesktopScreenOzone::~TestDesktopScreenOzone() {
g_instance = nullptr;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_desktop_screen_ozone.cc | C++ | unknown | 907 |
// 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_TEST_DESKTOP_SCREEN_OZONE_H_
#define UI_VIEWS_TEST_TEST_DESKTOP_SCREEN_OZONE_H_
#include <memory>
#include "ui/gfx/geometry/point.h"
#include "ui/views/widget/desktop_aura/desktop_screen_ozone.h"
namespace display {
class Screen;
}
namespace views::test {
// Replaces the screen instance in Linux/Ozone (non-ChromeOS) tests. Allows
// aura tests to manually set the cursor screen point to be reported
// by GetCursorScreenPoint(). Needed because of a limitation in the
// X11 protocol that restricts us from warping the pointer with the
// mouse button held down.
class TestDesktopScreenOzone : public views::DesktopScreenOzone {
public:
TestDesktopScreenOzone(const TestDesktopScreenOzone&) = delete;
TestDesktopScreenOzone& operator=(const TestDesktopScreenOzone&) = delete;
static std::unique_ptr<display::Screen> Create();
static TestDesktopScreenOzone* GetInstance();
// DesktopScreenOzone:
gfx::Point GetCursorScreenPoint() override;
void set_cursor_screen_point(const gfx::Point& point) {
cursor_screen_point_ = point;
}
TestDesktopScreenOzone();
~TestDesktopScreenOzone() override;
private:
gfx::Point cursor_screen_point_;
};
} // namespace views::test
#endif // UI_VIEWS_TEST_TEST_DESKTOP_SCREEN_OZONE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_desktop_screen_ozone.h | C++ | unknown | 1,425 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/test_layout_manager.h"
namespace views::test {
TestLayoutManager::TestLayoutManager() = default;
TestLayoutManager::~TestLayoutManager() = default;
void TestLayoutManager::Layout(View* host) {}
gfx::Size TestLayoutManager::GetPreferredSize(const View* host) const {
return preferred_size_;
}
int TestLayoutManager::GetPreferredHeightForWidth(const View* host,
int width) const {
return preferred_height_for_width_;
}
void TestLayoutManager::InvalidateLayout() {
++invalidate_count_;
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_layout_manager.cc | C++ | unknown | 745 |
// 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_TEST_TEST_LAYOUT_MANAGER_H_
#define UI_VIEWS_TEST_TEST_LAYOUT_MANAGER_H_
#include "ui/gfx/geometry/size.h"
#include "ui/views/layout/layout_manager.h"
namespace views::test {
// A stub layout manager that returns a specific preferred size and height for
// width.
class TestLayoutManager : public LayoutManager {
public:
TestLayoutManager();
TestLayoutManager(const TestLayoutManager&) = delete;
TestLayoutManager& operator=(const TestLayoutManager&) = delete;
~TestLayoutManager() override;
void SetPreferredSize(const gfx::Size& size) { preferred_size_ = size; }
void set_preferred_height_for_width(int height) {
preferred_height_for_width_ = height;
}
int invalidate_count() const { return invalidate_count_; }
// LayoutManager:
void Layout(View* host) override;
gfx::Size GetPreferredSize(const View* host) const override;
int GetPreferredHeightForWidth(const View* host, int width) const override;
void InvalidateLayout() override;
private:
// The return value of GetPreferredSize();
gfx::Size preferred_size_;
// The return value for GetPreferredHeightForWidth().
int preferred_height_for_width_ = 0;
// The number of calls to InvalidateLayout().
int invalidate_count_ = 0;
};
} // namespace views::test
#endif // UI_VIEWS_TEST_TEST_LAYOUT_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_layout_manager.h | C++ | unknown | 1,478 |
// 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/test_layout_provider.h"
namespace views::test {
TestLayoutProvider::TestLayoutProvider() = default;
TestLayoutProvider::~TestLayoutProvider() = default;
void TestLayoutProvider::SetDistanceMetric(int metric, int value) {
distance_metrics_[metric] = value;
}
void TestLayoutProvider::SetSnappedDialogWidth(int width) {
snapped_dialog_width_ = width;
}
void TestLayoutProvider::SetFontDetails(
int context,
int style,
const ui::ResourceBundle::FontDetails& details) {
details_[{context, style}] = details;
}
int TestLayoutProvider::GetDistanceMetric(int metric) const {
if (distance_metrics_.count(metric))
return distance_metrics_.find(metric)->second;
return LayoutProvider::GetDistanceMetric(metric);
}
const TypographyProvider& TestLayoutProvider::GetTypographyProvider() const {
return *this;
}
int TestLayoutProvider::GetSnappedDialogWidth(int min_width) const {
return snapped_dialog_width_ ? snapped_dialog_width_ : min_width;
}
ui::ResourceBundle::FontDetails TestLayoutProvider::GetFontDetails(
int context,
int style) const {
auto it = details_.find({context, style});
return it != details_.end()
? it->second
: TypographyProvider::GetFontDetails(context, style);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_layout_provider.cc | C++ | unknown | 1,449 |
// 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_TEST_TEST_LAYOUT_PROVIDER_H_
#define UI_VIEWS_TEST_TEST_LAYOUT_PROVIDER_H_
#include <map>
#include <utility>
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/typography_provider.h"
namespace views::test {
// Helper to test LayoutProvider overrides.
class TestLayoutProvider : public LayoutProvider, public TypographyProvider {
public:
TestLayoutProvider();
TestLayoutProvider(const TestLayoutProvider&) = delete;
TestLayoutProvider& operator=(const TestLayoutProvider&) = delete;
~TestLayoutProvider() override;
// Override requests for the |metric| DistanceMetric to return |value| rather
// than the default.
void SetDistanceMetric(int metric, int value);
// Override the return value of GetSnappedDialogWidth().
void SetSnappedDialogWidth(int width);
// Override the font details for a given |context| and |style|.
void SetFontDetails(int context,
int style,
const ui::ResourceBundle::FontDetails& details);
// LayoutProvider:
int GetDistanceMetric(int metric) const override;
const TypographyProvider& GetTypographyProvider() const override;
int GetSnappedDialogWidth(int min_width) const override;
// TypographyProvider:
ui::ResourceBundle::FontDetails GetFontDetails(int context,
int style) const override;
private:
std::map<int, int> distance_metrics_;
std::map<std::pair<int, int>, ui::ResourceBundle::FontDetails> details_;
int snapped_dialog_width_ = 0;
};
} // namespace views::test
#endif // UI_VIEWS_TEST_TEST_LAYOUT_PROVIDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_layout_provider.h | C++ | unknown | 1,775 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_TEST_TEST_PLATFORM_NATIVE_WIDGET_H_
#define UI_VIEWS_TEST_TEST_PLATFORM_NATIVE_WIDGET_H_
#include <utility>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "ui/views/view.h"
namespace views {
namespace internal {
class NativeWidgetDelegate;
}
namespace test {
// NativeWidget implementation that adds the following:
// . capture can be mocked.
// . a boolean is set when the NativeWidget is destroyed.
// Don't create directly, instead go through functions in
// native_widget_factory.h that create the appropriate platform specific
// implementation.
template <typename PlatformNativeWidget>
class TestPlatformNativeWidget : public PlatformNativeWidget {
public:
TestPlatformNativeWidget(internal::NativeWidgetDelegate* delegate,
bool mock_capture,
bool* destroyed)
: PlatformNativeWidget(delegate),
mouse_capture_(false),
mock_capture_(mock_capture),
destroyed_(destroyed) {}
TestPlatformNativeWidget(internal::NativeWidgetDelegate* delegate,
bool mock_capture,
base::OnceClosure destroyed_callback)
: PlatformNativeWidget(delegate),
mouse_capture_(false),
mock_capture_(mock_capture),
destroyed_(nullptr),
destroyed_callback_(std::move(destroyed_callback)) {}
TestPlatformNativeWidget(const TestPlatformNativeWidget&) = delete;
TestPlatformNativeWidget& operator=(const TestPlatformNativeWidget&) = delete;
~TestPlatformNativeWidget() override {
if (destroyed_)
*destroyed_ = true;
if (destroyed_callback_)
std::move(destroyed_callback_).Run();
}
// PlatformNativeWidget:
void SetCapture() override {
if (mock_capture_)
mouse_capture_ = true;
else
PlatformNativeWidget::SetCapture();
}
void ReleaseCapture() override {
if (mock_capture_) {
if (mouse_capture_)
PlatformNativeWidget::GetWidget()->OnMouseCaptureLost();
mouse_capture_ = false;
} else {
PlatformNativeWidget::ReleaseCapture();
}
}
bool HasCapture() const override {
return mock_capture_ ? mouse_capture_ : PlatformNativeWidget::HasCapture();
}
private:
bool mouse_capture_;
const bool mock_capture_;
raw_ptr<bool> destroyed_;
base::OnceClosure destroyed_callback_;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_TEST_TEST_PLATFORM_NATIVE_WIDGET_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/test/test_platform_native_widget.h | C++ | unknown | 2,640 |